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(Default)]
224pub(crate) struct TypeGraph {
225 definitions: BTreeMap<&'static str, &'static TypeSchema>,
226 visited: BTreeSet<usize>,
229}
230impl TypeGraph {
231 pub fn include(&mut self, value: FieldType) -> Result<(), Error> {
232 let mut pending = Vec::new();
233 let mut first = Some(value);
234 while let Some(value) = first.take().or_else(|| pending.pop()) {
235 let value = if let FieldType::List { item, max_items } = value {
236 if max_items > MAX_COLLECTION_ITEMS as u32 || matches!(item, FieldType::List { .. })
237 {
238 return Err(Error::InvalidSchema);
239 }
240
241 *item
242 } else {
243 value
244 };
245 let FieldType::Named(link) = value else {
246 continue;
247 };
248 let definition = (link.definition)();
249 if definition.name != link.name {
250 return Err(Error::InvalidSchema);
251 }
252 if !self.visited.insert(std::ptr::from_ref(definition).addr()) {
253 continue;
254 }
255 if self
256 .definitions
257 .insert(link.name, definition)
258 .is_some_and(|old| old != definition)
259 {
260 return Err(Error::InvalidSchema);
261 }
262 match &definition.body {
263 TypeBody::Wrapped(FieldType::Named(_)) => return Err(Error::InvalidSchema),
264 TypeBody::Wrapped(value) => pending.push(*value),
265 TypeBody::Checked(_) => {}
266 TypeBody::Map {
267 key,
268 value,
269 max_items,
270 } => {
271 if *max_items > MAX_COLLECTION_ITEMS as u32 {
272 return Err(Error::InvalidSchema);
273 }
274 Self::validate_ordered(*key)?;
275 pending.push(*key);
276 pending.push(value.value);
277 }
278 TypeBody::Set { item, max_items } => {
279 if *max_items > MAX_COLLECTION_ITEMS as u32 {
280 return Err(Error::InvalidSchema);
281 }
282 Self::validate_ordered(*item)?;
283 pending.push(*item);
284 }
285 TypeBody::Record(fields) => {
286 if fields.len() > MAX_FIELDS {
287 return Err(Error::InvalidSchema);
288 }
289 for field in *fields {
290 pending.push(field.value);
291 }
292 }
293 TypeBody::Enum(variants) => {
294 if variants.len() > 64 {
295 return Err(Error::InvalidSchema);
296 }
297 for variant in *variants {
298 if let Some(payload) = variant.payload {
299 pending.push(payload.value);
300 }
301 }
302 }
303 }
304 }
305 Ok(())
306 }
307
308 fn validate_ordered(value: FieldType) -> Result<(), Error> {
309 match crate::key::operand_type(value) {
310 FieldType::List { .. } => return Err(Error::InvalidSchema),
311 FieldType::Named(link) if unit_enum_len((link.definition)()).is_none() => {
312 return Err(Error::InvalidSchema);
313 }
314 _ => {}
315 }
316
317 Ok(())
318 }
319
320 pub fn definitions(&self) -> impl Iterator<Item = &'static TypeSchema> + '_ {
321 self.definitions.values().copied()
322 }
323
324 pub fn contains(&self, other: &Self) -> bool {
325 other
326 .definitions
327 .iter()
328 .all(|(name, definition)| self.definitions.get(name) == Some(definition))
329 }
330
331 pub fn encode(&mut self, bytes: &mut Vec<u8>) -> Result<(), Error> {
332 if self.definitions.is_empty() {
333 return Ok(());
334 }
335 bytes.extend(b"ic-db:named-types\0");
336 bytes.extend((MAX_DEPTH as u32).to_le_bytes());
337 bytes.extend((MAX_NODES as u32).to_le_bytes());
338 let count = u32::try_from(self.definitions.len()).map_err(|_| Error::InvalidSchema)?;
339 bytes.extend(count.to_le_bytes());
340 for definition in self.definitions.values() {
341 let (kind, count) = match &definition.body {
342 TypeBody::Enum(v) => (1, v.len()),
343 TypeBody::Record(f) => (2, f.len()),
344 TypeBody::Set { .. } => (3, 1),
345 TypeBody::Map { .. } => (4, 2),
346 TypeBody::Wrapped(_) => (5, 1),
347 TypeBody::Checked(_) => (6, 1),
348 };
349 bytes.push(kind);
350 name(bytes, definition.name)?;
351 bytes.extend((count as u32).to_le_bytes());
352
353 match &definition.body {
354 TypeBody::Wrapped(value) => encode_type(bytes, *value, false, false)?,
355 TypeBody::Checked(rule) => {
356 encode_type(bytes, rule.primitive(), false, false)?;
357 match rule {
358 NewtypeRule::NonAnonymous => bytes.push(1),
359 NewtypeRule::Text {
360 non_blank,
361 max_chars,
362 max_bytes,
363 } => {
364 if (!non_blank && max_chars.is_none())
365 || (*non_blank && (*max_bytes == 0 || *max_chars == Some(0)))
366 {
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 self.validate_finite()?;
426 self.visited.clear();
427 Ok(())
428 }
429
430 fn validate_finite(&self) -> Result<(), Error> {
431 let mut dependents = BTreeMap::<_, Vec<_>>::new();
432 let mut remaining = BTreeMap::new();
433 let mut ready = Vec::new();
434 for definition in self.definitions() {
435 let mut requires = |value: FieldType, optional: bool| {
437 if let FieldType::Named(link) = value
438 && !optional
439 && matches!(
440 (link.definition)().body,
441 TypeBody::Record(_) | TypeBody::Enum(_)
442 )
443 {
444 dependents
445 .entry(link.name)
446 .or_default()
447 .push(definition.name);
448 true
449 } else {
450 false
451 }
452 };
453 let needed = match definition.body {
455 TypeBody::Record(fields) => fields
456 .iter()
457 .filter(|f| requires(f.value, f.optional))
458 .count(),
459 TypeBody::Enum(variants) => usize::from(
460 variants
461 .iter()
462 .all(|v| v.payload.is_some_and(|p| requires(p.value, p.optional))),
463 ),
464 TypeBody::Wrapped(_)
465 | TypeBody::Checked(_)
466 | TypeBody::Set { .. }
467 | TypeBody::Map { .. } => continue,
468 };
469 if needed == 0 {
470 ready.push(definition.name);
471 } else {
472 remaining.insert(definition.name, needed);
473 }
474 }
475 while let Some(name) = ready.pop() {
476 for parent in dependents.remove(name).into_iter().flatten() {
477 if let std::collections::btree_map::Entry::Occupied(mut entry) =
478 remaining.entry(parent)
479 {
480 *entry.get_mut() -= 1;
481 if *entry.get() == 0 {
482 entry.remove();
483 ready.push(parent);
484 }
485 }
486 }
487 }
488 if remaining.is_empty() {
489 Ok(())
490 } else {
491 Err(Error::InvalidSchema)
492 }
493 }
494}