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}
157
158impl TypeBody {
159 pub(crate) fn is_transparent_wrapper(&self) -> bool {
160 matches!(self, Self::Wrapped(_) | Self::Checked(_))
161 }
162}
163
164fn serialize_checked<S: serde::Serializer>(
166 rule: &NewtypeRule,
167 serializer: S,
168) -> Result<S::Ok, S::Error> {
169 use serde::ser::SerializeStruct;
170 let mut checked = serializer.serialize_struct("Checked", 2)?;
171 checked.serialize_field("primitive", &rule.primitive())?;
172 checked.serialize_field("rule", rule)?;
173 checked.end()
174}
175
176#[derive(Debug, PartialEq, Eq, serde::Serialize)]
178pub struct VariantSchema {
179 pub name: &'static str,
181 pub payload: Option<ValueSchema>,
183}
184
185fn valid_variants(variants: &[VariantSchema]) -> bool {
186 (1..=64).contains(&variants.len())
187 && variants.iter().all(|v| (1..=64).contains(&v.name.len()))
188 && variants.windows(2).all(|w| w[0].name < w[1].name)
189}
190
191pub(crate) fn unit_enum_len(definition: &TypeSchema) -> Option<usize> {
194 let TypeBody::Enum(variants) = &definition.body else {
195 return None;
196 };
197
198 (!definition.name.is_empty()
199 && definition.name.len() <= 64
200 && valid_variants(variants)
201 && variants.iter().all(|v| v.payload.is_none()))
202 .then_some(variants.len())
203}
204#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
206pub struct ValueSchema {
207 pub value: FieldType,
209 pub optional: bool,
211}
212pub trait Value: Sized {
214 const NAME: &'static str;
216 fn definition() -> &'static TypeSchema;
218
219 #[doc(hidden)]
223 fn encode_into(&self, writer: &mut Encoder) -> Result<(), Error>;
224
225 #[doc(hidden)]
229 fn decode_from(reader: &mut Decoder<'_>) -> Result<Self, Error>;
230}
231
232#[derive(Default)]
233pub(crate) struct TypeGraph {
234 definitions: BTreeMap<&'static str, &'static TypeSchema>,
235 visited: BTreeSet<usize>,
238}
239impl TypeGraph {
240 pub fn include(&mut self, value: FieldType) -> Result<(), Error> {
241 let mut pending = Vec::new();
242 let mut first = Some(value);
243 while let Some(value) = first.take().or_else(|| pending.pop()) {
244 let value = if let FieldType::List { item, max_items } = value {
245 if max_items > MAX_COLLECTION_ITEMS as u32 || matches!(item, FieldType::List { .. })
246 {
247 return Err(Error::InvalidSchema);
248 }
249
250 *item
251 } else {
252 value
253 };
254 let FieldType::Named(link) = value else {
255 continue;
256 };
257 let definition = (link.definition)();
258 if definition.name != link.name {
259 return Err(Error::InvalidSchema);
260 }
261 if !self.visited.insert(std::ptr::from_ref(definition).addr()) {
262 continue;
263 }
264 if self
265 .definitions
266 .insert(link.name, definition)
267 .is_some_and(|old| old != definition)
268 {
269 return Err(Error::InvalidSchema);
270 }
271 match &definition.body {
272 TypeBody::Wrapped(FieldType::Named(_)) => return Err(Error::InvalidSchema),
273 TypeBody::Wrapped(value) => pending.push(*value),
274 TypeBody::Checked(_) => {}
275 TypeBody::Map {
276 key,
277 value,
278 max_items,
279 } => {
280 if *max_items > MAX_COLLECTION_ITEMS as u32 {
281 return Err(Error::InvalidSchema);
282 }
283 Self::validate_ordered(*key)?;
284 pending.push(*key);
285 pending.push(value.value);
286 }
287 TypeBody::Set { item, max_items } => {
288 if *max_items > MAX_COLLECTION_ITEMS as u32 {
289 return Err(Error::InvalidSchema);
290 }
291 Self::validate_ordered(*item)?;
292 pending.push(*item);
293 }
294 TypeBody::Record(fields) => {
295 if fields.len() > MAX_FIELDS {
296 return Err(Error::InvalidSchema);
297 }
298 for field in *fields {
299 pending.push(field.value);
300 }
301 }
302 TypeBody::Enum(variants) => {
303 if variants.len() > 64 {
304 return Err(Error::InvalidSchema);
305 }
306 for variant in *variants {
307 if let Some(payload) = variant.payload {
308 pending.push(payload.value);
309 }
310 }
311 }
312 }
313 }
314 Ok(())
315 }
316
317 fn validate_ordered(value: FieldType) -> Result<(), Error> {
318 match crate::key::operand_type(value) {
319 FieldType::List { .. } => return Err(Error::InvalidSchema),
320 FieldType::Named(link) if unit_enum_len((link.definition)()).is_none() => {
321 return Err(Error::InvalidSchema);
322 }
323 _ => {}
324 }
325
326 Ok(())
327 }
328
329 pub fn definitions(&self) -> impl Iterator<Item = &'static TypeSchema> + '_ {
330 self.definitions.values().copied()
331 }
332
333 pub fn contains(&self, other: &Self) -> bool {
334 other
335 .definitions
336 .iter()
337 .all(|(name, definition)| self.definitions.get(name) == Some(definition))
338 }
339
340 pub fn encode(&mut self, bytes: &mut Vec<u8>) -> Result<(), Error> {
341 if self.definitions.is_empty() {
342 return Ok(());
343 }
344 bytes.extend(b"ic-db:named-types\0");
345 bytes.extend((MAX_DEPTH as u32).to_le_bytes());
346 bytes.extend((MAX_NODES as u32).to_le_bytes());
347 let count = u32::try_from(self.definitions.len()).map_err(|_| Error::InvalidSchema)?;
348 bytes.extend(count.to_le_bytes());
349 for definition in self.definitions.values() {
350 let (kind, count) = match &definition.body {
351 TypeBody::Enum(v) => (1, v.len()),
352 TypeBody::Record(f) => (2, f.len()),
353 TypeBody::Set { .. } => (3, 1),
354 TypeBody::Map { .. } => (4, 2),
355 TypeBody::Wrapped(_) => (5, 1),
356 TypeBody::Checked(_) => (6, 1),
357 };
358 bytes.push(kind);
359 name(bytes, definition.name)?;
360 bytes.extend((count as u32).to_le_bytes());
361
362 match &definition.body {
363 TypeBody::Wrapped(value) => encode_type(bytes, *value, false, false)?,
364 TypeBody::Checked(rule) => {
365 encode_type(bytes, rule.primitive(), false, false)?;
366 match rule {
367 NewtypeRule::NonAnonymous => bytes.push(1),
368 NewtypeRule::Text {
369 non_blank,
370 max_chars,
371 max_bytes,
372 } => {
373 if (!non_blank && max_chars.is_none())
374 || (*non_blank && (*max_bytes == 0 || *max_chars == Some(0)))
375 {
376 return Err(Error::InvalidSchema);
377 }
378 bytes.extend([2, u8::from(*non_blank), u8::from(max_chars.is_some())]);
379 if let Some(max) = max_chars {
380 bytes.extend(max.to_le_bytes());
381 }
382 }
383 }
384 }
385 TypeBody::Map {
386 key,
387 value,
388 max_items,
389 } => {
390 bytes.extend(max_items.to_le_bytes());
391 bytes.extend((MAX_COLLECTION_ITEMS as u32).to_le_bytes());
392 encode_type(bytes, *key, false, false)?;
393 encode_type(bytes, value.value, value.optional, false)?;
394 }
395 TypeBody::Set { item, max_items } => {
396 bytes.extend(max_items.to_le_bytes());
397 bytes.extend((MAX_COLLECTION_ITEMS as u32).to_le_bytes());
398 encode_type(bytes, *item, false, false)?;
399 }
400 TypeBody::Enum(variants) => {
401 if !valid_variants(variants) {
402 return Err(Error::InvalidSchema);
403 }
404 for variant in *variants {
405 name(bytes, variant.name)?;
406 bytes.push(u8::from(variant.payload.is_some()));
407 if let Some(payload) = variant.payload {
408 encode_type(bytes, payload.value, payload.optional, false)?;
409 }
410 }
411 }
412 TypeBody::Record(fields) => {
413 if fields.len() > MAX_FIELDS
414 || fields.windows(2).any(|w| w[0].name >= w[1].name)
415 {
416 return Err(Error::InvalidSchema);
417 }
418 for field in *fields {
419 if field.reference.is_some()
420 || field.default.is_some()
421 || field.managed.is_some()
422 {
423 return Err(Error::InvalidSchema);
424 }
425 name(bytes, field.name)?;
426 encode_type(bytes, field.value, field.optional, false)?;
427 }
428 }
429 }
430 }
431 self.validate_finite()?;
432 self.visited.clear();
433 Ok(())
434 }
435
436 fn validate_finite(&self) -> Result<(), Error> {
437 let mut dependents = BTreeMap::<_, Vec<_>>::new();
438 let mut remaining = BTreeMap::new();
439 let mut ready = Vec::new();
440 for definition in self.definitions() {
441 let mut requires = |value: FieldType, optional: bool| {
443 if let FieldType::Named(link) = value
444 && !optional
445 && matches!(
446 (link.definition)().body,
447 TypeBody::Record(_) | TypeBody::Enum(_)
448 )
449 {
450 dependents
451 .entry(link.name)
452 .or_default()
453 .push(definition.name);
454 true
455 } else {
456 false
457 }
458 };
459 let needed = match definition.body {
461 TypeBody::Record(fields) => fields
462 .iter()
463 .filter(|f| requires(f.value, f.optional))
464 .count(),
465 TypeBody::Enum(variants) => usize::from(
466 variants
467 .iter()
468 .all(|v| v.payload.is_some_and(|p| requires(p.value, p.optional))),
469 ),
470 TypeBody::Wrapped(_)
471 | TypeBody::Checked(_)
472 | TypeBody::Set { .. }
473 | TypeBody::Map { .. } => continue,
474 };
475 if needed == 0 {
476 ready.push(definition.name);
477 } else {
478 remaining.insert(definition.name, needed);
479 }
480 }
481 while let Some(name) = ready.pop() {
482 for parent in dependents.remove(name).into_iter().flatten() {
483 if let std::collections::btree_map::Entry::Occupied(mut entry) =
484 remaining.entry(parent)
485 {
486 *entry.get_mut() -= 1;
487 if *entry.get() == 0 {
488 entry.remove();
489 ready.push(parent);
490 }
491 }
492 }
493 }
494 if remaining.is_empty() {
495 Ok(())
496 } else {
497 Err(Error::InvalidSchema)
498 }
499 }
500}