1mod 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#[derive(Clone, Debug, Eq, PartialEq)]
13pub struct List<T, const N: usize>(Vec<T>);
14impl<T, const N: usize> List<T, N> {
15 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 #[must_use]
25 pub fn as_slice(&self) -> &[T] {
26 &self.0
27 }
28 #[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 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 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 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#[derive(Clone, Debug, Eq, PartialEq)]
100pub struct Bytes<const N: usize>(Vec<u8>);
101impl<const N: usize> Bytes<N> {
102 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 #[must_use]
112 pub fn as_slice(&self) -> &[u8] {
113 &self.0
114 }
115 #[must_use]
117 pub fn as_borrowed(&self) -> BytesRef<'_, N> {
118 BytesRef::from_owned(self)
119 }
120 #[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
137struct 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#[derive(Clone, Debug, Eq, PartialEq)]
162pub struct Text<const N: usize>(String);
163impl<const N: usize> Text<N> {
164 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 #[must_use]
174 pub fn as_str(&self) -> &str {
175 &self.0
176 }
177 #[must_use]
179 pub fn as_borrowed(&self) -> TextRef<'_, N> {
180 TextRef::from_owned(self)
181 }
182 #[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}