Skip to main content

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    Ok(())
39}
40
41/// Derive a routing ID from the exact exported method name.
42///
43/// Uses FNV-1a-64 over `ic-wire:method:` followed by the name's UTF-8 bytes,
44/// modulo 2^64. No case folding or Unicode normalization is performed.
45/// This is not authentication or a schema fingerprint. Callers must reject
46/// duplicate IDs; explicit IDs remain valid and need not use this derivation.
47#[must_use]
48pub const fn method_id(name: &str) -> u64 {
49    let parts: [&[u8]; 2] = [b"ic-wire:method:", name.as_bytes()];
50    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
51    let mut part = 0;
52    while part < parts.len() {
53        let mut index = 0;
54        while index < parts[part].len() {
55            hash = (hash ^ parts[part][index] as u64).wrapping_mul(0x0100_0000_01b3);
56            index += 1;
57        }
58        part += 1;
59    }
60    hash
61}
62
63/// Admit an exact 11-byte request header before copying its payload.
64///
65/// Requires ASCII `IW`, the expected method in little-endian order, and request
66/// direction zero. This allocates nothing and examines no payload bytes.
67/// Success does not authenticate the sender or admit payload resources/schema.
68///
69/// # Errors
70///
71/// Returns [`Error::Identity`] for any marker, method or direction mismatch.
72/// The fixed-size argument excludes truncated headers at this API boundary.
73pub fn validate_request_header(method: u64, header: &[u8; 11]) -> Result<(), Error> {
74    validate_header(method, Direction::Request, header)
75}