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