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