Skip to main content

predsync_schema/
lib.rs

1#![no_std]
2
3//! Schema types shared by the compiler and the core engine.
4
5pub mod ref_;
6
7#[cfg(feature = "alloc")]
8extern crate alloc;
9
10#[cfg(feature = "alloc")]
11use alloc::string::String;
12#[cfg(feature = "alloc")]
13use alloc::vec::Vec;
14#[cfg(feature = "alloc")]
15use core::fmt;
16
17/// Maximum number of fields in one message.
18pub const MAX_FIELDS: usize = 64;
19/// Maximum predictor window.
20pub const MAX_WINDOW: u8 = 64;
21/// Maximum number of messages in one schema set.
22pub const MAX_MESSAGES: usize = 256;
23
24/// Storage layout for no-alloc engine.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26pub struct StorageLayout {
27    pub field_count: usize,
28    pub predictor_count: usize,
29    pub opaque_words_per_state: usize,
30    pub opaque_bytes_per_state: usize,
31    pub staging_words: usize,
32    pub staging_bytes: usize,
33    pub presence_bytes: usize,
34}
35impl StorageLayout {
36    pub const fn total_opaque_words(&self) -> usize {
37        self.opaque_words_per_state
38            .saturating_add(self.staging_words)
39    }
40    pub const fn total_opaque_bytes(&self) -> usize {
41        self.opaque_bytes_per_state
42            .saturating_add(self.staging_bytes)
43    }
44}
45
46/// Why a schema cannot be sized into fixed storage.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum StorageError {
49    /// The requested message does not exist.
50    MessageNotFound,
51    /// A string or list field has no `max_len`.
52    MissingMaxLen,
53    /// The accumulated requirements overflowed `usize`.
54    TooLarge,
55}
56
57/// Compute the fixed storage needed by one message from a borrowed schema.
58pub fn try_storage_layout(
59    schema: &ref_::SchemaRef<'_>,
60    message_index: usize,
61) -> Result<StorageLayout, StorageError> {
62    let msg = schema
63        .messages
64        .as_slice()
65        .get(message_index)
66        .ok_or(StorageError::MessageNotFound)?;
67    let mut layout = StorageLayout {
68        field_count: msg.fields.as_slice().len(),
69        ..Default::default()
70    };
71
72    for field in msg.fields.as_slice() {
73        let is_opaque = match &field.ty {
74            ref_::FieldTypeRef::String
75            | ref_::FieldTypeRef::List(_)
76            | ref_::FieldTypeRef::Enum { .. }
77            | ref_::FieldTypeRef::EnumNamed(_) => true,
78            ref_::FieldTypeRef::Scalar(scalar) => !scalar.is_numeric(),
79        };
80        let has_predictor = field.predictor.is_some();
81        if has_predictor {
82            layout.predictor_count = layout
83                .predictor_count
84                .checked_add(1)
85                .ok_or(StorageError::TooLarge)?;
86        }
87        let cap = match &field.ty {
88            ref_::FieldTypeRef::String | ref_::FieldTypeRef::List(_) => Some(usize::from(
89                field.max_len.ok_or(StorageError::MissingMaxLen)?,
90            )),
91            _ => None,
92        };
93        if has_predictor && is_opaque {
94            match cap {
95                Some(bytes) if matches!(&field.ty, ref_::FieldTypeRef::String) => {
96                    layout.opaque_bytes_per_state = layout
97                        .opaque_bytes_per_state
98                        .checked_add(bytes)
99                        .ok_or(StorageError::TooLarge)?;
100                }
101                Some(words) => {
102                    layout.opaque_words_per_state = layout
103                        .opaque_words_per_state
104                        .checked_add(words)
105                        .ok_or(StorageError::TooLarge)?;
106                }
107                None => {
108                    layout.opaque_words_per_state = layout
109                        .opaque_words_per_state
110                        .checked_add(1)
111                        .ok_or(StorageError::TooLarge)?;
112                }
113            }
114        }
115        match (&field.ty, cap) {
116            (ref_::FieldTypeRef::String, Some(bytes)) => {
117                layout.staging_bytes = layout
118                    .staging_bytes
119                    .checked_add(bytes)
120                    .ok_or(StorageError::TooLarge)?;
121            }
122            (ref_::FieldTypeRef::List(_), Some(words)) => {
123                layout.staging_words = layout
124                    .staging_words
125                    .checked_add(words)
126                    .ok_or(StorageError::TooLarge)?;
127            }
128            _ => {}
129        }
130    }
131    layout.staging_words = layout
132        .staging_words
133        .checked_mul(2)
134        .ok_or(StorageError::TooLarge)?;
135    layout.staging_bytes = layout
136        .staging_bytes
137        .checked_mul(2)
138        .ok_or(StorageError::TooLarge)?;
139    layout.presence_bytes = layout
140        .predictor_count
141        .checked_mul(2)
142        .ok_or(StorageError::TooLarge)?
143        .div_ceil(8);
144    Ok(layout)
145}
146/// Maximum string or list length.
147pub const MAX_LEN: u16 = u16::MAX;
148/// Maximum number of variants in one enum.
149pub const MAX_ENUM_VARIANTS: usize = 65_536;
150
151#[cfg(feature = "alloc")]
152/// A parsed schema set with its non-fatal warnings.
153#[derive(Debug, Clone, PartialEq)]
154pub struct ParsedSchema {
155    pub set: SchemaSet,
156    pub warnings: Vec<Warning>,
157}
158
159#[cfg(feature = "alloc")]
160/// All messages that share one wire contract.
161#[derive(Debug, Clone, PartialEq)]
162pub struct SchemaSet {
163    pub messages: Vec<MessageSchema>,
164}
165
166#[cfg(feature = "alloc")]
167impl SchemaSet {
168    /// Whether frames carry the optional message-ID byte.
169    pub fn id_byte_present(&self) -> bool {
170        self.messages.len() > 1
171    }
172
173    /// Borrow this schema set as a `SchemaRef`.
174    ///
175    /// The nested field/message lists are built in owned alloc storage, while
176    /// all names and numeric properties borrow directly from `self`. Generated
177    /// no-alloc schemas should expose a const `SchemaRef` with borrowed lists.
178    pub fn as_schema_ref(&self) -> ref_::SchemaRef<'_> {
179        use ref_::{FieldRef, FieldTypeRef, MessageRef, PredictorKindRef, PredictorRef, RefList};
180
181        fn field_type<'a>(message: &'a MessageSchema, ty: &'a FieldType) -> FieldTypeRef<'a> {
182            match ty {
183                FieldType::Scalar(ScalarType::Enum(name)) => {
184                    let count = message
185                        .enums
186                        .iter()
187                        .find(|definition| definition.name == *name)
188                        .map(|definition| definition.variants.len() as u16)
189                        .unwrap_or(0);
190                    if count == 0 {
191                        FieldTypeRef::EnumNamed(name.as_str())
192                    } else {
193                        FieldTypeRef::Enum {
194                            variant_count: count,
195                        }
196                    }
197                }
198                FieldType::Scalar(scalar) => FieldTypeRef::Scalar(scalar.clone()),
199                FieldType::String => FieldTypeRef::String,
200                FieldType::List(scalar) => FieldTypeRef::List(scalar.clone()),
201            }
202        }
203
204        fn predictor_kind(kind: &PredictorKind) -> PredictorKindRef<'_> {
205            match kind {
206                PredictorKind::Linear => PredictorKindRef::Linear,
207                PredictorKind::Quadratic => PredictorKindRef::Quadratic,
208                PredictorKind::Cubic => PredictorKindRef::Cubic,
209                PredictorKind::Ewma => PredictorKindRef::Ewma,
210                PredictorKind::HoldLast => PredictorKindRef::HoldLast,
211                PredictorKind::Custom(name) => PredictorKindRef::Custom(name.as_str()),
212            }
213        }
214
215        let messages = self
216            .messages
217            .iter()
218            .map(|message| MessageRef {
219                name: message.name.as_str(),
220                id: message.id,
221                sync: message.sync,
222                fields: RefList::Owned(
223                    message
224                        .fields
225                        .iter()
226                        .map(|field| FieldRef {
227                            name: field.name.as_str(),
228                            ty: field_type(message, &field.ty),
229                            quantise: field.quantise,
230                            range: field.range,
231                            predictor: field.predictor.as_ref().map(|spec| PredictorRef {
232                                kind: predictor_kind(&spec.kind),
233                                window: spec.window,
234                                alpha: spec.alpha,
235                            }),
236                            tolerance_abs: field.tolerance.as_ref().and_then(|t| t.abs),
237                            tolerance_rel: field.tolerance.as_ref().and_then(|t| t.rel),
238                            tolerance_mode: field
239                                .tolerance
240                                .as_ref()
241                                .map(|t| t.mode)
242                                .unwrap_or(ToleranceMode::All),
243                            refresh: field.refresh.map(|value| value as u16),
244                            reset: field.reset.map(|value| value as u16),
245                            max_len: field.max_len,
246                        })
247                        .collect(),
248                ),
249            })
250            .collect();
251        ref_::SchemaRef {
252            messages: RefList::Owned(messages),
253        }
254    }
255
256    /// Compute storage layout for a message (alloc convenience).
257    pub fn storage_layout(&self, message_index: usize) -> Option<StorageLayout> {
258        try_storage_layout(&self.as_schema_ref(), message_index).ok()
259    }
260
261    /// A deterministic fingerprint of custom predictor declarations.
262    ///
263    /// It includes custom name, window, ordered params and version so both ends
264    /// cannot silently disagree about which model they run.
265    #[cfg(feature = "alloc")]
266    pub fn predictor_fingerprint(&self) -> u64 {
267        fn write_u64(hash: &mut u64, value: u64) {
268            for byte in value.to_le_bytes() {
269                *hash ^= u64::from(byte);
270                *hash = hash.wrapping_mul(0x100000001b3);
271            }
272        }
273        fn write_bytes(hash: &mut u64, bytes: &[u8]) {
274            write_u64(hash, bytes.len() as u64);
275            for byte in bytes {
276                *hash ^= u64::from(*byte);
277                *hash = hash.wrapping_mul(0x100000001b3);
278            }
279        }
280        let mut hash = 0xcbf29ce484222325u64;
281        for message in &self.messages {
282            write_bytes(&mut hash, message.qualified_name().as_bytes());
283            for field in &message.fields {
284                if let Some(spec) = &field.predictor {
285                    write_bytes(&mut hash, field.name.as_bytes());
286                    match &spec.kind {
287                        PredictorKind::Custom(name) => {
288                            write_bytes(&mut hash, b"custom");
289                            write_bytes(&mut hash, name.as_bytes());
290                        }
291                        PredictorKind::Linear => write_bytes(&mut hash, b"linear"),
292                        PredictorKind::Quadratic => write_bytes(&mut hash, b"quadratic"),
293                        PredictorKind::Cubic => write_bytes(&mut hash, b"cubic"),
294                        PredictorKind::Ewma => {
295                            write_bytes(&mut hash, b"ewma");
296                            write_u64(&mut hash, spec.alpha.map(f64::to_bits).unwrap_or(u64::MAX));
297                        }
298                        PredictorKind::HoldLast => write_bytes(&mut hash, b"hold_last"),
299                    }
300                    write_u64(&mut hash, spec.window.map(u64::from).unwrap_or(u64::MAX));
301                    write_u64(&mut hash, spec.params.len() as u64);
302                    for (name, value) in &spec.params {
303                        write_bytes(&mut hash, name.as_bytes());
304                        match value {
305                            PredictorParamValue::Int(v) => {
306                                write_bytes(&mut hash, b"i");
307                                write_u64(&mut hash, *v as u64);
308                            }
309                            PredictorParamValue::Float(v) => {
310                                write_bytes(&mut hash, b"f");
311                                write_u64(&mut hash, v.to_bits());
312                            }
313                        }
314                    }
315                    match spec.version {
316                        Some(version) => {
317                            write_bytes(&mut hash, b"v");
318                            write_u64(&mut hash, version);
319                        }
320                        None => write_bytes(&mut hash, b"none"),
321                    }
322                }
323            }
324        }
325        hash
326    }
327}
328
329#[cfg(feature = "alloc")]
330/// One message type in a schema set.
331#[derive(Debug, Clone, PartialEq)]
332pub struct MessageSchema {
333    pub namespace: Option<String>,
334    pub name: String,
335    pub id: u8,
336    pub sync: Option<SyncDefaults>,
337    pub enums: Vec<EnumDef>,
338    pub fields: Vec<FieldSchema>,
339}
340
341#[cfg(feature = "alloc")]
342impl MessageSchema {
343    /// The qualified name used to derive the default message ID.
344    #[cfg(feature = "alloc")]
345    pub fn qualified_name(&self) -> String {
346        match &self.namespace {
347            Some(namespace) => {
348                let mut name = String::with_capacity(namespace.len() + 1 + self.name.len());
349                name.push_str(namespace);
350                name.push('.');
351                name.push_str(&self.name);
352                name
353            }
354            None => self.name.clone(),
355        }
356    }
357}
358
359/// Message-level recovery defaults.
360#[derive(Debug, Clone, Copy, PartialEq, Eq)]
361pub struct SyncDefaults {
362    pub refresh: Option<u32>,
363    pub reset: Option<u32>,
364    pub max_resets_per_frame: Option<u8>,
365}
366
367#[cfg(feature = "alloc")]
368/// An enum declaration; the wire value is the variant index.
369#[derive(Debug, Clone, PartialEq, Eq)]
370pub struct EnumDef {
371    pub name: String,
372    pub variants: Vec<String>,
373}
374
375#[cfg(feature = "alloc")]
376/// One field of a message, in wire order.
377#[derive(Debug, Clone, PartialEq)]
378pub struct FieldSchema {
379    pub name: String,
380    pub ty: FieldType,
381    pub quantise: Option<f64>,
382    pub range: Option<(f64, f64)>,
383    pub predictor: Option<PredictorSpec>,
384    pub tolerance: Option<ToleranceSpec>,
385    pub refresh: Option<u32>,
386    pub reset: Option<u32>,
387    pub max_len: Option<u16>,
388}
389
390/// The wire type of a field.
391#[derive(Debug, Clone, PartialEq, Eq)]
392pub enum FieldType {
393    Scalar(ScalarType),
394    String,
395    List(ScalarType),
396}
397
398#[cfg(feature = "alloc")]
399impl FieldType {
400    /// Whether this field carries a numeric value suitable for extrapolation.
401    pub fn is_numeric(&self) -> bool {
402        match self {
403            Self::Scalar(scalar) | Self::List(scalar) => scalar.is_numeric(),
404            Self::String => false,
405        }
406    }
407
408    /// Whether this field is delivered by exact equality rather than tolerance.
409    pub fn is_opaque(&self) -> bool {
410        matches!(
411            self,
412            Self::String | Self::List(_) | Self::Scalar(ScalarType::Bool | ScalarType::Enum(_))
413        )
414    }
415
416    /// Whether this type requires `max_len`.
417    pub fn requires_max_len(&self) -> bool {
418        matches!(self, Self::String | Self::List(_))
419    }
420}
421
422/// A v1 scalar type, including enum references and list element types.
423#[derive(Debug, Clone, PartialEq, Eq)]
424pub enum ScalarType {
425    Bool,
426    U8,
427    U16,
428    U32,
429    U64,
430    I8,
431    I16,
432    I32,
433    I64,
434    F32,
435    F64,
436    #[cfg(feature = "alloc")]
437    Enum(String),
438    #[cfg(not(feature = "alloc"))]
439    Enum,
440}
441
442impl ScalarType {
443    /// Whether this scalar is a numeric predictor input.
444    pub fn is_numeric(&self) -> bool {
445        matches!(
446            self,
447            Self::U8
448                | Self::U16
449                | Self::U32
450                | Self::U64
451                | Self::I8
452                | Self::I16
453                | Self::I32
454                | Self::I64
455                | Self::F32
456                | Self::F64
457        )
458    }
459}
460
461/// A numeric parameter value for a custom predictor.
462#[derive(Debug, Clone, PartialEq)]
463pub enum PredictorParamValue {
464    Int(i64),
465    Float(f64),
466}
467
468impl Eq for PredictorParamValue {}
469
470#[cfg(feature = "alloc")]
471/// Predictor configuration declared inline on a field.
472#[derive(Debug, Clone, PartialEq)]
473pub struct PredictorSpec {
474    pub kind: PredictorKind,
475    pub window: Option<u8>,
476    /// Smoothing factor for the built-in `ewma` predictor, in `(0, 1]`.
477    pub alpha: Option<f64>,
478    /// Ordered custom-predictor parameters; insertion order is preserved.
479    #[cfg(feature = "alloc")]
480    pub params: Vec<(String, PredictorParamValue)>,
481    /// Optional custom-predictor version, folded into schema fingerprint.
482    pub version: Option<u64>,
483}
484
485// Alpha is validated finite, so derived PartialEq is reflexive for valid specs.
486#[cfg(feature = "alloc")]
487impl Eq for PredictorSpec {}
488
489/// Predictor kinds supported by the schema.
490#[derive(Debug, Clone, PartialEq, Eq)]
491pub enum PredictorKind {
492    Linear,
493    Quadratic,
494    Cubic,
495    Ewma,
496    HoldLast,
497    #[cfg(feature = "alloc")]
498    Custom(String),
499}
500
501impl PredictorKind {
502    /// Minimum window samples required before this predictor can predict.
503    pub const fn min_samples(&self) -> u8 {
504        match self {
505            Self::Linear => 2,
506            Self::Quadratic => 3,
507            Self::Cubic => 4,
508            Self::Ewma | Self::HoldLast => 1,
509            #[cfg(feature = "alloc")]
510            Self::Custom(_) => 1,
511        }
512    }
513
514    /// Whether this predictor needs a `window` parameter.
515    pub const fn needs_window(&self) -> bool {
516        match self {
517            Self::Linear | Self::Quadratic | Self::Cubic => true,
518            Self::Ewma | Self::HoldLast => false,
519            #[cfg(feature = "alloc")]
520            Self::Custom(_) => true,
521        }
522    }
523
524    /// Whether this is a user-registered custom predictor.
525    pub fn is_custom(&self) -> bool {
526        #[cfg(feature = "alloc")]
527        {
528            matches!(self, Self::Custom(_))
529        }
530        #[cfg(not(feature = "alloc"))]
531        {
532            false
533        }
534    }
535}
536
537/// Tolerance bounds on the delivered value of a numeric field.
538#[derive(Debug, Clone, PartialEq)]
539pub struct ToleranceSpec {
540    pub abs: Option<f64>,
541    pub rel: Option<f64>,
542    pub mode: ToleranceMode,
543}
544
545/// How absolute and relative bounds combine when both are present.
546#[derive(Debug, Clone, Copy, PartialEq, Eq)]
547pub enum ToleranceMode {
548    All,
549    Any,
550}
551
552#[cfg(feature = "alloc")]
553/// A non-fatal schema warning.
554#[derive(Debug, Clone, PartialEq, Eq)]
555pub struct Warning {
556    pub kind: WarningKind,
557    pub message: String,
558}
559
560/// Categories of schema warning.
561#[derive(Debug, Clone, Copy, PartialEq, Eq)]
562pub enum WarningKind {
563    NoRecoveryConfigured,
564}
565
566/// Every schema grammar or validation failure.
567#[cfg(feature = "alloc")]
568#[derive(Debug, Clone, PartialEq)]
569pub enum SchemaError {
570    DuplicateField(usize),
571    UnknownType(String),
572    UnknownPredictorKind(String),
573    MissingPredictorParam(String),
574    WindowTooSmall(usize),
575    WindowTooLarge(usize),
576    PredictorWithoutTolerance(usize),
577    ToleranceWithoutPredictor(usize),
578    NoToleranceBound(usize),
579    ToleranceBelowQuantiseStep(usize),
580    RangeWithoutQuantise(usize),
581    InvalidRange(usize),
582    QuantiseNotPositive(usize),
583    QuantiseNotAllowedForType(usize),
584    ResetNotMultipleOfRefresh(usize),
585    RefreshBelowWindow(usize),
586    ZeroPeriod(usize),
587    TooManyFields(usize),
588    UnknownEnum(usize),
589    DuplicateEnum(usize),
590    EnumNoVariants(usize),
591    DuplicateVariant(usize),
592    EnumTooLarge(usize),
593    InvalidIdentifier(String),
594    MissingMaxLen(usize),
595    MaxLenOnFixedType(usize),
596    ZeroMaxLen(usize),
597    ListElementNotScalar(usize),
598    PredictorNotAllowedForType(usize),
599    ToleranceNotAllowedForType(usize),
600    Unsupported(String),
601}
602
603#[cfg(not(feature = "alloc"))]
604#[derive(Debug, Clone, PartialEq)]
605pub enum SchemaError {
606    Invalid,
607}
608
609#[cfg(feature = "alloc")]
610impl fmt::Display for SchemaError {
611    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
612        write!(f, "{self:?}")
613    }
614}
615
616/// Whether a name matches `[A-Za-z_][A-Za-z0-9_]*`.
617pub fn is_identifier(name: &str) -> bool {
618    let mut chars = name.chars();
619    let Some(first) = chars.next() else {
620        return false;
621    };
622    if !(first.is_ascii_alphabetic() || first == '_') {
623        return false;
624    }
625    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
626}
627
628/// Returns a fixed value used by the M0 scaffolding smoke test.
629pub fn schema_smoke_value() -> u8 {
630    42
631}
632
633#[cfg(test)]
634mod tests {
635    #[test]
636    fn smoke_test() {
637        assert_eq!(crate::schema_smoke_value(), 42);
638    }
639}