ic-wire 0.34.6

Bounded Serde/Postcard encoding with schema and TypeScript generation
Documentation
use super::*;
use crate::evolution::{
    Projected, decode_projected, encode_projected_into, encode_projected_to_slice, inline::Fixed,
};
use crate::{LimitKind, TextRef};
use serde::{Deserialize, Serialize};

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Request<'a>(#[serde(borrow)] TextRef<'a, 16>);

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Reply(u16);

impl Fixed for Reply {}

impl<'de: 'a, 'a> Evolving<'de> for Request<'a> {
    fn encode_evolving(
        &self,
        output: &mut Vec<u8>,
        encoding: Encoding,
        limits: Limits,
    ) -> Result<(), Error> {
        encode_projected_into(output, encoding, limits, |_| Ok(Projected::empty(self))).map(|_| ())
    }

    fn decode_evolving(
        input: &'de [u8],
        encoding: Encoding,
        limits: Limits,
    ) -> Result<Self, Error> {
        decode_projected(
            input,
            encoding,
            limits,
            |root: Projected<'_, Self>, context| {
                root.extensions.visit(context, |_, _| Ok(()))?;
                Ok(root.core)
            },
        )
    }
}

impl<'de> Evolving<'de> for Reply {
    fn encode_evolving(
        &self,
        output: &mut Vec<u8>,
        encoding: Encoding,
        limits: Limits,
    ) -> Result<(), Error> {
        encode_projected_into(output, encoding, limits, |_| Ok(Projected::empty(self))).map(|_| ())
    }

    fn decode_evolving(
        input: &'de [u8],
        encoding: Encoding,
        limits: Limits,
    ) -> Result<Self, Error> {
        decode_projected(
            input,
            encoding,
            limits,
            |root: Projected<'_, Self>, context| {
                root.extensions.visit(context, |_, _| Ok(()))?;
                Ok(root.core)
            },
        )
    }
}

const REQUEST_LIMITS: Limits = Limits {
    bytes: 64,
    allocation: 4096,
    nodes: 64,
    depth: 16,
};
const REPLY_LIMITS: Limits = Limits {
    bytes: 13,
    ..REQUEST_LIMITS
};
const LOOKUP: Method<Request<'static>, Reply> = Method::new("lookup", REQUEST_LIMITS, REPLY_LIMITS);

#[test]
fn typed_methods_round_trip_borrowed_requests_and_check_identity() {
    assert_eq!(LOOKUP.name(), "lookup");
    assert_eq!(LOOKUP.id(), method_id("lookup"));
    assert_eq!(LOOKUP.request_limits().bytes, 64);
    assert_eq!(LOOKUP.reply_limits().bytes, 13);

    let value = alloc::string::String::from("hello");
    let mut input = Vec::new();
    let method: Method<Request<'_>, Reply> = LOOKUP;
    method
        .encode_request(&Request(TextRef::new(&value).unwrap()), &mut input)
        .unwrap();
    let decoded = method.decode_request(&input).unwrap();
    assert_eq!(decoded.0.as_str(), "hello");
    assert_eq!(decoded.0.as_str().as_bytes().as_ptr(), input[12..].as_ptr());

    let other = Method::<Request<'_>, Reply>::new("other", REQUEST_LIMITS, REPLY_LIMITS);
    assert_eq!(other.decode_request(&input), Err(Error::Identity));
    let mut reply = Vec::new();
    method.encode_reply(&Reply(7), &mut reply).unwrap();
    assert_eq!(reply[10..], [1, 7, 0]);
    assert_eq!(method.decode_reply(&reply), Ok(Reply(7)));
    assert_eq!(method.decode_request(&reply), Err(Error::Identity));
}

#[test]
fn reply_limits_apply_to_both_encoding_and_decoding() {
    let mut reply = alloc::vec![1, 2, 3];
    assert_eq!(
        LOOKUP.encode_reply(&Reply(128), &mut reply),
        Err(Error::Limit(LimitKind::Bytes))
    );
    assert!(reply.is_empty());
    let large = encode(
        &Reply(128),
        Encoding::Frame {
            method: LOOKUP.id(),
            direction: Direction::Response,
        },
        REQUEST_LIMITS,
    )
    .unwrap();
    assert_eq!(
        LOOKUP.decode_reply(&large),
        Err(Error::Limit(LimitKind::Bytes))
    );
}

#[test]
fn fixed_nested_reply_uses_its_explicit_projection_at_the_root() {
    let value = Reply(42);
    let encoding = Encoding::Payload;
    let owned = encode(&value, encoding, REPLY_LIMITS).unwrap();
    let mut output = [0; 2];
    let slice = encode_projected_to_slice(&mut output, encoding, REPLY_LIMITS, |_| {
        Ok(Projected::empty(&value))
    })
    .unwrap();
    assert_eq!(slice, [42, 0]);
    assert_eq!(slice, owned);
    assert_eq!(decode::<Reply>(slice, encoding, REPLY_LIMITS), Ok(value));
}