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