ic_wire/framing.rs
1use crate::Error;
2
3pub(crate) const HEADER_BYTES: usize = 11;
4
5/// Interpretation of the input byte span.
6#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub enum Encoding {
8 /// A Postcard payload without a frame header.
9 Payload,
10 /// An 11-byte Wire header followed by a Postcard payload.
11 Frame {
12 /// Expected routing identity.
13 method: u64,
14 /// Expected request or response direction.
15 direction: Direction,
16 },
17}
18
19/// Direction carried by the last header byte.
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum Direction {
22 /// Request, encoded as zero.
23 Request,
24 /// Response, encoded as one.
25 Response,
26}
27
28pub(crate) fn validate_header(
29 method: u64,
30 direction: Direction,
31 header: &[u8; HEADER_BYTES],
32) -> Result<(), Error> {
33 let direction = match direction {
34 Direction::Request => 0,
35 Direction::Response => 1,
36 };
37 if header[..2] != *b"IW" || header[2..10] != method.to_le_bytes() || header[10] != direction {
38 return Err(Error::Identity);
39 }
40
41 Ok(())
42}
43
44/// Derive a routing ID from the exact exported method name.
45///
46/// Uses FNV-1a-64 over `ic-wire:method:` followed by the name's UTF-8 bytes,
47/// modulo 2^64. No case folding or Unicode normalization is performed.
48/// This is not authentication or a schema fingerprint. Callers must reject
49/// duplicate IDs; explicit IDs remain valid and need not use this derivation.
50#[must_use]
51pub const fn method_id(name: &str) -> u64 {
52 let parts: [&[u8]; 2] = [b"ic-wire:method:", name.as_bytes()];
53 let mut hash = 0xcbf2_9ce4_8422_2325_u64;
54 let mut part = 0;
55 while part < parts.len() {
56 let mut index = 0;
57 while index < parts[part].len() {
58 hash = (hash ^ parts[part][index] as u64).wrapping_mul(0x0100_0000_01b3);
59 index += 1;
60 }
61 part += 1;
62 }
63
64 hash
65}
66
67/// Admit an exact 11-byte request header before copying its payload.
68///
69/// Requires ASCII `IW`, the expected method in little-endian order, and request
70/// direction zero. This allocates nothing and examines no payload bytes.
71/// Success does not authenticate the sender or admit payload resources/schema.
72///
73/// # Errors
74///
75/// Returns [`Error::Identity`] for any marker, method or direction mismatch.
76/// The fixed-size argument excludes truncated headers at this API boundary.
77pub fn validate_request_header(method: u64, header: &[u8; HEADER_BYTES]) -> Result<(), Error> {
78 validate_header(method, Direction::Request, header)
79}