1use crate::{
4 Error, FieldSchema, FieldType,
5 codec::{Decoder, Encoder},
6 schema::{MAX_FIELDS, encode_type, name},
7};
8use std::collections::{BTreeMap, BTreeSet};
9
10pub(crate) const MAX_DEPTH: usize = 32;
11pub(crate) const MAX_NODES: usize = 256;
12pub(crate) const MAX_COLLECTION_ITEMS: usize = 256;
13
14#[derive(Clone, Copy, Debug)]
16pub struct TypeLink {
17 pub name: &'static str,
19 pub definition: fn() -> &'static TypeSchema,
21}
22impl PartialEq for TypeLink {
23 fn eq(&self, other: &Self) -> bool {
24 self.name == other.name
25 }
26}
27impl Eq for TypeLink {}
28
29#[derive(Debug, PartialEq, Eq)]
31pub struct TypeSchema {
32 pub name: &'static str,
34 pub body: TypeBody,
36}
37#[derive(Debug, PartialEq, Eq)]
39pub enum TypeBody {
40 Wrapped(FieldType),
42 Map {
44 key: FieldType,
46 value: ValueSchema,
48 max_items: u32,
50 },
51 Set {
53 item: FieldType,
55 max_items: u32,
57 },
58 Record(&'static [FieldSchema]),
60 Enum(&'static [VariantSchema]),
62}
63#[derive(Debug, PartialEq, Eq)]
65pub struct VariantSchema {
66 pub name: &'static str,
68 pub payload: Option<ValueSchema>,
70}
71
72pub(crate) fn unit_enum_len(definition: &TypeSchema) -> Option<usize> {
75 let TypeBody::Enum(variants) = &definition.body else {
76 return None;
77 };
78
79 (!definition.name.is_empty()
80 && definition.name.len() <= 64
81 && !variants.is_empty()
82 && variants.len() <= 64
83 && variants
84 .iter()
85 .all(|v| v.payload.is_none() && !v.name.is_empty() && v.name.len() <= 64)
86 && variants.windows(2).all(|w| w[0].name < w[1].name))
87 .then_some(variants.len())
88}
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub struct ValueSchema {
92 pub value: FieldType,
94 pub optional: bool,
96}
97pub trait Value: Sized {
99 const NAME: &'static str;
101 fn definition() -> &'static TypeSchema;
103
104 #[doc(hidden)]
108 fn encode_into(&self, writer: &mut Encoder) -> Result<(), Error>;
109
110 #[doc(hidden)]
114 fn decode_from(reader: &mut Decoder<'_>) -> Result<Self, Error>;
115}
116
117#[derive(Clone, Default)]
118pub(crate) struct TypeGraph {
119 definitions: BTreeMap<&'static str, &'static TypeSchema>,
120 visited: Vec<&'static TypeSchema>,
123}
124impl TypeGraph {
125 pub fn include(&mut self, value: FieldType) -> Result<(), Error> {
126 let value = if let FieldType::List { item, max_items } = value {
127 if max_items > MAX_COLLECTION_ITEMS as u32 || matches!(item, FieldType::List { .. }) {
128 return Err(Error::InvalidSchema);
129 }
130
131 *item
132 } else {
133 value
134 };
135 let FieldType::Named(link) = value else {
136 return Ok(());
137 };
138 let definition = (link.definition)();
139 if definition.name != link.name {
140 return Err(Error::InvalidSchema);
141 }
142 if self
143 .visited
144 .iter()
145 .any(|seen| std::ptr::eq(*seen, definition))
146 {
147 return Ok(());
148 }
149 if self.visited.len() >= 64 {
150 return Err(Error::InvalidSchema);
151 }
152 self.visited.push(definition);
153 if self
154 .definitions
155 .insert(link.name, definition)
156 .is_some_and(|old| old != definition)
157 || self.definitions.len() > 32
158 {
159 return Err(Error::InvalidSchema);
160 }
161 match &definition.body {
162 TypeBody::Wrapped(FieldType::Named(_)) => return Err(Error::InvalidSchema),
163 TypeBody::Wrapped(value) => self.include(*value)?,
164 TypeBody::Map {
165 key,
166 value,
167 max_items,
168 } => {
169 if *max_items > MAX_COLLECTION_ITEMS as u32 {
170 return Err(Error::InvalidSchema);
171 }
172 self.include_ordered(*key)?;
173 self.include(value.value)?;
174 }
175 TypeBody::Set { item, max_items } => {
176 if *max_items > MAX_COLLECTION_ITEMS as u32 {
177 return Err(Error::InvalidSchema);
178 }
179 self.include_ordered(*item)?;
180 }
181 TypeBody::Record(fields) => {
182 if fields.len() > MAX_FIELDS {
183 return Err(Error::InvalidSchema);
184 }
185 for field in *fields {
186 self.include(field.value)?;
187 }
188 }
189 TypeBody::Enum(variants) => {
190 if variants.len() > 64 {
191 return Err(Error::InvalidSchema);
192 }
193 for variant in *variants {
194 if let Some(payload) = variant.payload {
195 self.include(payload.value)?;
196 }
197 }
198 }
199 }
200
201 Ok(())
202 }
203
204 fn include_ordered(&mut self, value: FieldType) -> Result<(), Error> {
205 match crate::key::operand_type(value) {
206 FieldType::List { .. } => return Err(Error::InvalidSchema),
207 FieldType::Named(link) if unit_enum_len((link.definition)()).is_none() => {
208 return Err(Error::InvalidSchema);
209 }
210 _ => {}
211 }
212
213 self.include(value)
214 }
215
216 pub fn definitions(&self) -> impl Iterator<Item = &'static TypeSchema> + '_ {
217 self.definitions.values().copied()
218 }
219
220 pub fn contains(&self, other: &Self) -> bool {
221 other
222 .definitions
223 .iter()
224 .all(|(name, definition)| self.definitions.get(name) == Some(definition))
225 }
226
227 pub fn encode(&mut self, bytes: &mut Vec<u8>) -> Result<(), Error> {
228 if self.definitions.is_empty() {
229 return Ok(());
230 }
231 bytes.extend(b"ICDBTY02");
232 bytes.extend((MAX_DEPTH as u32).to_le_bytes());
233 bytes.extend((MAX_NODES as u32).to_le_bytes());
234 bytes.extend((self.definitions.len() as u32).to_le_bytes());
235 for definition in self.definitions.values() {
236 let (kind, count) = match &definition.body {
237 TypeBody::Enum(v) => (1, v.len()),
238 TypeBody::Record(f) => (2, f.len()),
239 TypeBody::Set { .. } => (3, 1),
240 TypeBody::Map { .. } => (4, 2),
241 TypeBody::Wrapped(_) => (5, 1),
242 };
243 bytes.push(kind);
244 name(bytes, definition.name)?;
245 bytes.extend((count as u32).to_le_bytes());
246
247 match &definition.body {
248 TypeBody::Wrapped(value) => encode_type(bytes, *value, false, false)?,
249 TypeBody::Map {
250 key,
251 value,
252 max_items,
253 } => {
254 bytes.extend(max_items.to_le_bytes());
255 bytes.extend((MAX_COLLECTION_ITEMS as u32).to_le_bytes());
256 encode_type(bytes, *key, false, false)?;
257 encode_type(bytes, value.value, value.optional, false)?;
258 }
259 TypeBody::Set { item, max_items } => {
260 bytes.extend(max_items.to_le_bytes());
261 bytes.extend((MAX_COLLECTION_ITEMS as u32).to_le_bytes());
262 encode_type(bytes, *item, false, false)?;
263 }
264 TypeBody::Enum(variants) => {
265 if variants.is_empty()
266 || variants.len() > 64
267 || variants.windows(2).any(|w| w[0].name >= w[1].name)
268 {
269 return Err(Error::InvalidSchema);
270 }
271 for variant in *variants {
272 name(bytes, variant.name)?;
273 bytes.push(u8::from(variant.payload.is_some()));
274 if let Some(payload) = variant.payload {
275 encode_type(bytes, payload.value, payload.optional, false)?;
276 }
277 }
278 }
279 TypeBody::Record(fields) => {
280 if fields.len() > MAX_FIELDS
281 || fields.windows(2).any(|w| w[0].name >= w[1].name)
282 {
283 return Err(Error::InvalidSchema);
284 }
285 for field in *fields {
286 if field.reference.is_some()
287 || field.default.is_some()
288 || field.managed.is_some()
289 {
290 return Err(Error::InvalidSchema);
291 }
292 name(bytes, field.name)?;
293 encode_type(bytes, field.value, field.optional, false)?;
294 }
295 }
296 }
297 }
298 let mut finite = BTreeSet::new();
301 for _ in 0..self.definitions.len() {
302 for (name, definition) in &self.definitions {
303 let viable = |value, optional| {
304 optional
305 || match value {
306 FieldType::Named(link) => finite.contains(link.name),
307 _ => true,
308 }
309 };
310 let has_value = match &definition.body {
311 TypeBody::Wrapped(_) | TypeBody::Set { .. } | TypeBody::Map { .. } => true,
312 TypeBody::Record(fields) => fields.iter().all(|f| viable(f.value, f.optional)),
313 TypeBody::Enum(variants) => variants
314 .iter()
315 .any(|v| v.payload.is_none_or(|p| viable(p.value, p.optional))),
316 };
317 if has_value {
318 finite.insert(*name);
319 }
320 }
321 }
322 if finite.len() != self.definitions.len() {
323 return Err(Error::InvalidSchema);
324 }
325 self.visited = Vec::new();
326
327 Ok(())
328 }
329}