1#![no_std]
2
3pub 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
17pub const MAX_FIELDS: usize = 64;
19pub const MAX_WINDOW: u8 = 64;
21pub const MAX_MESSAGES: usize = 256;
23
24#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum StorageError {
49 MessageNotFound,
51 MissingMaxLen,
53 TooLarge,
55}
56
57pub 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}
146pub const MAX_LEN: u16 = u16::MAX;
148pub const MAX_ENUM_VARIANTS: usize = 65_536;
150
151#[cfg(feature = "alloc")]
152#[derive(Debug, Clone, PartialEq)]
154pub struct ParsedSchema {
155 pub set: SchemaSet,
156 pub warnings: Vec<Warning>,
157}
158
159#[cfg(feature = "alloc")]
160#[derive(Debug, Clone, PartialEq)]
162pub struct SchemaSet {
163 pub messages: Vec<MessageSchema>,
164}
165
166#[cfg(feature = "alloc")]
167impl SchemaSet {
168 pub fn id_byte_present(&self) -> bool {
170 self.messages.len() > 1
171 }
172
173 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 pub fn storage_layout(&self, message_index: usize) -> Option<StorageLayout> {
258 try_storage_layout(&self.as_schema_ref(), message_index).ok()
259 }
260
261 #[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#[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 #[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#[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#[derive(Debug, Clone, PartialEq, Eq)]
370pub struct EnumDef {
371 pub name: String,
372 pub variants: Vec<String>,
373}
374
375#[cfg(feature = "alloc")]
376#[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#[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 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 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 pub fn requires_max_len(&self) -> bool {
418 matches!(self, Self::String | Self::List(_))
419 }
420}
421
422#[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 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#[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#[derive(Debug, Clone, PartialEq)]
473pub struct PredictorSpec {
474 pub kind: PredictorKind,
475 pub window: Option<u8>,
476 pub alpha: Option<f64>,
478 #[cfg(feature = "alloc")]
480 pub params: Vec<(String, PredictorParamValue)>,
481 pub version: Option<u64>,
483}
484
485#[cfg(feature = "alloc")]
487impl Eq for PredictorSpec {}
488
489#[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 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 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 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#[derive(Debug, Clone, PartialEq)]
539pub struct ToleranceSpec {
540 pub abs: Option<f64>,
541 pub rel: Option<f64>,
542 pub mode: ToleranceMode,
543}
544
545#[derive(Debug, Clone, Copy, PartialEq, Eq)]
547pub enum ToleranceMode {
548 All,
549 Any,
550}
551
552#[cfg(feature = "alloc")]
553#[derive(Debug, Clone, PartialEq, Eq)]
555pub struct Warning {
556 pub kind: WarningKind,
557 pub message: String,
558}
559
560#[derive(Debug, Clone, Copy, PartialEq, Eq)]
562pub enum WarningKind {
563 NoRecoveryConfigured,
564}
565
566#[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
616pub 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
628pub 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}