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, serde::Serialize)]
16pub struct TypeLink {
17 pub name: &'static str,
19 #[serde(skip)]
21 pub definition: fn() -> &'static TypeSchema,
22}
23impl PartialEq for TypeLink {
24 fn eq(&self, other: &Self) -> bool {
25 self.name == other.name
26 }
27}
28impl Eq for TypeLink {}
29
30#[derive(Debug, PartialEq, Eq, serde::Serialize)]
32pub struct TypeSchema {
33 pub name: &'static str,
35 pub body: TypeBody,
37}
38#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
40pub enum NewtypeRule {
41 NonAnonymous,
43 Text {
45 max_bytes: u32,
47 non_blank: bool,
49 max_chars: Option<u32>,
51 },
52}
53
54impl NewtypeRule {
55 #[must_use]
57 pub const fn primitive(self) -> FieldType {
58 match self {
59 Self::NonAnonymous => FieldType::Principal,
60 Self::Text { max_bytes, .. } => FieldType::Text { max_bytes },
61 }
62 }
63 pub(crate) fn check_text(self, text: &str) -> Result<(), Error> {
64 let mut check = self.text_check().ok_or(Error::InvalidOperand)?;
65 check.segment(text)?;
66 check.finish()
67 }
68
69 pub(crate) fn text_check(self) -> Option<TextCheck> {
70 match self {
71 Self::Text {
72 max_bytes,
73 non_blank,
74 max_chars,
75 } => Some(TextCheck {
76 bytes_left: max_bytes as usize,
77 chars_left: max_chars.filter(|n| *n < max_bytes).map(|n| n as usize),
78 needs_non_blank: non_blank,
79 }),
80 Self::NonAnonymous => None,
81 }
82 }
83}
84
85pub(crate) struct TextCheck {
87 bytes_left: usize,
88 chars_left: Option<usize>,
89 needs_non_blank: bool,
90}
91
92impl TextCheck {
93 pub(crate) fn segment(&mut self, text: &str) -> Result<(), Error> {
94 self.bytes_left = self
95 .bytes_left
96 .checked_sub(text.len())
97 .ok_or(Error::Limit)?;
98 if let Some(left) = &mut self.chars_left {
99 *left = left
100 .checked_sub(text.chars().count())
101 .ok_or(Error::InvalidOperand)?;
102 }
103 if self.needs_non_blank {
105 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));
106 }
107 Ok(())
108 }
109
110 pub(crate) fn finish(self) -> Result<(), Error> {
111 if self.needs_non_blank {
112 Err(Error::InvalidOperand)
113 } else {
114 Ok(())
115 }
116 }
117}
118
119impl FieldType {
120 pub(crate) fn newtype_rule(self) -> Option<NewtypeRule> {
121 if let Self::Named(link) = self
122 && let TypeBody::Checked(rule) = (link.definition)().body
123 {
124 return Some(rule);
125 }
126 None
127 }
128}
129#[derive(Debug, PartialEq, Eq, serde::Serialize)]
131pub enum TypeBody {
132 Wrapped(FieldType),
134 Checked(#[serde(serialize_with = "serialize_checked")] NewtypeRule),
136 Map {
138 key: FieldType,
140 value: ValueSchema,
142 max_items: u32,
144 },
145 Set {
147 item: FieldType,
149 max_items: u32,
151 },
152 Record(&'static [FieldSchema]),
154 Enum(&'static [VariantSchema]),
156}
157fn serialize_checked<S: serde::Serializer>(
159 rule: &NewtypeRule,
160 serializer: S,
161) -> Result<S::Ok, S::Error> {
162 use serde::ser::SerializeStruct;
163 let mut checked = serializer.serialize_struct("Checked", 2)?;
164 checked.serialize_field("primitive", &rule.primitive())?;
165 checked.serialize_field("rule", rule)?;
166 checked.end()
167}
168
169#[derive(Debug, PartialEq, Eq, serde::Serialize)]
171pub struct VariantSchema {
172 pub name: &'static str,
174 pub payload: Option<ValueSchema>,
176}
177
178pub(crate) fn unit_enum_len(definition: &TypeSchema) -> Option<usize> {
181 let TypeBody::Enum(variants) = &definition.body else {
182 return None;
183 };
184
185 (!definition.name.is_empty()
186 && definition.name.len() <= 64
187 && !variants.is_empty()
188 && variants.len() <= 64
189 && variants
190 .iter()
191 .all(|v| v.payload.is_none() && !v.name.is_empty() && v.name.len() <= 64)
192 && variants.windows(2).all(|w| w[0].name < w[1].name))
193 .then_some(variants.len())
194}
195#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
197pub struct ValueSchema {
198 pub value: FieldType,
200 pub optional: bool,
202}
203pub trait Value: Sized {
205 const NAME: &'static str;
207 fn definition() -> &'static TypeSchema;
209
210 #[doc(hidden)]
214 fn encode_into(&self, writer: &mut Encoder) -> Result<(), Error>;
215
216 #[doc(hidden)]
220 fn decode_from(reader: &mut Decoder<'_>) -> Result<Self, Error>;
221}
222
223#[derive(Clone, Default)]
224pub(crate) struct TypeGraph {
225 definitions: BTreeMap<&'static str, &'static TypeSchema>,
226 visited: Vec<&'static TypeSchema>,
229}
230impl TypeGraph {
231 pub fn include(&mut self, value: FieldType) -> Result<(), Error> {
232 let value = if let FieldType::List { item, max_items } = value {
233 if max_items > MAX_COLLECTION_ITEMS as u32 || matches!(item, FieldType::List { .. }) {
234 return Err(Error::InvalidSchema);
235 }
236
237 *item
238 } else {
239 value
240 };
241 let FieldType::Named(link) = value else {
242 return Ok(());
243 };
244 let definition = (link.definition)();
245 if definition.name != link.name {
246 return Err(Error::InvalidSchema);
247 }
248 if self
249 .visited
250 .iter()
251 .any(|seen| std::ptr::eq(*seen, definition))
252 {
253 return Ok(());
254 }
255 if self.visited.len() >= 64 {
256 return Err(Error::InvalidSchema);
257 }
258 self.visited.push(definition);
259 if self
260 .definitions
261 .insert(link.name, definition)
262 .is_some_and(|old| old != definition)
263 || self.definitions.len() > 32
264 {
265 return Err(Error::InvalidSchema);
266 }
267 match &definition.body {
268 TypeBody::Wrapped(FieldType::Named(_)) => return Err(Error::InvalidSchema),
269 TypeBody::Wrapped(value) => self.include(*value)?,
270 TypeBody::Checked(_) => {}
271 TypeBody::Map {
272 key,
273 value,
274 max_items,
275 } => {
276 if *max_items > MAX_COLLECTION_ITEMS as u32 {
277 return Err(Error::InvalidSchema);
278 }
279 self.include_ordered(*key)?;
280 self.include(value.value)?;
281 }
282 TypeBody::Set { item, max_items } => {
283 if *max_items > MAX_COLLECTION_ITEMS as u32 {
284 return Err(Error::InvalidSchema);
285 }
286 self.include_ordered(*item)?;
287 }
288 TypeBody::Record(fields) => {
289 if fields.len() > MAX_FIELDS {
290 return Err(Error::InvalidSchema);
291 }
292 for field in *fields {
293 self.include(field.value)?;
294 }
295 }
296 TypeBody::Enum(variants) => {
297 if variants.len() > 64 {
298 return Err(Error::InvalidSchema);
299 }
300 for variant in *variants {
301 if let Some(payload) = variant.payload {
302 self.include(payload.value)?;
303 }
304 }
305 }
306 }
307
308 Ok(())
309 }
310
311 fn include_ordered(&mut self, value: FieldType) -> Result<(), Error> {
312 match crate::key::operand_type(value) {
313 FieldType::List { .. } => return Err(Error::InvalidSchema),
314 FieldType::Named(link) if unit_enum_len((link.definition)()).is_none() => {
315 return Err(Error::InvalidSchema);
316 }
317 _ => {}
318 }
319
320 self.include(value)
321 }
322
323 pub fn definitions(&self) -> impl Iterator<Item = &'static TypeSchema> + '_ {
324 self.definitions.values().copied()
325 }
326
327 pub fn contains(&self, other: &Self) -> bool {
328 other
329 .definitions
330 .iter()
331 .all(|(name, definition)| self.definitions.get(name) == Some(definition))
332 }
333
334 pub fn encode(&mut self, bytes: &mut Vec<u8>) -> Result<(), Error> {
335 if self.definitions.is_empty() {
336 return Ok(());
337 }
338 bytes.extend(b"ICDBTY02");
339 bytes.extend((MAX_DEPTH as u32).to_le_bytes());
340 bytes.extend((MAX_NODES as u32).to_le_bytes());
341 bytes.extend((self.definitions.len() as u32).to_le_bytes());
342 for definition in self.definitions.values() {
343 let (kind, count) = match &definition.body {
344 TypeBody::Enum(v) => (1, v.len()),
345 TypeBody::Record(f) => (2, f.len()),
346 TypeBody::Set { .. } => (3, 1),
347 TypeBody::Map { .. } => (4, 2),
348 TypeBody::Wrapped(_) => (5, 1),
349 TypeBody::Checked(_) => (6, 1),
350 };
351 bytes.push(kind);
352 name(bytes, definition.name)?;
353 bytes.extend((count as u32).to_le_bytes());
354
355 match &definition.body {
356 TypeBody::Wrapped(value) => encode_type(bytes, *value, false, false)?,
357 TypeBody::Checked(rule) => {
358 encode_type(bytes, rule.primitive(), false, false)?;
359 match rule {
360 NewtypeRule::NonAnonymous => bytes.push(1),
361 NewtypeRule::Text {
362 non_blank,
363 max_chars,
364 ..
365 } => {
366 if !non_blank && max_chars.is_none() {
367 return Err(Error::InvalidSchema);
368 }
369 bytes.extend([2, u8::from(*non_blank), u8::from(max_chars.is_some())]);
370 if let Some(max) = max_chars {
371 bytes.extend(max.to_le_bytes());
372 }
373 }
374 }
375 }
376 TypeBody::Map {
377 key,
378 value,
379 max_items,
380 } => {
381 bytes.extend(max_items.to_le_bytes());
382 bytes.extend((MAX_COLLECTION_ITEMS as u32).to_le_bytes());
383 encode_type(bytes, *key, false, false)?;
384 encode_type(bytes, value.value, value.optional, false)?;
385 }
386 TypeBody::Set { item, max_items } => {
387 bytes.extend(max_items.to_le_bytes());
388 bytes.extend((MAX_COLLECTION_ITEMS as u32).to_le_bytes());
389 encode_type(bytes, *item, false, false)?;
390 }
391 TypeBody::Enum(variants) => {
392 if variants.is_empty()
393 || variants.len() > 64
394 || variants.windows(2).any(|w| w[0].name >= w[1].name)
395 {
396 return Err(Error::InvalidSchema);
397 }
398 for variant in *variants {
399 name(bytes, variant.name)?;
400 bytes.push(u8::from(variant.payload.is_some()));
401 if let Some(payload) = variant.payload {
402 encode_type(bytes, payload.value, payload.optional, false)?;
403 }
404 }
405 }
406 TypeBody::Record(fields) => {
407 if fields.len() > MAX_FIELDS
408 || fields.windows(2).any(|w| w[0].name >= w[1].name)
409 {
410 return Err(Error::InvalidSchema);
411 }
412 for field in *fields {
413 if field.reference.is_some()
414 || field.default.is_some()
415 || field.managed.is_some()
416 {
417 return Err(Error::InvalidSchema);
418 }
419 name(bytes, field.name)?;
420 encode_type(bytes, field.value, field.optional, false)?;
421 }
422 }
423 }
424 }
425 let mut finite = BTreeSet::new();
428 for _ in 0..self.definitions.len() {
429 for (name, definition) in &self.definitions {
430 let viable = |value, optional| {
431 optional
432 || match value {
433 FieldType::Named(link) => finite.contains(link.name),
434 _ => true,
435 }
436 };
437 let has_value = match &definition.body {
438 TypeBody::Wrapped(_)
439 | TypeBody::Checked(_)
440 | TypeBody::Set { .. }
441 | TypeBody::Map { .. } => true,
442 TypeBody::Record(fields) => fields.iter().all(|f| viable(f.value, f.optional)),
443 TypeBody::Enum(variants) => variants
444 .iter()
445 .any(|v| v.payload.is_none_or(|p| viable(p.value, p.optional))),
446 };
447 if has_value {
448 finite.insert(*name);
449 }
450 }
451 }
452 if finite.len() != self.definitions.len() {
453 return Err(Error::InvalidSchema);
454 }
455 self.visited = Vec::new();
456
457 Ok(())
458 }
459}