Skip to main content

ic_wire/fields/
mod.rs

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