use crate::Error;
pub(crate) const HEADER_BYTES: usize = 11;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Encoding {
Payload,
Frame {
method: u64,
direction: Direction,
},
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Direction {
Request,
Response,
}
impl Encoding {
pub(crate) const fn header_len(self) -> usize {
match self {
Self::Payload => 0,
Self::Frame { .. } => HEADER_BYTES,
}
}
pub(crate) fn header(self) -> Option<[u8; HEADER_BYTES]> {
match self {
Self::Payload => None,
Self::Frame { method, direction } => Some(frame_header(method, direction)),
}
}
}
fn frame_header(method: u64, direction: Direction) -> [u8; HEADER_BYTES] {
let mut header = [0; HEADER_BYTES];
header[..2].copy_from_slice(b"IW");
header[2..10].copy_from_slice(&method.to_le_bytes());
header[10] = match direction {
Direction::Request => 0,
Direction::Response => 1,
};
header
}
pub(crate) fn validate_header(
method: u64,
direction: Direction,
header: &[u8; HEADER_BYTES],
) -> Result<(), Error> {
if *header != frame_header(method, direction) {
return Err(Error::Identity);
}
Ok(())
}
#[must_use]
pub const fn method_id(name: &str) -> u64 {
let parts: [&[u8]; 2] = [b"ic-wire:method:", name.as_bytes()];
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
let mut part = 0;
while part < parts.len() {
let mut index = 0;
while index < parts[part].len() {
hash = (hash ^ parts[part][index] as u64).wrapping_mul(0x0100_0000_01b3);
index += 1;
}
part += 1;
}
hash
}
pub fn validate_request_header(method: u64, header: &[u8; HEADER_BYTES]) -> Result<(), Error> {
validate_header(method, Direction::Request, header)
}