Skip to main content

ic_wire/bounded/
mod.rs

1mod borrowed;
2pub use borrowed::{BytesRef, TextRef};
3
4use crate::Error;
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}
83
84/// Bounded opaque bytes; consumers validate principal bytes using their existing
85/// principal type. IC Wire defines no new identity type.
86#[derive(Clone, Debug, Eq, PartialEq)]
87pub struct Bytes<const N: usize>(Vec<u8>);
88impl<const N: usize> Bytes<N> {
89    /// Admit bytes without copying.
90    pub fn new(bytes: Vec<u8>) -> Result<Self, Error> {
91        if bytes.len() > N {
92            Err(Error::Limit)
93        } else {
94            Ok(Self(bytes))
95        }
96    }
97    /// Borrow the bytes.
98    pub fn as_slice(&self) -> &[u8] {
99        &self.0
100    }
101    /// Borrow this bounded value without copying or repeating admission.
102    pub fn as_borrowed(&self) -> BytesRef<'_, N> {
103        BytesRef::from_owned(self)
104    }
105    /// Recover the admitted bytes without copying or allocating.
106    pub fn into_vec(self) -> Vec<u8> {
107        self.0
108    }
109}
110impl<const N: usize> Serialize for Bytes<N> {
111    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
112        s.serialize_bytes(&self.0)
113    }
114}
115impl<'de, const N: usize> Deserialize<'de> for Bytes<N> {
116    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
117        struct Visitor<const N: usize>;
118        impl<const N: usize> de::Visitor<'_> for Visitor<N> {
119            type Value = Bytes<N>;
120            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121                f.write_str("bounded bytes")
122            }
123            fn visit_bytes<E: de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
124                if bytes.len() > N {
125                    return Err(E::custom("byte limit"));
126                }
127                let mut out = Vec::new();
128                out.try_reserve_exact(bytes.len())
129                    .map_err(|_| E::custom("allocation"))?;
130                out.extend_from_slice(bytes);
131                Ok(Bytes(out))
132            }
133        }
134        d.deserialize_bytes(Visitor::<N>)
135    }
136}
137
138/// UTF-8 text bounded in bytes.
139#[derive(Clone, Debug, Eq, PartialEq)]
140pub struct Text<const N: usize>(String);
141impl<const N: usize> Text<N> {
142    /// Admit owned text without copying.
143    pub fn new(text: String) -> Result<Self, Error> {
144        if text.len() > N {
145            Err(Error::Limit)
146        } else {
147            Ok(Self(text))
148        }
149    }
150    /// Borrow the text.
151    pub fn as_str(&self) -> &str {
152        &self.0
153    }
154    /// Borrow this bounded value without copying or repeating admission.
155    pub fn as_borrowed(&self) -> TextRef<'_, N> {
156        TextRef::from_owned(self)
157    }
158    /// Recover the admitted text without copying or allocating.
159    pub fn into_string(self) -> String {
160        self.0
161    }
162}
163impl<const N: usize> Serialize for Text<N> {
164    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
165        s.serialize_str(&self.0)
166    }
167}
168impl<'de, const N: usize> Deserialize<'de> for Text<N> {
169    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
170        let bytes = Bytes::<N>::deserialize(d)?;
171        let text = String::from_utf8(bytes.0).map_err(|_| de::Error::custom("invalid UTF-8"))?;
172        Ok(Self(text))
173    }
174}