Skip to main content

ic_db/
schema.rs

1//! One compiled contract, canonical fingerprint and inspection projection.
2
3use crate::{
4    __private::RowInfo,
5    Error, IndexValue,
6    codec::Decoder,
7    key,
8    primary::RowKey,
9    types::{TypeGraph, TypeLink},
10};
11use sha2::{Digest, Sha256};
12use std::collections::BTreeSet;
13
14/// Verify producer-owned membership during constant evaluation. Entries are Rust
15/// paths relative to the crate, separated by a character forbidden in identifiers.
16/// Root entries end with `::` so sibling names sharing a prefix stay independent.
17#[doc(hidden)]
18#[must_use]
19pub const fn check_schema_member(path: &str, root: &str, members: Option<&str>) -> bool {
20    const fn listed(path: &[u8], list: &[u8]) -> bool {
21        let mut start = 0;
22        while start < list.len() {
23            let mut end = start;
24            let mut same = true;
25            while end < list.len() && list[end] != b'|' {
26                let i = end - start;
27                same = same && i < path.len() && path[i] == list[end];
28                end += 1;
29            }
30            if same && end - start == path.len() {
31                return true;
32            }
33            start = end + 1;
34        }
35
36        false
37    }
38    let path = path.as_bytes();
39    let mut first_separator = 0;
40    while first_separator < path.len() && path[first_separator] != b':' {
41        first_separator += 1;
42    }
43    let (_, relative) = path.split_at(first_separator);
44
45    let root = root.as_bytes();
46    let mut index = 0;
47    while index < root.len() {
48        if index == relative.len() || relative[index] != root[index] {
49            return true;
50        }
51        index += 1;
52    }
53
54    match members {
55        Some(paths) => listed(relative, paths.as_bytes()),
56        None => false,
57    }
58}
59
60pub(crate) const MAX_ENTITIES: u8 = 128;
61pub(crate) const MAX_FIELDS: usize = 16;
62
63// FNV-1a is only a compact physical handle, never schema authority. Admission
64// rejects collisions; full names and semantics enter the SHA-256 contract.
65#[doc(hidden)]
66#[must_use]
67pub const fn handle(name: &str) -> u32 {
68    let bytes = name.as_bytes();
69    let mut value = 2_166_136_261_u32;
70    let mut position = 0;
71    while position < bytes.len() {
72        value = (value ^ bytes[position] as u32).wrapping_mul(16_777_619);
73        position += 1;
74    }
75
76    value
77}
78
79/// Stored value semantics supported by this increment.
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub enum FieldType {
82    /// An ordered bounded list of scalars or named values.
83    List {
84        /// Exact element type; optional elements and inline lists are not admitted yet.
85        item: &'static FieldType,
86        /// Maximum number of elements, from zero through 256.
87        max_items: u32,
88    },
89    /// A compiler-resolved named value. Scalar newtypes and unit enums support
90    /// secondary keys. Primary and reference keys require supported primitives.
91    Named(TypeLink),
92    /// Exact unsigned 8-bit integer.
93    Nat8,
94    /// Exact unsigned 16-bit integer.
95    Nat16,
96    /// Exact unsigned 32-bit integer.
97    Nat32,
98    /// Exact signed 8-bit integer.
99    Int8,
100    /// Exact signed 16-bit integer.
101    Int16,
102    /// Exact signed 32-bit integer.
103    Int32,
104    /// Exact unsigned 64-bit integer.
105    Nat64,
106    /// Exact signed 64-bit integer, without unsigned or floating-point coercion.
107    Int64,
108    /// Exact unsigned 128-bit integer, without narrowing or floating-point coercion.
109    Nat128,
110    /// Exact signed 128-bit integer, without narrowing or floating-point coercion.
111    Int128,
112    /// Exact unsigned 256-bit integer, stored as 32 big-endian bytes.
113    U256,
114    /// Exact 16-byte ULID, ordered by timestamp prefix then remaining bits.
115    Ulid,
116    /// Gregorian epoch days, bounded to years 0000 through 9999.
117    Date,
118    /// Signed Unix milliseconds; full i64 domain.
119    Timestamp,
120    /// Nonnegative milliseconds; full u64 domain.
121    Duration,
122    /// Exact decimal, stored at the declared fractional scale without rounding.
123    Decimal {
124        /// Number of fractional places, 0 through 28.
125        scale: u32,
126    },
127    /// Finite IEEE-754 single precision, canonical positive zero.
128    Float32,
129    /// Finite IEEE-754 double precision, canonical positive zero.
130    Float64,
131    /// Boolean, without numeric coercion.
132    Bool,
133    /// Opaque IC identity, zero to 29 significant bytes; no authority policy.
134    Principal,
135    /// Exact 32-byte opaque subaccount, ordered lexicographically.
136    Subaccount,
137    /// Platform account identity: owner then effective subaccount; absent and zero agree.
138    Account,
139    /// Exact UTF-8 text, bounded in bytes without implicit normalization.
140    Text {
141        /// Maximum UTF-8 byte length (0..=4096); zero admits only empty text.
142        max_bytes: u32,
143    },
144    /// Exact binary bytes without UTF-8 interpretation or normalization.
145    Blob {
146        /// Maximum payload length (0..=4096); zero admits only an empty value.
147        max_bytes: u32,
148    },
149}
150
151/// One named stored field; type, bounds, optionality and write policy define identity.
152#[derive(Clone, Copy, Debug, PartialEq, Eq)]
153pub struct FieldSchema {
154    /// Database-owned insertion/update time policy, never applied during decode.
155    pub managed: Option<crate::ManagedTimestamp>,
156    /// Compiled insert-omission policy; no default is applied during decode/update.
157    pub default: Option<&'static crate::LiteralDefault>,
158    /// Stable field identity within its entity.
159    pub name: &'static str,
160    /// Declared primitive and its bounds.
161    pub value: FieldType,
162    /// Whether absence is a stored value, distinct from empty/zero/false.
163    pub optional: bool,
164    /// Present targets must exist; deletion is restricted through a declared index.
165    pub reference: Option<ReferenceSchema>,
166}
167
168/// A required or optional typed reference using an ordinary reverse-lookup index.
169/// An absent optional value has no target; zero remains an ordinary target key.
170#[derive(Clone, Copy, Debug, PartialEq, Eq)]
171pub struct ReferenceSchema {
172    /// Full logical target identity; its required key type must match this field.
173    pub entity_name: &'static str,
174    /// Generated target storage handle.
175    #[doc(hidden)]
176    pub entity: u32,
177    /// Index on this entity whose first component is the referencing field.
178    pub index: u32,
179}
180
181/// A compiled index over supported exact scalar components.
182#[derive(Debug, PartialEq, Eq)]
183pub struct IndexSchema {
184    /// Generated storage handle; use the name when selecting an index.
185    #[doc(hidden)]
186    pub id: u32,
187    /// Logical identity within its entity, included in the stored contract.
188    pub name: &'static str,
189    /// Fields in declared index order.
190    pub fields: &'static [&'static str],
191    /// Whether the complete key must be unique in the final batch state.
192    pub unique: bool,
193    /// Unique membership requires every optional component to be present.
194    pub present_only: bool,
195}
196
197impl IndexSchema {
198    /// An admitted equality prefix identifies at most one owner when it fixes the entire unique key.
199    pub(crate) fn is_unique_lookup(&self, fixed_components: usize) -> bool {
200        self.unique && fixed_components == self.fields.len()
201    }
202}
203
204/// Compiled entity metadata emitted by the entity macro.
205pub struct EntitySchema {
206    /// Generated storage handle; schema authors do not assign this number.
207    #[doc(hidden)]
208    pub id: u32,
209    /// Logical entity identity, included in the stored contract.
210    pub name: &'static str,
211    /// Fields in canonical name order.
212    pub fields: &'static [FieldSchema],
213    /// Supplied scalar primary-key field; its type must implement `PrimaryKey`.
214    pub primary_key: &'static str,
215    /// Indexes ordered by logical name.
216    pub indexes: &'static [IndexSchema],
217}
218
219impl EntitySchema {
220    pub(crate) fn field_position(&self, name: &str) -> Option<usize> {
221        self.fields.iter().position(|field| field.name == name)
222    }
223
224    pub(crate) fn field_by_name(&self, name: &str) -> Option<&FieldSchema> {
225        self.field_position(name)
226            .map(|position| &self.fields[position])
227    }
228
229    pub(crate) fn field_is_required(&self, path: &str) -> bool {
230        crate::member::resolve_field(self, path).is_ok_and(|(parent, member)| {
231            !self.fields[parent].optional && member.is_none_or(|m| !m.field().optional)
232        })
233    }
234
235    pub(crate) fn record_member(&self, path: &str) -> Option<(usize, crate::member::RecordMember)> {
236        let (parent, child) = path.split_once('.')?;
237        let position = self.field_position(parent)?;
238        let member =
239            crate::member::RecordMember::resolve(self.fields[position].value, child).ok()?;
240        Some((position, member))
241    }
242
243    pub(crate) fn index_field(&self, name: &str) -> Option<&FieldSchema> {
244        self.field_by_name(name)
245            .or_else(|| self.record_member(name).map(|(_, member)| member.field()))
246    }
247
248    pub(crate) fn index_by_name(&self, name: &str) -> Option<&IndexSchema> {
249        self.indexes.iter().find(|index| index.name == name)
250    }
251
252    pub(crate) fn has_managed(&self) -> bool {
253        self.fields.iter().any(|field| field.managed.is_some())
254    }
255
256    pub(crate) fn key_type(&self) -> Result<FieldType, Error> {
257        self.field_by_name(self.primary_key)
258            .filter(|field| !field.optional)
259            .map(|f| f.value)
260            .ok_or(Error::Corrupt)
261    }
262    // Called only for an admitted schema. Validate every stored field but retain
263    // only selected key values; no entity or owned text/blob materialization.
264    pub(crate) fn inspect_row(&self, bytes: &[u8]) -> Result<RowInfo, Error> {
265        let mut values = [IndexValue::Absent; MAX_FIELDS];
266        let mut spans = [(0, 0); MAX_FIELDS];
267        self.inspect_fields(bytes, self.key_fields(), &mut values, Some(&mut spans))?;
268
269        self.row_info(&values, bytes, &spans)
270    }
271
272    pub(crate) fn key_fields(&self) -> u16 {
273        self.fields
274            .iter()
275            .enumerate()
276            .fold(0, |mask, (position, field)| {
277                if field.name == self.primary_key
278                    || self.indexes.iter().any(|i| i.fields.contains(&field.name))
279                {
280                    mask | (1 << position)
281                } else {
282                    mask
283                }
284            })
285    }
286    // One bounded borrowed field view serves mutation integrity and predicates.
287    // Unselected fields are still validated, never silently trusted or materialized.
288    // Callers supply fresh absent slots; filling in place avoids copying the view.
289    // Projection captures validated byte ranges, including presence tags. There
290    // is still one row decoder and one shared depth/node/collection budget.
291    pub(crate) fn inspect_fields<'a>(
292        &self,
293        bytes: &'a [u8],
294        selected: u16,
295        keys: &mut [IndexValue<'a>; MAX_FIELDS],
296        mut spans: Option<&mut [(u16, u16); MAX_FIELDS]>,
297    ) -> Result<(), Error> {
298        let mut reader = Decoder::new(bytes)?;
299        let mut times = [None; 2];
300        for (position, field) in self.fields.iter().enumerate() {
301            let start = reader.position();
302            let present = !field.optional || reader.boolean()?;
303            if !present {
304                // The fresh slot remains absent; its presence tag is projected.
305            } else if let Some(managed) = field.managed {
306                let value = reader.timestamp()?;
307                times[managed.slot()] = Some(value);
308                keys[position] = IndexValue::from(value);
309            } else if selected & (1 << position) != 0 {
310                *keys.get_mut(position).ok_or(Error::Corrupt)? =
311                    IndexValue::read(&mut reader, field.value)?;
312            } else {
313                reader.skip(field.value)?;
314            }
315            if let Some(spans) = &mut spans {
316                spans[position] = (start as u16, reader.position() as u16);
317            }
318        }
319        reader.finish()?;
320        crate::managed::validate_order(times)?;
321
322        Ok(())
323    }
324
325    pub(crate) fn row_info<'a>(
326        &self,
327        keys: &[IndexValue<'a>; MAX_FIELDS],
328        bytes: &'a [u8],
329        spans: &[(u16, u16); MAX_FIELDS],
330    ) -> Result<RowInfo, Error> {
331        let position = |name: &str| self.field_position(name).ok_or(Error::Corrupt);
332        let indexes = self
333            .indexes
334            .iter()
335            .map(|index| {
336                let mut components = [(IndexValue::Absent, false); 4];
337                for (slot, name) in components.iter_mut().zip(index.fields) {
338                    *slot = if let Some(position) = self.field_position(name) {
339                        (keys[position], self.fields[position].optional)
340                    } else {
341                        let (parent, member) = self.record_member(name).ok_or(Error::Corrupt)?;
342                        let (start, end) = spans[parent];
343                        (
344                            member.read(&bytes[usize::from(start)..usize::from(end)], false)?,
345                            false,
346                        )
347                    };
348                    if slot.0 == IndexValue::Absent && !slot.1 {
349                        return Err(Error::Corrupt);
350                    }
351                }
352
353                Ok(key::encode_index(
354                    &components[..index.fields.len()],
355                    index.present_only,
356                ))
357            })
358            .collect::<Result<_, Error>>()?;
359        let key = RowKey::from_index(keys[position(self.primary_key)?])?;
360
361        Ok(RowInfo { key, indexes })
362    }
363}
364
365/// Validated executable schema. It is never reconstructed from stored data.
366/// Clones retain only immutable executable metadata; each database open still
367/// validates the current durable manifest independently. Revision reads and
368/// writes validate the affected counters when used, without caching them.
369#[derive(Clone)]
370pub struct Schema {
371    entities: Vec<&'static EntitySchema>,
372    pub(crate) fingerprint: [u8; 32],
373    types: TypeGraph,
374}
375
376impl Schema {
377    /// Validate one bounded compiled schema and compute its canonical fingerprint.
378    /// # Errors
379    /// Refuses duplicate/invalid identities, fields, keys, indexes or capacity.
380    pub fn new(entities: &[&'static EntitySchema]) -> Result<Self, Error> {
381        Self::admit_schema(entities, |_, _, _, _| {})
382    }
383
384    // The host formats reference failures at the same check used by ordinary admission.
385    pub(crate) fn admit_schema(
386        entities: &[&'static EntitySchema],
387        report_reference: impl FnOnce(&str, &FieldSchema, &str, Option<(&str, FieldType)>),
388    ) -> Result<Self, Error> {
389        if entities.is_empty() || entities.len() > usize::from(MAX_ENTITIES) {
390            return Err(Error::InvalidSchema);
391        }
392        let mut entities = entities.to_vec();
393        entities.sort_by_key(|entity| entity.name);
394        let mut bytes = b"ICDBSC01".to_vec();
395        // Contract grammar, row codec, key codec, semantics, supplier contract.
396        // Supplier contract 1 is qualified with Storage 0.74.1; it is not a guess
397        // that every future supplier release uses a compatible collection format.
398        // Semantics 2 admits complete physical index keys of at most 512 bytes.
399        // Older wider-key contracts refuse intact; stored component bytes are unchanged.
400        for version in [2, crate::codec::ROW_CODEC_VERSION, 1, 2, 1] {
401            bytes.extend(version.to_le_bytes());
402        }
403        bytes.extend((entities.len() as u32).to_le_bytes());
404        let mut ids = BTreeSet::new();
405        let mut types = TypeGraph::default();
406        for entity in &entities {
407            if entity.id != handle(entity.name)
408                || !ids.insert(entity.id)
409                || entity.fields.is_empty()
410                || entity.fields.len() > MAX_FIELDS
411                || entity.indexes.len() > 8
412                || !entity.key_type().is_ok_and(RowKey::supports)
413                || entity
414                    .fields
415                    .windows(2)
416                    .any(|pair| pair[0].name >= pair[1].name)
417            {
418                return Err(Error::InvalidSchema);
419            }
420            name(&mut bytes, entity.name)?;
421            bytes.extend((entity.fields.len() as u32).to_le_bytes());
422            for field in entity.fields {
423                name(&mut bytes, field.name)?;
424                encode_type(
425                    &mut bytes,
426                    field.value,
427                    field.optional,
428                    field.reference.is_some(),
429                )?;
430                types.include(field.value)?;
431                if let Some(reference) = field.reference {
432                    let Some(target) = entities.iter().find(|target| {
433                        target.id == reference.entity && target.name == reference.entity_name
434                    }) else {
435                        report_reference(entity.name, field, reference.entity_name, None);
436
437                        return Err(Error::InvalidSchema);
438                    };
439                    let key_type = target.key_type().map_err(|_| Error::InvalidSchema)?;
440                    if field.value != key_type {
441                        report_reference(
442                            entity.name,
443                            field,
444                            target.name,
445                            Some((target.primary_key, key_type)),
446                        );
447
448                        return Err(Error::InvalidSchema);
449                    }
450                    if !RowKey::supports(field.value) {
451                        return Err(Error::InvalidSchema);
452                    }
453                    let index = entity
454                        .indexes
455                        .iter()
456                        .find(|index| {
457                            index.id == reference.index
458                                && !index.present_only
459                                && index.fields.first() == Some(&field.name)
460                        })
461                        .ok_or(Error::InvalidSchema)?;
462                    name(&mut bytes, target.name)?;
463                    name(&mut bytes, index.name)?;
464                }
465            }
466            name(&mut bytes, entity.primary_key)?;
467            bytes.extend((entity.indexes.len() as u32).to_le_bytes());
468            let mut index_ids = BTreeSet::new();
469            for index in entity.indexes {
470                if index.id != handle(index.name)
471                    || !index_ids.insert(index.id)
472                    || index.fields.is_empty()
473                    || index.fields.len() > 4
474                {
475                    return Err(Error::InvalidSchema);
476                }
477                let mut fields = BTreeSet::new();
478                let has_optional = index.fields.iter().any(|name| {
479                    entity
480                        .fields
481                        .iter()
482                        .any(|field| field.name == *name && field.optional)
483                });
484                if (index.unique && has_optional && !index.present_only)
485                    || (index.present_only && (!index.unique || !has_optional))
486                {
487                    return Err(Error::InvalidSchema);
488                }
489                name(&mut bytes, index.name)?;
490                bytes.push(u8::from(index.unique) | (u8::from(index.present_only) << 1));
491                bytes.extend((index.fields.len() as u32).to_le_bytes());
492                for field in index.fields {
493                    if !fields.insert(field) {
494                        return Err(Error::InvalidSchema);
495                    }
496                    if let Some(declared) = entity.field_by_name(field) {
497                        if !key::supports(declared.value) {
498                            return Err(Error::InvalidSchema);
499                        }
500                        name(&mut bytes, field)?;
501                    } else {
502                        let (parent, member) =
503                            entity.record_member(field).ok_or(Error::InvalidSchema)?;
504                        let parent = &entity.fields[parent];
505                        let leaf = member.field();
506                        if index.unique
507                            || index.fields.len() != 1
508                            || parent.optional
509                            || leaf.optional
510                        {
511                            return Err(Error::InvalidSchema);
512                        }
513                        // Outside the 1..=64 length domain of a flat field. Each path part
514                        // owns its own frame, including when the index has an explicit name.
515                        bytes.extend(u32::MAX.to_le_bytes());
516                        name(&mut bytes, parent.name)?;
517                        name(&mut bytes, leaf.name)?;
518                    }
519                }
520            }
521            if entity
522                .indexes
523                .windows(2)
524                .any(|pair| pair[0].name >= pair[1].name)
525            {
526                return Err(Error::InvalidSchema);
527            }
528        }
529        types.encode(&mut bytes)?;
530        // Versioned policy trailer only for schemas that declare defaults. Existing
531        // contracts retain their bytes; the trailer is not a second durable catalog.
532        let defaults: Vec<_> = entities
533            .iter()
534            .flat_map(|entity| {
535                entity
536                    .fields
537                    .iter()
538                    .filter_map(move |field| field.default.map(|value| (entity, field, value)))
539            })
540            .collect();
541        if !defaults.is_empty() {
542            bytes.extend(b"ic-db:insert-defaults:v1\0");
543            bytes.extend((defaults.len() as u32).to_le_bytes());
544            for (entity, field, value) in defaults {
545                if field.name == entity.primary_key {
546                    return Err(Error::InvalidSchema);
547                }
548                name(&mut bytes, entity.name)?;
549                name(&mut bytes, field.name)?;
550                let encoded = value.encode(field.value)?;
551                bytes.extend((encoded.len() as u32).to_le_bytes());
552                bytes.extend(encoded);
553            }
554        }
555        let mut policies = Vec::new();
556        for entity in &entities {
557            let mut seen = [false; 2];
558            for field in entity.fields {
559                if let Some(managed) = field.managed {
560                    if crate::key::operand_type(field.value) != FieldType::Timestamp
561                        || field.optional
562                        || field.default.is_some()
563                        || field.reference.is_some()
564                        || field.name == entity.primary_key
565                        || seen[managed.slot()]
566                    {
567                        return Err(Error::InvalidSchema);
568                    }
569                    seen[managed.slot()] = true;
570                    policies.push((entity.name, field.name, managed));
571                }
572            }
573        }
574        if !policies.is_empty() {
575            bytes.extend(b"ic-db:managed-times:v1\0");
576            bytes.extend((policies.len() as u32).to_le_bytes());
577            for (entity, field, managed) in policies {
578                name(&mut bytes, entity)?;
579                name(&mut bytes, field)?;
580                bytes.push(managed.slot() as u8 + 1);
581            }
582        }
583        let mut hash = Sha256::new();
584        hash.update(b"ic-db:schema:v1\0");
585        hash.update(bytes);
586
587        Ok(Self {
588            entities,
589            types,
590            fingerprint: hash.finalize().into(),
591        })
592    }
593
594    /// Full domain-separated contract identity used by the durable manifest.
595    #[must_use]
596    pub const fn fingerprint(&self) -> [u8; 32] {
597        self.fingerprint
598    }
599
600    /// Compiled entities in logical-name order, for bounded inspection.
601    #[must_use]
602    pub fn entities(&self) -> &[&'static EntitySchema] {
603        &self.entities
604    }
605
606    pub(crate) fn entity_by_id(&self, id: u32) -> Option<&'static EntitySchema> {
607        self.entities.iter().copied().find(|entity| entity.id == id)
608    }
609
610    pub(crate) fn entity_by_name(&self, name: &str) -> Option<&'static EntitySchema> {
611        self.entities
612            .binary_search_by_key(&name, |entity| entity.name)
613            .ok()
614            .map(|position| self.entities[position])
615    }
616
617    /// Reachable named definitions in logical-name order, without expanding cycles.
618    pub fn types(&self) -> impl Iterator<Item = &'static crate::TypeSchema> + '_ {
619        self.types.definitions()
620    }
621
622    // Return the existing admitted descriptor after checking the complete type
623    // contract. Typed callers can use it without specializing execution around
624    // their executable's descriptor address.
625    pub(crate) fn admits(&self, proposed: &EntitySchema) -> Result<&'static EntitySchema, Error> {
626        let current = self.entity_by_id(proposed.id).ok_or(Error::UnknownEntity)?;
627        if current.name != proposed.name
628            || current.fields != proposed.fields
629            || current.primary_key != proposed.primary_key
630            || current.indexes != proposed.indexes
631        {
632            return Err(Error::UnknownEntity);
633        }
634        let mut proposed_types = TypeGraph::default();
635        for field in proposed.fields {
636            proposed_types
637                .include(field.value)
638                .map_err(|_| Error::UnknownEntity)?;
639        }
640        if !self.types.contains(&proposed_types) {
641            return Err(Error::UnknownEntity);
642        }
643
644        Ok(current)
645    }
646}
647
648pub(crate) fn name(bytes: &mut Vec<u8>, value: &str) -> Result<(), Error> {
649    if value.is_empty() || value.len() > 64 {
650        return Err(Error::InvalidSchema);
651    }
652    bytes.extend((value.len() as u32).to_le_bytes());
653    bytes.extend(value.as_bytes());
654
655    Ok(())
656}
657
658pub(crate) fn encode_type(
659    bytes: &mut Vec<u8>,
660    value: FieldType,
661    optional: bool,
662    reference: bool,
663) -> Result<(), Error> {
664    let tag = match value {
665        FieldType::Nat64 => 1,
666        FieldType::Bool => 2,
667        FieldType::Text { .. } => 3,
668        FieldType::Int64 => 4,
669        FieldType::Nat128 => 5,
670        FieldType::Int128 => 6,
671        FieldType::Blob { .. } => 7,
672        FieldType::Nat8 => 8,
673        FieldType::Nat16 => 9,
674        FieldType::Nat32 => 10,
675        FieldType::Int8 => 11,
676        FieldType::Int16 => 12,
677        FieldType::Int32 => 13,
678        FieldType::Principal => 14,
679        FieldType::Named(_) => 15,
680        FieldType::List { .. } => 16,
681        FieldType::U256 => 17,
682        FieldType::Float32 => 18,
683        FieldType::Float64 => 19,
684        FieldType::Subaccount => 20,
685        FieldType::Account => 21,
686        FieldType::Ulid => 22,
687        FieldType::Date => 23,
688        FieldType::Timestamp => 24,
689        FieldType::Duration => 25,
690        FieldType::Decimal { .. } => 26,
691    };
692    bytes.push(tag | if optional { 0x80 } else { 0 } | if reference { 0x40 } else { 0 });
693    match value {
694        FieldType::Decimal { scale } => {
695            if scale > crate::Decimal::MAX_SCALE {
696                return Err(Error::InvalidSchema);
697            }
698            bytes.extend(scale.to_le_bytes());
699        }
700        FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => {
701            if max_bytes > 4096 {
702                return Err(Error::InvalidSchema);
703            }
704            bytes.extend(max_bytes.to_le_bytes());
705        }
706        FieldType::Named(link) => name(bytes, link.name)?,
707        FieldType::List { item, max_items } => {
708            if max_items > crate::types::MAX_COLLECTION_ITEMS as u32
709                || matches!(item, FieldType::List { .. })
710            {
711                return Err(Error::InvalidSchema);
712            }
713            for bound in [
714                max_items,
715                crate::types::MAX_DEPTH as u32,
716                crate::types::MAX_NODES as u32,
717                crate::types::MAX_COLLECTION_ITEMS as u32,
718            ] {
719                bytes.extend(bound.to_le_bytes());
720            }
721            encode_type(bytes, *item, false, false)?;
722        }
723        _ => {}
724    }
725
726    Ok(())
727}