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