1use crate::Error;
2
3pub(crate) const HEADER_BYTES: usize = 11;
4
5#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub enum Encoding {
8 Payload,
10 Frame {
12 method: u64,
14 direction: Direction,
16 },
17}
18
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum Direction {
22 Request,
24 Response,
26}
27
28impl Encoding {
29 pub(crate) const fn header_len(self) -> usize {
30 match self {
31 Self::Payload => 0,
32 Self::Frame { .. } => HEADER_BYTES,
33 }
34 }
35
36 pub(crate) fn header(self) -> Option<[u8; HEADER_BYTES]> {
37 match self {
38 Self::Payload => None,
39 Self::Frame { method, direction } => Some(frame_header(method, direction)),
40 }
41 }
42}
43
44fn frame_header(method: u64, direction: Direction) -> [u8; HEADER_BYTES] {
45 let mut header = [0; HEADER_BYTES];
46 header[..2].copy_from_slice(b"IW");
47 header[2..10].copy_from_slice(&method.to_le_bytes());
48 header[10] = match direction {
49 Direction::Request => 0,
50 Direction::Response => 1,
51 };
52 header
53}
54
55pub(crate) fn validate_header(
56 method: u64,
57 direction: Direction,
58 header: &[u8; HEADER_BYTES],
59) -> Result<(), Error> {
60 if *header != frame_header(method, direction) {
61 return Err(Error::Identity);
62 }
63
64 Ok(())
65}
66
67#[must_use]
74pub const fn method_id(name: &str) -> u64 {
75 let parts: [&[u8]; 2] = [b"ic-wire:method:", name.as_bytes()];
76 let mut hash = 0xcbf2_9ce4_8422_2325_u64;
77 let mut part = 0;
78 while part < parts.len() {
79 let mut index = 0;
80 while index < parts[part].len() {
81 hash = (hash ^ parts[part][index] as u64).wrapping_mul(0x0100_0000_01b3);
82 index += 1;
83 }
84 part += 1;
85 }
86
87 hash
88}
89
90pub fn validate_request_header(method: u64, header: &[u8; HEADER_BYTES]) -> Result<(), Error> {
101 validate_header(method, Direction::Request, header)
102}