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 record_member(&self, path: &str) -> Option<(usize, crate::member::RecordMember)> {
230        let (parent, child) = path.split_once('.')?;
231        let position = self.field_position(parent)?;
232        let member =
233            crate::member::RecordMember::resolve(self.fields[position].value, child).ok()?;
234        Some((position, member))
235    }
236
237    pub(crate) fn index_field(&self, name: &str) -> Option<&FieldSchema> {
238        self.field_by_name(name)
239            .or_else(|| self.record_member(name).map(|(_, member)| member.field()))
240    }
241
242    pub(crate) fn index_by_name(&self, name: &str) -> Option<&IndexSchema> {
243        self.indexes.iter().find(|index| index.name == name)
244    }
245
246    pub(crate) fn has_managed(&self) -> bool {
247        self.fields.iter().any(|field| field.managed.is_some())
248    }
249
250    pub(crate) fn key_type(&self) -> Result<FieldType, Error> {
251        self.field_by_name(self.primary_key)
252            .filter(|field| !field.optional)
253            .map(|f| f.value)
254            .ok_or(Error::Corrupt)
255    }
256    // Called only for an admitted schema. Validate every stored field but retain
257    // only selected key values; no entity or owned text/blob materialization.
258    pub(crate) fn inspect_row(&self, bytes: &[u8]) -> Result<RowInfo, Error> {
259        let mut values = [IndexValue::Absent; MAX_FIELDS];
260        let mut spans = [(0, 0); MAX_FIELDS];
261        self.inspect_fields(bytes, self.key_fields(), &mut values, Some(&mut spans))?;
262
263        self.row_info(&values, bytes, &spans)
264    }
265
266    pub(crate) fn key_fields(&self) -> u16 {
267        self.fields
268            .iter()
269            .enumerate()
270            .fold(0, |mask, (position, field)| {
271                if field.name == self.primary_key
272                    || self.indexes.iter().any(|i| i.fields.contains(&field.name))
273                {
274                    mask | (1 << position)
275                } else {
276                    mask
277                }
278            })
279    }
280    // One bounded borrowed field view serves mutation integrity and predicates.
281    // Unselected fields are still validated, never silently trusted or materialized.
282    // Callers supply fresh absent slots; filling in place avoids copying the view.
283    // Projection captures validated byte ranges, including presence tags. There
284    // is still one row decoder and one shared depth/node/collection budget.
285    pub(crate) fn inspect_fields<'a>(
286        &self,
287        bytes: &'a [u8],
288        selected: u16,
289        keys: &mut [IndexValue<'a>; MAX_FIELDS],
290        mut spans: Option<&mut [(u16, u16); MAX_FIELDS]>,
291    ) -> Result<(), Error> {
292        let mut reader = Decoder::new(bytes)?;
293        let mut times = [None; 2];
294        for (position, field) in self.fields.iter().enumerate() {
295            let start = reader.position();
296            let present = !field.optional || reader.boolean()?;
297            if !present {
298                // The fresh slot remains absent; its presence tag is projected.
299            } else if let Some(managed) = field.managed {
300                let value = reader.timestamp()?;
301                times[managed.slot()] = Some(value);
302                keys[position] = IndexValue::from(value);
303            } else if selected & (1 << position) != 0 {
304                *keys.get_mut(position).ok_or(Error::Corrupt)? =
305                    IndexValue::read(&mut reader, field.value)?;
306            } else {
307                reader.skip(field.value)?;
308            }
309            if let Some(spans) = &mut spans {
310                spans[position] = (start as u16, reader.position() as u16);
311            }
312        }
313        reader.finish()?;
314        crate::managed::validate_order(times)?;
315
316        Ok(())
317    }
318
319    pub(crate) fn row_info<'a>(
320        &self,
321        keys: &[IndexValue<'a>; MAX_FIELDS],
322        bytes: &'a [u8],
323        spans: &[(u16, u16); MAX_FIELDS],
324    ) -> Result<RowInfo, Error> {
325        let position = |name: &str| self.field_position(name).ok_or(Error::Corrupt);
326        let indexes = self
327            .indexes
328            .iter()
329            .map(|index| {
330                let mut components = [(IndexValue::Absent, false); 4];
331                for (slot, name) in components.iter_mut().zip(index.fields) {
332                    *slot = if let Some(position) = self.field_position(name) {
333                        (keys[position], self.fields[position].optional)
334                    } else {
335                        let (parent, member) = self.record_member(name).ok_or(Error::Corrupt)?;
336                        let (start, end) = spans[parent];
337                        (
338                            member.read(&bytes[usize::from(start)..usize::from(end)], false)?,
339                            false,
340                        )
341                    };
342                    if slot.0 == IndexValue::Absent && !slot.1 {
343                        return Err(Error::Corrupt);
344                    }
345                }
346
347                Ok(key::encode_index(
348                    &components[..index.fields.len()],
349                    index.present_only,
350                ))
351            })
352            .collect::<Result<_, Error>>()?;
353        let key = RowKey::from_index(keys[position(self.primary_key)?])?;
354
355        Ok(RowInfo { key, indexes })
356    }
357}
358
359/// Validated executable schema. It is never reconstructed from stored data.
360/// Clones retain only immutable executable metadata; each database open still
361/// validates the current durable manifest independently. Revision reads and
362/// writes validate the affected counters when used, without caching them.
363#[derive(Clone)]
364pub struct Schema {
365    entities: Vec<&'static EntitySchema>,
366    pub(crate) fingerprint: [u8; 32],
367    types: TypeGraph,
368}
369
370impl Schema {
371    /// Validate one bounded compiled schema and compute its canonical fingerprint.
372    /// # Errors
373    /// Refuses duplicate/invalid identities, fields, keys, indexes or capacity.
374    pub fn new(entities: &[&'static EntitySchema]) -> Result<Self, Error> {
375        Self::admit_schema(entities, |_, _, _, _| {})
376    }
377
378    // The host formats reference failures at the same check used by ordinary admission.
379    pub(crate) fn admit_schema(
380        entities: &[&'static EntitySchema],
381        report_reference: impl FnOnce(&str, &FieldSchema, &str, Option<(&str, FieldType)>),
382    ) -> Result<Self, Error> {
383        if entities.is_empty() || entities.len() > usize::from(MAX_ENTITIES) {
384            return Err(Error::InvalidSchema);
385        }
386        let mut entities = entities.to_vec();
387        entities.sort_by_key(|entity| entity.name);
388        let mut bytes = b"ICDBSC01".to_vec();
389        // Contract grammar, row codec, key codec, semantics, supplier contract.
390        // Supplier contract 1 is qualified with Storage 0.74.1; it is not a guess
391        // that every future supplier release uses a compatible collection format.
392        // Semantics 2 admits complete physical index keys of at most 512 bytes.
393        // Older wider-key contracts refuse intact; stored component bytes are unchanged.
394        for version in [2, crate::codec::ROW_CODEC_VERSION, 1, 2, 1] {
395            bytes.extend(version.to_le_bytes());
396        }
397        bytes.extend((entities.len() as u32).to_le_bytes());
398        let mut ids = BTreeSet::new();
399        let mut types = TypeGraph::default();
400        for entity in &entities {
401            if entity.id != handle(entity.name)
402                || !ids.insert(entity.id)
403                || entity.fields.is_empty()
404                || entity.fields.len() > MAX_FIELDS
405                || entity.indexes.len() > 8
406                || !entity.key_type().is_ok_and(RowKey::supports)
407                || entity
408                    .fields
409                    .windows(2)
410                    .any(|pair| pair[0].name >= pair[1].name)
411            {
412                return Err(Error::InvalidSchema);
413            }
414            name(&mut bytes, entity.name)?;
415            bytes.extend((entity.fields.len() as u32).to_le_bytes());
416            for field in entity.fields {
417                name(&mut bytes, field.name)?;
418                encode_type(
419                    &mut bytes,
420                    field.value,
421                    field.optional,
422                    field.reference.is_some(),
423                )?;
424                types.include(field.value)?;
425                if let Some(reference) = field.reference {
426                    let Some(target) = entities.iter().find(|target| {
427                        target.id == reference.entity && target.name == reference.entity_name
428                    }) else {
429                        report_reference(entity.name, field, reference.entity_name, None);
430
431                        return Err(Error::InvalidSchema);
432                    };
433                    let key_type = target.key_type().map_err(|_| Error::InvalidSchema)?;
434                    if field.value != key_type {
435                        report_reference(
436                            entity.name,
437                            field,
438                            target.name,
439                            Some((target.primary_key, key_type)),
440                        );
441
442                        return Err(Error::InvalidSchema);
443                    }
444                    if !RowKey::supports(field.value) {
445                        return Err(Error::InvalidSchema);
446                    }
447                    let index = entity
448                        .indexes
449                        .iter()
450                        .find(|index| {
451                            index.id == reference.index
452                                && !index.present_only
453                                && index.fields.first() == Some(&field.name)
454                        })
455                        .ok_or(Error::InvalidSchema)?;
456                    name(&mut bytes, target.name)?;
457                    name(&mut bytes, index.name)?;
458                }
459            }
460            name(&mut bytes, entity.primary_key)?;
461            bytes.extend((entity.indexes.len() as u32).to_le_bytes());
462            let mut index_ids = BTreeSet::new();
463            for index in entity.indexes {
464                if index.id != handle(index.name)
465                    || !index_ids.insert(index.id)
466                    || index.fields.is_empty()
467                    || index.fields.len() > 4
468                {
469                    return Err(Error::InvalidSchema);
470                }
471                let mut fields = BTreeSet::new();
472                let has_optional = index.fields.iter().any(|name| {
473                    entity
474                        .fields
475                        .iter()
476                        .any(|field| field.name == *name && field.optional)
477                });
478                if (index.unique && has_optional && !index.present_only)
479                    || (index.present_only && (!index.unique || !has_optional))
480                {
481                    return Err(Error::InvalidSchema);
482                }
483                name(&mut bytes, index.name)?;
484                bytes.push(u8::from(index.unique) | (u8::from(index.present_only) << 1));
485                bytes.extend((index.fields.len() as u32).to_le_bytes());
486                for field in index.fields {
487                    if !fields.insert(field) {
488                        return Err(Error::InvalidSchema);
489                    }
490                    if let Some(declared) = entity.field_by_name(field) {
491                        if !key::supports(declared.value) {
492                            return Err(Error::InvalidSchema);
493                        }
494                        name(&mut bytes, field)?;
495                    } else {
496                        let (parent, member) =
497                            entity.record_member(field).ok_or(Error::InvalidSchema)?;
498                        let parent = &entity.fields[parent];
499                        let leaf = member.field();
500                        if index.unique
501                            || index.fields.len() != 1
502                            || parent.optional
503                            || leaf.optional
504                        {
505                            return Err(Error::InvalidSchema);
506                        }
507                        // Outside the 1..=64 length domain of a flat field. Each path part
508                        // owns its own frame, including when the index has an explicit name.
509                        bytes.extend(u32::MAX.to_le_bytes());
510                        name(&mut bytes, parent.name)?;
511                        name(&mut bytes, leaf.name)?;
512                    }
513                }
514            }
515            if entity
516                .indexes
517                .windows(2)
518                .any(|pair| pair[0].name >= pair[1].name)
519            {
520                return Err(Error::InvalidSchema);
521            }
522        }
523        types.encode(&mut bytes)?;
524        // Versioned policy trailer only for schemas that declare defaults. Existing
525        // contracts retain their bytes; the trailer is not a second durable catalog.
526        let defaults: Vec<_> = entities
527            .iter()
528            .flat_map(|entity| {
529                entity
530                    .fields
531                    .iter()
532                    .filter_map(move |field| field.default.map(|value| (entity, field, value)))
533            })
534            .collect();
535        if !defaults.is_empty() {
536            bytes.extend(b"ic-db:insert-defaults:v1\0");
537            bytes.extend((defaults.len() as u32).to_le_bytes());
538            for (entity, field, value) in defaults {
539                if field.name == entity.primary_key {
540                    return Err(Error::InvalidSchema);
541                }
542                name(&mut bytes, entity.name)?;
543                name(&mut bytes, field.name)?;
544                let encoded = value.encode(field.value)?;
545                bytes.extend((encoded.len() as u32).to_le_bytes());
546                bytes.extend(encoded);
547            }
548        }
549        let mut policies = Vec::new();
550        for entity in &entities {
551            let mut seen = [false; 2];
552            for field in entity.fields {
553                if let Some(managed) = field.managed {
554                    if crate::key::operand_type(field.value) != FieldType::Timestamp
555                        || field.optional
556                        || field.default.is_some()
557                        || field.reference.is_some()
558                        || field.name == entity.primary_key
559                        || seen[managed.slot()]
560                    {
561                        return Err(Error::InvalidSchema);
562                    }
563                    seen[managed.slot()] = true;
564                    policies.push((entity.name, field.name, managed));
565                }
566            }
567        }
568        if !policies.is_empty() {
569            bytes.extend(b"ic-db:managed-times:v1\0");
570            bytes.extend((policies.len() as u32).to_le_bytes());
571            for (entity, field, managed) in policies {
572                name(&mut bytes, entity)?;
573                name(&mut bytes, field)?;
574                bytes.push(managed.slot() as u8 + 1);
575            }
576        }
577        let mut hash = Sha256::new();
578        hash.update(b"ic-db:schema:v1\0");
579        hash.update(bytes);
580
581        Ok(Self {
582            entities,
583            types,
584            fingerprint: hash.finalize().into(),
585        })
586    }
587
588    /// Full domain-separated contract identity used by the durable manifest.
589    #[must_use]
590    pub const fn fingerprint(&self) -> [u8; 32] {
591        self.fingerprint
592    }
593
594    /// Compiled entities in logical-name order, for bounded inspection.
595    #[must_use]
596    pub fn entities(&self) -> &[&'static EntitySchema] {
597        &self.entities
598    }
599
600    pub(crate) fn entity_by_id(&self, id: u32) -> Option<&'static EntitySchema> {
601        self.entities.iter().copied().find(|entity| entity.id == id)
602    }
603
604    pub(crate) fn entity_by_name(&self, name: &str) -> Option<&'static EntitySchema> {
605        self.entities
606            .binary_search_by_key(&name, |entity| entity.name)
607            .ok()
608            .map(|position| self.entities[position])
609    }
610
611    /// Reachable named definitions in logical-name order, without expanding cycles.
612    pub fn types(&self) -> impl Iterator<Item = &'static crate::TypeSchema> + '_ {
613        self.types.definitions()
614    }
615
616    // Return the existing admitted descriptor after checking the complete type
617    // contract. Typed callers can use it without specializing execution around
618    // their executable's descriptor address.
619    pub(crate) fn admits(&self, proposed: &EntitySchema) -> Result<&'static EntitySchema, Error> {
620        let current = self.entity_by_id(proposed.id).ok_or(Error::UnknownEntity)?;
621        if current.name != proposed.name
622            || current.fields != proposed.fields
623            || current.primary_key != proposed.primary_key
624            || current.indexes != proposed.indexes
625        {
626            return Err(Error::UnknownEntity);
627        }
628        let mut proposed_types = TypeGraph::default();
629        for field in proposed.fields {
630            proposed_types
631                .include(field.value)
632                .map_err(|_| Error::UnknownEntity)?;
633        }
634        if !self.types.contains(&proposed_types) {
635            return Err(Error::UnknownEntity);
636        }
637
638        Ok(current)
639    }
640}
641
642pub(crate) fn name(bytes: &mut Vec<u8>, value: &str) -> Result<(), Error> {
643    if value.is_empty() || value.len() > 64 {
644        return Err(Error::InvalidSchema);
645    }
646    bytes.extend((value.len() as u32).to_le_bytes());
647    bytes.extend(value.as_bytes());
648
649    Ok(())
650}
651
652pub(crate) fn encode_type(
653    bytes: &mut Vec<u8>,
654    value: FieldType,
655    optional: bool,
656    reference: bool,
657) -> Result<(), Error> {
658    let tag = match value {
659        FieldType::Nat64 => 1,
660        FieldType::Bool => 2,
661        FieldType::Text { .. } => 3,
662        FieldType::Int64 => 4,
663        FieldType::Nat128 => 5,
664        FieldType::Int128 => 6,
665        FieldType::Blob { .. } => 7,
666        FieldType::Nat8 => 8,
667        FieldType::Nat16 => 9,
668        FieldType::Nat32 => 10,
669        FieldType::Int8 => 11,
670        FieldType::Int16 => 12,
671        FieldType::Int32 => 13,
672        FieldType::Principal => 14,
673        FieldType::Named(_) => 15,
674        FieldType::List { .. } => 16,
675        FieldType::U256 => 17,
676        FieldType::Float32 => 18,
677        FieldType::Float64 => 19,
678        FieldType::Subaccount => 20,
679        FieldType::Account => 21,
680        FieldType::Ulid => 22,
681        FieldType::Date => 23,
682        FieldType::Timestamp => 24,
683        FieldType::Duration => 25,
684        FieldType::Decimal { .. } => 26,
685    };
686    bytes.push(tag | if optional { 0x80 } else { 0 } | if reference { 0x40 } else { 0 });
687    match value {
688        FieldType::Decimal { scale } => {
689            if scale > crate::Decimal::MAX_SCALE {
690                return Err(Error::InvalidSchema);
691            }
692            bytes.extend(scale.to_le_bytes());
693        }
694        FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => {
695            if max_bytes > 4096 {
696                return Err(Error::InvalidSchema);
697            }
698            bytes.extend(max_bytes.to_le_bytes());
699        }
700        FieldType::Named(link) => name(bytes, link.name)?,
701        FieldType::List { item, max_items } => {
702            if max_items > crate::types::MAX_COLLECTION_ITEMS as u32
703                || matches!(item, FieldType::List { .. })
704            {
705                return Err(Error::InvalidSchema);
706            }
707            for bound in [
708                max_items,
709                crate::types::MAX_DEPTH as u32,
710                crate::types::MAX_NODES as u32,
711                crate::types::MAX_COLLECTION_ITEMS as u32,
712            ] {
713                bytes.extend(bound.to_le_bytes());
714            }
715            encode_type(bytes, *item, false, false)?;
716        }
717        _ => {}
718    }
719
720    Ok(())
721}