Skip to main content

ic_wire/bounded/
mod.rs

1mod borrowed;
2pub use borrowed::{BytesRef, TextRef};
3
4use crate::{Error, Shape, Wire};
5use alloc::{string::String, vec::Vec};
6use core::fmt;
7use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
8
9/// A sequence with a compile-time element bound.
10#[derive(Clone, Debug, Eq, PartialEq)]
11pub struct List<T, const N: usize>(Vec<T>);
12impl<T, const N: usize> List<T, N> {
13    /// Admit an owned sequence without copying.
14    pub fn new(values: Vec<T>) -> Result<Self, Error> {
15        if values.len() > N {
16            Err(Error::Limit)
17        } else {
18            Ok(Self(values))
19        }
20    }
21    /// Borrow the elements.
22    pub fn as_slice(&self) -> &[T] {
23        &self.0
24    }
25    /// Recover the admitted sequence.
26    pub fn into_vec(self) -> Vec<T> {
27        self.0
28    }
29}
30impl<T: Serialize, const N: usize> Serialize for List<T, N> {
31    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
32        self.0.serialize(s)
33    }
34}
35impl<'de, T: Deserialize<'de>, const N: usize> Deserialize<'de> for List<T, N> {
36    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
37        struct Visitor<T, const N: usize>(core::marker::PhantomData<T>);
38        impl<'de, T: Deserialize<'de>, const N: usize> de::Visitor<'de> for Visitor<T, N> {
39            type Value = List<T, N>;
40            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41                f.write_str("bounded sequence")
42            }
43            fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
44                // Postcard hides its count when remaining bytes are fewer than
45                // elements (including legitimate unit values). Bound both paths.
46                let count = seq.size_hint();
47                if count.is_some_and(|count| count > N) {
48                    return Err(de::Error::custom("element limit"));
49                }
50                let mut values = Vec::new();
51                values
52                    .try_reserve_exact(count.unwrap_or(0))
53                    .map_err(|_| de::Error::custom("allocation"))?;
54                for _ in 0..N {
55                    let Some(value) = seq.next_element()? else {
56                        return Ok(List(values));
57                    };
58                    if values.len() == values.capacity() {
59                        // Hidden lengths need amortized growth, capped by the
60                        // declared element bound rather than Vec's growth policy.
61                        let next = values.len().saturating_mul(2).max(1).min(N);
62                        values
63                            .try_reserve_exact(next - values.len())
64                            .map_err(|_| de::Error::custom("allocation"))?;
65                    }
66                    values.push(value);
67                }
68                // Detect an excess element without invoking its decoder.
69                struct Reject;
70                impl<'de> de::DeserializeSeed<'de> for Reject {
71                    type Value = ();
72                    fn deserialize<D: Deserializer<'de>>(self, _: D) -> Result<(), D::Error> {
73                        Err(de::Error::custom("element limit"))
74                    }
75                }
76                seq.next_element_seed(Reject)?;
77                Ok(List(values))
78            }
79        }
80        d.deserialize_seq(Visitor::<T, N>(core::marker::PhantomData))
81    }
82}
83impl<T: Wire, const N: usize> Wire for List<T, N> {
84    const __CANONICAL_FIELDS: bool = T::__CANONICAL_FIELDS;
85    const SCHEMA: crate::schema::Schema = crate::schema::Schema::List(&T::SCHEMA, N);
86    const SHAPE: Shape = Shape {
87        bytes: 10_usize.saturating_add(T::SHAPE.bytes.saturating_mul(N)),
88        heap: N.saturating_mul(core::mem::size_of::<T>().saturating_add(T::SHAPE.heap)),
89        nodes: 1_usize.saturating_add(N.saturating_mul(T::SHAPE.nodes)),
90        depth: T::SHAPE.depth.saturating_add(1),
91    };
92}
93
94/// Bounded opaque bytes; consumers validate principal bytes using their existing
95/// principal type. IC Wire defines no new identity type.
96#[derive(Clone, Debug, Eq, PartialEq)]
97pub struct Bytes<const N: usize>(Vec<u8>);
98impl<const N: usize> Bytes<N> {
99    /// Admit bytes without copying.
100    pub fn new(bytes: Vec<u8>) -> Result<Self, Error> {
101        if bytes.len() > N {
102            Err(Error::Limit)
103        } else {
104            Ok(Self(bytes))
105        }
106    }
107    /// Borrow the bytes.
108    pub fn as_slice(&self) -> &[u8] {
109        &self.0
110    }
111    /// Borrow this bounded value without copying or repeating admission.
112    pub fn as_borrowed(&self) -> BytesRef<'_, N> {
113        BytesRef::from_owned(self)
114    }
115    /// Recover the admitted bytes without copying or allocating.
116    pub fn into_vec(self) -> Vec<u8> {
117        self.0
118    }
119}
120impl<const N: usize> Serialize for Bytes<N> {
121    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
122        s.serialize_bytes(&self.0)
123    }
124}
125impl<'de, const N: usize> Deserialize<'de> for Bytes<N> {
126    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
127        struct Visitor<const N: usize>;
128        impl<const N: usize> de::Visitor<'_> for Visitor<N> {
129            type Value = Bytes<N>;
130            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131                f.write_str("bounded bytes")
132            }
133            fn visit_bytes<E: de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
134                if bytes.len() > N {
135                    return Err(E::custom("byte limit"));
136                }
137                let mut out = Vec::new();
138                out.try_reserve_exact(bytes.len())
139                    .map_err(|_| E::custom("allocation"))?;
140                out.extend_from_slice(bytes);
141                Ok(Bytes(out))
142            }
143        }
144        d.deserialize_bytes(Visitor::<N>)
145    }
146}
147impl<const N: usize> Wire for Bytes<N> {
148    const __CANONICAL_FIELDS: bool = true;
149    fn __canonical(&self, canonical: &mut crate::__private::Canonical<'_>) -> Result<(), Error> {
150        canonical.copied_bytes(self.0.len())
151    }
152
153    const SCHEMA: crate::schema::Schema = crate::schema::Schema::Bytes(N);
154    const SHAPE: Shape = Shape {
155        bytes: N.saturating_add(10),
156        heap: N,
157        nodes: 1,
158        depth: 1,
159    };
160}
161
162/// UTF-8 text bounded in bytes.
163#[derive(Clone, Debug, Eq, PartialEq)]
164pub struct Text<const N: usize>(String);
165impl<const N: usize> Text<N> {
166    /// Admit owned text without copying.
167    pub fn new(text: String) -> Result<Self, Error> {
168        if text.len() > N {
169            Err(Error::Limit)
170        } else {
171            Ok(Self(text))
172        }
173    }
174    /// Borrow the text.
175    pub fn as_str(&self) -> &str {
176        &self.0
177    }
178    /// Borrow this bounded value without copying or repeating admission.
179    pub fn as_borrowed(&self) -> TextRef<'_, N> {
180        TextRef::from_owned(self)
181    }
182    /// Recover the admitted text without copying or allocating.
183    pub fn into_string(self) -> String {
184        self.0
185    }
186}
187impl<const N: usize> Serialize for Text<N> {
188    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
189        s.serialize_str(&self.0)
190    }
191}
192impl<'de, const N: usize> Deserialize<'de> for Text<N> {
193    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
194        let bytes = Bytes::<N>::deserialize(d)?;
195        let text = String::from_utf8(bytes.0).map_err(|_| de::Error::custom("invalid UTF-8"))?;
196        Ok(Self(text))
197    }
198}
199impl<const N: usize> Wire for Text<N> {
200    const __CANONICAL_FIELDS: bool = true;
201    const SCHEMA: crate::schema::Schema = crate::schema::Schema::Text(N);
202    const SHAPE: Shape = Bytes::<N>::SHAPE;
203}