Skip to main content

ic_wire/bounded/
mod.rs

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