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(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum NewtypeRule {
40 NonAnonymous,
42 Text {
44 max_bytes: u32,
46 non_blank: bool,
48 max_chars: Option<u32>,
50 },
51}
52
53impl NewtypeRule {
54 #[must_use]
56 pub const fn primitive(self) -> FieldType {
57 match self {
58 Self::NonAnonymous => FieldType::Principal,
59 Self::Text { max_bytes, .. } => FieldType::Text { max_bytes },
60 }
61 }
62 pub(crate) fn check_text(self, text: &str) -> Result<(), Error> {
63 let mut check = self.text_check().ok_or(Error::InvalidOperand)?;
64 check.segment(text)?;
65 check.finish()
66 }
67
68 pub(crate) fn text_check(self) -> Option<TextCheck> {
69 match self {
70 Self::Text {
71 max_bytes,
72 non_blank,
73 max_chars,
74 } => Some(TextCheck {
75 bytes_left: max_bytes as usize,
76 chars_left: max_chars.filter(|n| *n < max_bytes).map(|n| n as usize),
77 needs_non_blank: non_blank,
78 }),
79 Self::NonAnonymous => None,
80 }
81 }
82}
83
84pub(crate) struct TextCheck {
86 bytes_left: usize,
87 chars_left: Option<usize>,
88 needs_non_blank: bool,
89}
90
91impl TextCheck {
92 pub(crate) fn segment(&mut self, text: &str) -> Result<(), Error> {
93 self.bytes_left = self
94 .bytes_left
95 .checked_sub(text.len())
96 .ok_or(Error::Limit)?;
97 if let Some(left) = &mut self.chars_left {
98 *left = left
99 .checked_sub(text.chars().count())
100 .ok_or(Error::InvalidOperand)?;
101 }
102 if self.needs_non_blank {
104 self.needs_non_blank = text.chars().all(|c| matches!(c as u32, 0x09..=0x0d | 0x20 | 0x85 | 0xa0 | 0x1680 | 0x2000..=0x200a | 0x2028..=0x2029 | 0x202f | 0x205f | 0x3000));
105 }
106 Ok(())
107 }
108
109 pub(crate) fn finish(self) -> Result<(), Error> {
110 if self.needs_non_blank {
111 Err(Error::InvalidOperand)
112 } else {
113 Ok(())
114 }
115 }
116}
117
118impl FieldType {
119 pub(crate) fn newtype_rule(self) -> Option<NewtypeRule> {
120 if let Self::Named(link) = self
121 && let TypeBody::Checked(rule) = (link.definition)().body
122 {
123 return Some(rule);
124 }
125 None
126 }
127}
128#[derive(Debug, PartialEq, Eq)]
130pub enum TypeBody {
131 Wrapped(FieldType),
133 Checked(NewtypeRule),
135 Map {
137 key: FieldType,
139 value: ValueSchema,
141 max_items: u32,
143 },
144 Set {
146 item: FieldType,
148 max_items: u32,
150 },
151 Record(&'static [FieldSchema]),
153 Enum(&'static [VariantSchema]),
155}
156#[derive(Debug, PartialEq, Eq)]
158pub struct VariantSchema {
159 pub name: &'static str,
161 pub payload: Option<ValueSchema>,
163}
164
165pub(crate) fn unit_enum_len(definition: &TypeSchema) -> Option<usize> {
168 let TypeBody::Enum(variants) = &definition.body else {
169 return None;
170 };
171
172 (!definition.name.is_empty()
173 && definition.name.len() <= 64
174 && !variants.is_empty()
175 && variants.len() <= 64
176 && variants
177 .iter()
178 .all(|v| v.payload.is_none() && !v.name.is_empty() && v.name.len() <= 64)
179 && variants.windows(2).all(|w| w[0].name < w[1].name))
180 .then_some(variants.len())
181}
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub struct ValueSchema {
185 pub value: FieldType,
187 pub optional: bool,
189}
190pub trait Value: Sized {
192 const NAME: &'static str;
194 fn definition() -> &'static TypeSchema;
196
197 #[doc(hidden)]
201 fn encode_into(&self, writer: &mut Encoder) -> Result<(), Error>;
202
203 #[doc(hidden)]
207 fn decode_from(reader: &mut Decoder<'_>) -> Result<Self, Error>;
208}
209
210#[derive(Clone, Default)]
211pub(crate) struct TypeGraph {
212 definitions: BTreeMap<&'static str, &'static TypeSchema>,
213 visited: Vec<&'static TypeSchema>,
216}
217impl TypeGraph {
218 pub fn include(&mut self, value: FieldType) -> Result<(), Error> {
219 let value = if let FieldType::List { item, max_items } = value {
220 if max_items > MAX_COLLECTION_ITEMS as u32 || matches!(item, FieldType::List { .. }) {
221 return Err(Error::InvalidSchema);
222 }
223
224 *item
225 } else {
226 value
227 };
228 let FieldType::Named(link) = value else {
229 return Ok(());
230 };
231 let definition = (link.definition)();
232 if definition.name != link.name {
233 return Err(Error::InvalidSchema);
234 }
235 if self
236 .visited
237 .iter()
238 .any(|seen| std::ptr::eq(*seen, definition))
239 {
240 return Ok(());
241 }
242 if self.visited.len() >= 64 {
243 return Err(Error::InvalidSchema);
244 }
245 self.visited.push(definition);
246 if self
247 .definitions
248 .insert(link.name, definition)
249 .is_some_and(|old| old != definition)
250 || self.definitions.len() > 32
251 {
252 return Err(Error::InvalidSchema);
253 }
254 match &definition.body {
255 TypeBody::Wrapped(FieldType::Named(_)) => return Err(Error::InvalidSchema),
256 TypeBody::Wrapped(value) => self.include(*value)?,
257 TypeBody::Checked(_) => {}
258 TypeBody::Map {
259 key,
260 value,
261 max_items,
262 } => {
263 if *max_items > MAX_COLLECTION_ITEMS as u32 {
264 return Err(Error::InvalidSchema);
265 }
266 self.include_ordered(*key)?;
267 self.include(value.value)?;
268 }
269 TypeBody::Set { item, max_items } => {
270 if *max_items > MAX_COLLECTION_ITEMS as u32 {
271 return Err(Error::InvalidSchema);
272 }
273 self.include_ordered(*item)?;
274 }
275 TypeBody::Record(fields) => {
276 if fields.len() > MAX_FIELDS {
277 return Err(Error::InvalidSchema);
278 }
279 for field in *fields {
280 self.include(field.value)?;
281 }
282 }
283 TypeBody::Enum(variants) => {
284 if variants.len() > 64 {
285 return Err(Error::InvalidSchema);
286 }
287 for variant in *variants {
288 if let Some(payload) = variant.payload {
289 self.include(payload.value)?;
290 }
291 }
292 }
293 }
294
295 Ok(())
296 }
297
298 fn include_ordered(&mut self, value: FieldType) -> Result<(), Error> {
299 match crate::key::operand_type(value) {
300 FieldType::List { .. } => return Err(Error::InvalidSchema),
301 FieldType::Named(link) if unit_enum_len((link.definition)()).is_none() => {
302 return Err(Error::InvalidSchema);
303 }
304 _ => {}
305 }
306
307 self.include(value)
308 }
309
310 pub fn definitions(&self) -> impl Iterator<Item = &'static TypeSchema> + '_ {
311 self.definitions.values().copied()
312 }
313
314 pub fn contains(&self, other: &Self) -> bool {
315 other
316 .definitions
317 .iter()
318 .all(|(name, definition)| self.definitions.get(name) == Some(definition))
319 }
320
321 pub fn encode(&mut self, bytes: &mut Vec<u8>) -> Result<(), Error> {
322 if self.definitions.is_empty() {
323 return Ok(());
324 }
325 bytes.extend(b"ICDBTY02");
326 bytes.extend((MAX_DEPTH as u32).to_le_bytes());
327 bytes.extend((MAX_NODES as u32).to_le_bytes());
328 bytes.extend((self.definitions.len() as u32).to_le_bytes());
329 for definition in self.definitions.values() {
330 let (kind, count) = match &definition.body {
331 TypeBody::Enum(v) => (1, v.len()),
332 TypeBody::Record(f) => (2, f.len()),
333 TypeBody::Set { .. } => (3, 1),
334 TypeBody::Map { .. } => (4, 2),
335 TypeBody::Wrapped(_) => (5, 1),
336 TypeBody::Checked(_) => (6, 1),
337 };
338 bytes.push(kind);
339 name(bytes, definition.name)?;
340 bytes.extend((count as u32).to_le_bytes());
341
342 match &definition.body {
343 TypeBody::Wrapped(value) => encode_type(bytes, *value, false, false)?,
344 TypeBody::Checked(rule) => {
345 encode_type(bytes, rule.primitive(), false, false)?;
346 match rule {
347 NewtypeRule::NonAnonymous => bytes.push(1),
348 NewtypeRule::Text {
349 non_blank,
350 max_chars,
351 ..
352 } => {
353 if !non_blank && max_chars.is_none() {
354 return Err(Error::InvalidSchema);
355 }
356 bytes.extend([2, u8::from(*non_blank), u8::from(max_chars.is_some())]);
357 if let Some(max) = max_chars {
358 bytes.extend(max.to_le_bytes());
359 }
360 }
361 }
362 }
363 TypeBody::Map {
364 key,
365 value,
366 max_items,
367 } => {
368 bytes.extend(max_items.to_le_bytes());
369 bytes.extend((MAX_COLLECTION_ITEMS as u32).to_le_bytes());
370 encode_type(bytes, *key, false, false)?;
371 encode_type(bytes, value.value, value.optional, false)?;
372 }
373 TypeBody::Set { item, max_items } => {
374 bytes.extend(max_items.to_le_bytes());
375 bytes.extend((MAX_COLLECTION_ITEMS as u32).to_le_bytes());
376 encode_type(bytes, *item, false, false)?;
377 }
378 TypeBody::Enum(variants) => {
379 if variants.is_empty()
380 || variants.len() > 64
381 || variants.windows(2).any(|w| w[0].name >= w[1].name)
382 {
383 return Err(Error::InvalidSchema);
384 }
385 for variant in *variants {
386 name(bytes, variant.name)?;
387 bytes.push(u8::from(variant.payload.is_some()));
388 if let Some(payload) = variant.payload {
389 encode_type(bytes, payload.value, payload.optional, false)?;
390 }
391 }
392 }
393 TypeBody::Record(fields) => {
394 if fields.len() > MAX_FIELDS
395 || fields.windows(2).any(|w| w[0].name >= w[1].name)
396 {
397 return Err(Error::InvalidSchema);
398 }
399 for field in *fields {
400 if field.reference.is_some()
401 || field.default.is_some()
402 || field.managed.is_some()
403 {
404 return Err(Error::InvalidSchema);
405 }
406 name(bytes, field.name)?;
407 encode_type(bytes, field.value, field.optional, false)?;
408 }
409 }
410 }
411 }
412 let mut finite = BTreeSet::new();
415 for _ in 0..self.definitions.len() {
416 for (name, definition) in &self.definitions {
417 let viable = |value, optional| {
418 optional
419 || match value {
420 FieldType::Named(link) => finite.contains(link.name),
421 _ => true,
422 }
423 };
424 let has_value = match &definition.body {
425 TypeBody::Wrapped(_)
426 | TypeBody::Checked(_)
427 | TypeBody::Set { .. }
428 | TypeBody::Map { .. } => true,
429 TypeBody::Record(fields) => fields.iter().all(|f| viable(f.value, f.optional)),
430 TypeBody::Enum(variants) => variants
431 .iter()
432 .any(|v| v.payload.is_none_or(|p| viable(p.value, p.optional))),
433 };
434 if has_value {
435 finite.insert(*name);
436 }
437 }
438 }
439 if finite.len() != self.definitions.len() {
440 return Err(Error::InvalidSchema);
441 }
442 self.visited = Vec::new();
443
444 Ok(())
445 }
446}