Skip to main content

zenkey_model/
packed.rs

1//! Packed records (core §7.6, 0.75; #979 B1): a type kind whose record is
2//! bit fields, each as wide as the codes its declaration names.
3//!
4//! - **The schema file** ([`PackedDoc::read`]) is strict JSON: `types`, each
5//!   a record of `fields`, every field `int`, `fixed`, `enum`, `bool`,
6//!   `counter` or `time`, optionally optional, and `"..."` the extension
7//!   marker. Its lints are E038 to E045 (core §9.2), in cascade 7's order.
8//! - **The layout** ([`Layout`]) is each item's width, the record's
9//!   shortest and longest length, its layout form (the root's wire, without
10//!   names) and the tag, the low four bits of the form's sha256.
11//! - **The codec** ([`Layout::write`], [`Layout::read`]) is interpreted
12//!   over `serde_json::Value`, as core §7.6's JSON reading spells a record.
13//!   It is the source of truth that generated code (B2) matches, checked
14//!   against `spec/conformance/packed/vectors.json`.
15//!
16//! Fixed point is computed in exact decimal arithmetic over big integers,
17//! never in binary floating point: a JSON number is read by its shortest
18//! decimal text, as JSON writes it.
19
20use std::collections::{BTreeMap, BTreeSet};
21use std::fmt::Write as _;
22
23use num_bigint::{BigInt, Sign};
24use num_integer::Integer as _;
25use num_traits::{One as _, Signed as _, ToPrimitive as _, Zero as _};
26use serde_json::{Map, Value};
27use sha2::{Digest, Sha256};
28
29/// The extension marker, as `fields` writes it.
30pub const MARKER: &str = "...";
31
32/// The six field types of core §7.6, by their `type` spelling.
33pub const FIELD_TYPES: &[&str] = &["int", "fixed", "enum", "bool", "counter", "time"];
34
35/// The reserved codes, in the order they take the top codes of a width.
36pub const RESERVED: &[&str] = &["not_available", "error", "out_of_range"];
37
38/// The most digits a writer's decimal may carry, either side of the point,
39/// once its exponent is applied. A model limit, not the text's: a value
40/// past it is refused as `value`.
41const INPUT_DIGITS: u32 = 1024;
42
43// --- Exact decimals ---------------------------------------------------------
44
45/// An exact decimal: `m / 10^e`.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Decimal {
48    m: BigInt,
49    e: u32,
50}
51
52impl Decimal {
53    /// A declaration's decimal string, `-?(0|[1-9][0-9]*)(\.[0-9]+)?`.
54    #[must_use]
55    pub fn parse(s: &str) -> Option<Self> {
56        let body = s.strip_prefix('-').unwrap_or(s);
57        let (int, frac) = match body.split_once('.') {
58            Some((i, f)) => (i, Some(f)),
59            None => (body, None),
60        };
61        let digits = |t: &str| !t.is_empty() && t.bytes().all(|b| b.is_ascii_digit());
62        if !digits(int) || (int.len() > 1 && int.starts_with('0')) {
63            return None;
64        }
65        if frac.is_some_and(|f| !digits(f)) {
66            return None;
67        }
68        Self::from_parts(s.starts_with('-'), int, frac.unwrap_or(""), 0)
69    }
70
71    /// A writer's decimal: a JSON number's text (RFC 8259 §6, core §7.6
72    /// "What a writer takes"), the declaration grammar with an exponent
73    /// allowed: no `+`, no leading zero, no bare point.
74    #[must_use]
75    pub fn parse_input(s: &str) -> Option<Self> {
76        let neg = s.starts_with('-');
77        let body = s.strip_prefix('-').unwrap_or(s);
78        let (mant, exp) = match body.find(['e', 'E']) {
79            Some(i) => (&body[..i], Some(&body[i + 1..])),
80            None => (body, None),
81        };
82        let (int, frac) = match mant.split_once('.') {
83            Some((i, f)) => (i, f),
84            None => (mant, ""),
85        };
86        let digits = |t: &str| !t.is_empty() && t.bytes().all(|b| b.is_ascii_digit());
87        if !digits(int) || (int.len() > 1 && int.starts_with('0')) {
88            return None;
89        }
90        if mant.contains('.') && !digits(frac) {
91            return None;
92        }
93        let exp: i64 = match exp {
94            None => 0,
95            Some(x) => {
96                let d = x.strip_prefix(['+', '-']).unwrap_or(x);
97                if !digits(d) || d.len() > 9 {
98                    return None;
99                }
100                x.parse().ok()?
101            }
102        };
103        Self::from_parts(neg, int, frac, exp)
104    }
105
106    fn from_parts(neg: bool, int: &str, frac: &str, exp: i64) -> Option<Self> {
107        let text = format!("{int}{frac}");
108        let mut m: BigInt = text.parse().ok()?;
109        let scale = i64::try_from(frac.len()).ok()? - exp;
110        let width = i64::try_from(int.len()).ok()? + exp;
111        if scale > i64::from(INPUT_DIGITS) || width > i64::from(INPUT_DIGITS) {
112            return None;
113        }
114        let e = if scale < 0 {
115            m *= pow10(u32::try_from(-scale).ok()?);
116            0
117        } else {
118            u32::try_from(scale).ok()?
119        };
120        if neg {
121            m = -m;
122        }
123        Some(Self { m, e }.normalized())
124    }
125
126    fn normalized(mut self) -> Self {
127        let ten = BigInt::from(10);
128        while self.e > 0 && (&self.m % &ten).is_zero() {
129            self.m /= &ten;
130            self.e -= 1;
131        }
132        self
133    }
134
135    /// `m` at the scale `e` (which is at least this decimal's).
136    fn at(&self, e: u32) -> BigInt {
137        &self.m * pow10(e - self.e)
138    }
139
140    fn sub(&self, o: &Self) -> Self {
141        let e = self.e.max(o.e);
142        Self {
143            m: self.at(e) - o.at(e),
144            e,
145        }
146        .normalized()
147    }
148
149    fn add(&self, o: &Self) -> Self {
150        let e = self.e.max(o.e);
151        Self {
152            m: self.at(e) + o.at(e),
153            e,
154        }
155        .normalized()
156    }
157
158    fn mul_int(&self, k: &BigInt) -> Self {
159        Self {
160            m: &self.m * k,
161            e: self.e,
162        }
163        .normalized()
164    }
165
166    fn is_positive(&self) -> bool {
167        self.m.is_positive()
168    }
169
170    /// An integer, as a decimal.
171    pub(crate) fn of_i128(v: i128) -> Self {
172        Self {
173            m: BigInt::from(v),
174            e: 0,
175        }
176    }
177
178    /// `|self − o|`: how far apart two values are, which a frame's
179    /// deadband weighs (core §7.7).
180    pub(crate) fn distance(&self, o: &Self) -> Self {
181        let d = self.sub(o);
182        Self {
183            m: d.m.abs(),
184            e: d.e,
185        }
186    }
187
188    /// `self / o`, when it is an integer.
189    fn div_exact(&self, o: &Self) -> Option<BigInt> {
190        let e = self.e.max(o.e);
191        let (q, r) = self.at(e).div_mod_floor(&o.at(e));
192        r.is_zero().then_some(q)
193    }
194
195    /// `self / o` rounded to the nearest integer, a tie to the even one.
196    fn div_round_even(&self, o: &Self) -> BigInt {
197        let e = self.e.max(o.e);
198        let d = o.at(e);
199        let (q, r) = self.at(e).div_mod_floor(&d);
200        let twice: BigInt = &r * BigInt::from(2u8);
201        let up = match twice.cmp(&d) {
202            std::cmp::Ordering::Less => false,
203            std::cmp::Ordering::Greater => true,
204            std::cmp::Ordering::Equal => q.is_odd(),
205        };
206        if up { q + BigInt::one() } else { q }
207    }
208}
209
210impl PartialOrd for Decimal {
211    fn partial_cmp(&self, o: &Self) -> Option<std::cmp::Ordering> {
212        Some(self.cmp(o))
213    }
214}
215
216impl Ord for Decimal {
217    fn cmp(&self, o: &Self) -> std::cmp::Ordering {
218        let e = self.e.max(o.e);
219        self.at(e).cmp(&o.at(e))
220    }
221}
222
223impl std::fmt::Display for Decimal {
224    /// The shortest form (core §7.6): no zero at the end of a fraction, no
225    /// point without a digit after it, `0` for zero.
226    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227        let n = self.clone().normalized();
228        if n.m.is_zero() {
229            return f.write_str("0");
230        }
231        let digits = n.m.abs().to_string();
232        let e = n.e as usize;
233        let sign = if n.m.sign() == Sign::Minus { "-" } else { "" };
234        if e == 0 {
235            return write!(f, "{sign}{digits}");
236        }
237        let padded = format!("{digits:0>width$}", width = e + 1);
238        let (int, frac) = padded.split_at(padded.len() - e);
239        write!(f, "{sign}{int}.{frac}")
240    }
241}
242
243impl std::str::FromStr for Decimal {
244    type Err = WriteRefusal;
245
246    /// A writer's decimal ([`Decimal::parse_input`]): `value` when it does
247    /// not read.
248    fn from_str(s: &str) -> Result<Self, WriteRefusal> {
249        Self::parse_input(s).ok_or(WriteRefusal::Value)
250    }
251}
252
253impl From<i64> for Decimal {
254    fn from(v: i64) -> Self {
255        Self {
256            m: BigInt::from(v),
257            e: 0,
258        }
259    }
260}
261
262impl Decimal {
263    /// A binary float, read by its shortest round-trip text, as a JSON
264    /// writer spells it (so `0.15` is the decimal 0.15); `None` for a NaN
265    /// or an infinity.
266    #[must_use]
267    pub fn from_f64(x: f64) -> Option<Self> {
268        if !x.is_finite() {
269            return None;
270        }
271        Self::parse_input(&format!("{x}"))
272    }
273
274    /// The nearest binary float: for display and arithmetic outside the
275    /// codec, never for a code.
276    #[must_use]
277    pub fn to_f64(&self) -> f64 {
278        self.to_string().parse().unwrap_or(f64::NAN)
279    }
280}
281
282fn pow10(n: u32) -> BigInt {
283    num_traits::pow(BigInt::from(10), n as usize)
284}
285
286/// The fewest bits that hold `codes` codes, `⌈log₂ codes⌉`.
287fn bits_for(codes: &BigInt) -> u64 {
288    if codes <= &BigInt::one() {
289        0
290    } else {
291        (codes - 1u32).bits()
292    }
293}
294
295// --- The schema file ---------------------------------------------------------
296
297/// One lint finding in a packed file (core §9.2's E038 to E045).
298#[derive(Debug, Clone, PartialEq, Eq)]
299pub struct Finding {
300    pub code: &'static str,
301    /// Where in the file: `""` for its top level, `types.<Name>`, or
302    /// `types.<Name>.fields[<i>]`.
303    pub at: String,
304    pub message: String,
305}
306
307/// A field's type, with what its declaration fixes.
308#[derive(Debug, Clone, PartialEq, Eq)]
309pub enum FieldKind {
310    Int {
311        minimum: i64,
312        maximum: i64,
313        reserved: Vec<&'static str>,
314    },
315    Fixed {
316        minimum: Decimal,
317        maximum: Decimal,
318        resolution: Decimal,
319        reserved: Vec<&'static str>,
320        /// `(maximum − minimum) / resolution + 1`.
321        values: u128,
322    },
323    Enum {
324        values: Vec<String>,
325        escape: bool,
326    },
327    Bool,
328    Counter,
329    Time {
330        ms: bool,
331    },
332}
333
334impl FieldKind {
335    #[must_use]
336    pub fn as_str(&self) -> &'static str {
337        match self {
338            Self::Int { .. } => "int",
339            Self::Fixed { .. } => "fixed",
340            Self::Enum { .. } => "enum",
341            Self::Bool => "bool",
342            Self::Counter => "counter",
343            Self::Time { .. } => "time",
344        }
345    }
346}
347
348/// One field of a layout.
349#[derive(Debug, Clone, PartialEq, Eq)]
350pub struct Field {
351    pub name: String,
352    pub kind: FieldKind,
353    /// From 1 to 64.
354    pub width: u32,
355    pub optional: bool,
356}
357
358/// An item of a record's `fields`.
359#[derive(Debug, Clone, PartialEq, Eq)]
360pub enum Item {
361    Field(Field),
362    /// The extension marker, one bit.
363    Marker,
364}
365
366/// A packed file read and linted: every type its `types` names with a type
367/// name, and the layout of each that has no finding.
368#[derive(Debug, Clone, Default)]
369pub struct PackedDoc {
370    /// `None` for a type whose record has a finding.
371    pub types: BTreeMap<String, Option<Layout>>,
372    pub findings: Vec<Finding>,
373}
374
375fn is_type_name(s: &str) -> bool {
376    let mut b = s.bytes();
377    b.next().is_some_and(|c| c.is_ascii_uppercase()) && b.all(|c| c.is_ascii_alphanumeric())
378}
379
380fn is_field_name(s: &str) -> bool {
381    let mut b = s.bytes();
382    b.next().is_some_and(|c| c.is_ascii_lowercase())
383        && b.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_')
384}
385
386fn is_value_name(s: &str) -> bool {
387    let mut b = s.bytes();
388    b.next().is_some_and(|c| c.is_ascii_alphabetic())
389        && b.all(|c| c.is_ascii_alphanumeric() || c == b'_')
390}
391
392/// The members a field type takes beside `name`, `type`, `optional` and
393/// `description`, and those it needs.
394fn members(ty: &str) -> (&'static [&'static str], &'static [&'static str]) {
395    match ty {
396        "int" => (&["minimum", "maximum", "reserved"], &["minimum", "maximum"]),
397        "fixed" => (
398            &["minimum", "maximum", "resolution", "reserved"],
399            &["minimum", "maximum", "resolution"],
400        ),
401        "enum" => (&["values", "escape", "width"], &["values"]),
402        "counter" => (&["width"], &["width"]),
403        "time" => (&["ms"], &[]),
404        _ => (&[], &[]),
405    }
406}
407
408/// The first shape problem of a field object, for its one E038.
409fn field_shape(m: &Map<String, Value>, ty: &str) -> Option<String> {
410    let (takes, needs) = members(ty);
411    for k in m.keys() {
412        if !["name", "type", "optional", "description"].contains(&k.as_str())
413            && !takes.contains(&k.as_str())
414        {
415            return Some(format!("a `{ty}` field takes no member {k:?}"));
416        }
417    }
418    for k in std::iter::once(&"name").chain(needs) {
419        if !m.contains_key(*k) {
420            return Some(format!("a `{ty}` field needs `{k}`"));
421        }
422    }
423    match m.get("name") {
424        Some(Value::String(n)) if is_field_name(n) => {}
425        Some(v) => return Some(format!("`name` {v} is not [a-z][a-z0-9_]*")),
426        None => {}
427    }
428    let is_bool = |k: &str| m.get(k).is_none_or(Value::is_boolean);
429    let is_int = |k: &str| m.get(k).is_none_or(|v| v.as_i64().is_some());
430    let is_str = |k: &str| m.get(k).is_none_or(Value::is_string);
431    if !is_bool("optional") {
432        return Some("`optional` is not a boolean".into());
433    }
434    if !is_str("description") {
435        return Some("`description` is not a string".into());
436    }
437    let list_of = |k: &str, ok: &dyn Fn(&str) -> bool| match m.get(k) {
438        None => true,
439        Some(Value::Array(a)) => a.iter().all(|v| v.as_str().is_some_and(ok)),
440        Some(_) => false,
441    };
442    let problem = match ty {
443        "int" if !is_int("minimum") || !is_int("maximum") => {
444            Some("`minimum` and `maximum` are integers")
445        }
446        "fixed" if !is_str("minimum") || !is_str("maximum") || !is_str("resolution") => {
447            Some("`minimum`, `maximum` and `resolution` are decimal strings")
448        }
449        "int" | "fixed" if !list_of("reserved", &|s| RESERVED.contains(&s)) => {
450            Some("`reserved` lists not_available, error and out_of_range")
451        }
452        "enum" if !list_of("values", &is_value_name) => {
453            Some("`values` is a list of names [A-Za-z][A-Za-z0-9_]*")
454        }
455        "enum" if !is_bool("escape") => Some("`escape` is not a boolean"),
456        "enum" | "counter" if !is_int("width") => Some("`width` is not an integer"),
457        "time" if !is_bool("ms") => Some("`ms` is not a boolean"),
458        _ => None,
459    };
460    problem.map(str::to_owned)
461}
462
463/// Repeats in a list of names: each one after its first.
464fn repeats<'a>(names: impl IntoIterator<Item = &'a str>) -> Vec<&'a str> {
465    let mut seen = BTreeSet::new();
466    names.into_iter().filter(|n| !seen.insert(*n)).collect()
467}
468
469fn strings(v: Option<&Value>) -> Vec<&str> {
470    v.and_then(Value::as_array)
471        .map(|a| a.iter().filter_map(Value::as_str).collect())
472        .unwrap_or_default()
473}
474
475fn reserved_of(m: &Map<String, Value>) -> Vec<&'static str> {
476    let listed = strings(m.get("reserved"));
477    RESERVED
478        .iter()
479        .copied()
480        .filter(|r| listed.contains(r))
481        .collect()
482}
483
484/// A field's E039, E040 or E041, the first met in cascade 7's order, or
485/// its layout.
486fn field_of(m: &Map<String, Value>, ty: &str) -> Result<Field, (&'static str, String)> {
487    let name = m["name"].as_str().unwrap_or_default().to_owned();
488    let optional = m.get("optional").and_then(Value::as_bool).unwrap_or(false);
489    let wide = |codes: &BigInt| -> Result<u32, (&'static str, String)> {
490        let w = bits_for(codes);
491        if (1..=64).contains(&w) {
492            Ok(u32::try_from(w).unwrap_or(64))
493        } else {
494            Err((
495                "E041",
496                format!("{codes} codes need {w} bits; a field is 1 to 64"),
497            ))
498        }
499    };
500    let (kind, width) = match ty {
501        "int" => {
502            let (lo, hi) = (
503                m["minimum"].as_i64().unwrap_or(0),
504                m["maximum"].as_i64().unwrap_or(0),
505            );
506            if lo > hi {
507                return Err(("E039", format!("`minimum` {lo} is above `maximum` {hi}")));
508            }
509            let reserved = reserved_of(m);
510            let codes = BigInt::from(hi) - BigInt::from(lo) + BigInt::from(1 + reserved.len());
511            let width = wide(&codes)?;
512            (
513                FieldKind::Int {
514                    minimum: lo,
515                    maximum: hi,
516                    reserved,
517                },
518                width,
519            )
520        }
521        "fixed" => {
522            let read = |k: &str| {
523                let s = m[k].as_str().unwrap_or_default();
524                Decimal::parse(s).ok_or_else(|| ("E040", format!("`{k}` {s:?} is not a decimal")))
525            };
526            let (lo, hi, res) = (read("minimum")?, read("maximum")?, read("resolution")?);
527            if lo > hi {
528                return Err(("E039", format!("`minimum` {lo} is above `maximum` {hi}")));
529            }
530            if !res.is_positive() {
531                return Err(("E040", format!("`resolution` {res} is not above 0")));
532            }
533            let Some(steps) = hi.sub(&lo).div_exact(&res) else {
534                return Err((
535                    "E040",
536                    format!("`resolution` {res} does not divide {hi} − {lo}"),
537                ));
538            };
539            let reserved = reserved_of(m);
540            let values: BigInt = steps + BigInt::one();
541            let width = wide(&(&values + BigInt::from(reserved.len())))?;
542            (
543                FieldKind::Fixed {
544                    minimum: lo,
545                    maximum: hi,
546                    resolution: res,
547                    reserved,
548                    values: values.to_u128().unwrap_or(u128::MAX),
549                },
550                width,
551            )
552        }
553        "enum" => {
554            let values: Vec<String> = strings(m.get("values"))
555                .into_iter()
556                .map(str::to_owned)
557                .collect();
558            if values.is_empty() {
559                return Err(("E039", "an enum with no value".into()));
560            }
561            let escape = m.get("escape").and_then(Value::as_bool).unwrap_or(false);
562            let need = bits_for(&BigInt::from(values.len() + usize::from(escape)));
563            let width = match m.get("width").and_then(Value::as_i64) {
564                Some(w) if !(1..=64).contains(&w) || u64::try_from(w).unwrap_or(0) < need => {
565                    return Err((
566                        "E041",
567                        format!("`width` {w}: the enum needs {need} bits, and a field is 1 to 64"),
568                    ));
569                }
570                Some(w) => u32::try_from(w).unwrap_or(64),
571                None => wide(&BigInt::from(values.len() + usize::from(escape)))?,
572            };
573            (FieldKind::Enum { values, escape }, width)
574        }
575        "bool" => (FieldKind::Bool, 1),
576        "counter" => {
577            let w = m["width"].as_i64().unwrap_or(0);
578            if !(1..=64).contains(&w) {
579                return Err(("E041", format!("a counter's `width` {w} is not 1 to 64")));
580            }
581            (FieldKind::Counter, u32::try_from(w).unwrap_or(64))
582        }
583        "time" => {
584            let ms = m.get("ms").and_then(Value::as_bool).unwrap_or(false);
585            (FieldKind::Time { ms }, if ms { 42 } else { 32 })
586        }
587        _ => unreachable!("checked by E043"),
588    };
589    Ok(Field {
590        name,
591        kind,
592        width,
593        optional,
594    })
595}
596
597impl PackedDoc {
598    /// Reads and lints a packed document (core §7.6, §9.2's E038 to E045 and
599    /// cascade 7).
600    #[must_use]
601    #[allow(clippy::too_many_lines)]
602    pub fn read(doc: &Value) -> Self {
603        let mut findings = Vec::new();
604        let mut find = |code: &'static str, at: String, message: String| {
605            findings.push(Finding { code, at, message });
606        };
607        let Value::Object(top) = doc else {
608            find(
609                "E038",
610                String::new(),
611                "the top level is not an object".into(),
612            );
613            return Self {
614                types: BTreeMap::new(),
615                findings,
616            };
617        };
618        let mut types: BTreeMap<String, Option<Layout>> = BTreeMap::new();
619        let problem = top
620            .keys()
621            .find(|k| *k != "types" && *k != "description")
622            .map(|k| format!("the top level takes no member {k:?}"))
623            .or_else(|| {
624                (!top.get("description").is_none_or(Value::is_string))
625                    .then(|| "`description` is not a string".to_owned())
626            })
627            .or_else(|| match top.get("types") {
628                Some(Value::Object(_)) => None,
629                Some(_) => Some("`types` is not an object".into()),
630                None => Some("there is no `types`".into()),
631            });
632        if let Some(p) = problem {
633            find("E038", String::new(), p);
634        }
635        let Some(Value::Object(defs)) = top.get("types") else {
636            return Self { types, findings };
637        };
638        for (name, record) in defs {
639            let at = format!("types.{name}");
640            if !is_type_name(name) {
641                find(
642                    "E038",
643                    at,
644                    format!("{name:?} is not a type name [A-Z][A-Za-z0-9]*"),
645                );
646                continue;
647            }
648            let mut clean = true;
649            let Value::Object(rec) = record else {
650                find("E038", at, "a record is an object".into());
651                types.insert(name.clone(), None);
652                continue;
653            };
654            let problem = rec
655                .keys()
656                .find(|k| *k != "fields" && *k != "description")
657                .map(|k| format!("a record takes no member {k:?}"))
658                .or_else(|| {
659                    (!rec.get("description").is_none_or(Value::is_string))
660                        .then(|| "`description` is not a string".to_owned())
661                })
662                .or_else(|| match rec.get("fields") {
663                    Some(Value::Array(_)) => None,
664                    Some(_) => Some("`fields` is not a list".into()),
665                    None => Some("a record needs `fields`".into()),
666                });
667            if let Some(p) = problem {
668                find("E038", at.clone(), p);
669                clean = false;
670            }
671            let Some(Value::Array(list)) = rec.get("fields") else {
672                types.insert(name.clone(), None);
673                continue;
674            };
675            // Each item: a marker, a field read whole, or a field with a
676            // finding (which takes no part in E042 and E045).
677            let mut items: Vec<Option<Item>> = Vec::new();
678            let mut sound: Vec<(usize, &str, bool)> = Vec::new();
679            let mut objects = 0;
680            for (i, item) in list.iter().enumerate() {
681                let fat = format!("{at}.fields[{i}]");
682                if item.as_str() == Some(MARKER) {
683                    items.push(Some(Item::Marker));
684                    continue;
685                }
686                let Value::Object(f) = item else {
687                    find(
688                        "E038",
689                        fat,
690                        "an item is a field object or the marker \"...\"".into(),
691                    );
692                    items.push(None);
693                    clean = false;
694                    continue;
695                };
696                objects += 1;
697                let ty = match f.get("type") {
698                    Some(Value::String(t)) if FIELD_TYPES.contains(&t.as_str()) => t.as_str(),
699                    Some(Value::String(t)) => {
700                        find(
701                            "E043",
702                            fat,
703                            format!("`type` {t:?} names no field type of core §7.6"),
704                        );
705                        items.push(None);
706                        clean = false;
707                        continue;
708                    }
709                    _ => {
710                        find("E038", fat, "a field needs `type`, a string".into());
711                        items.push(None);
712                        clean = false;
713                        continue;
714                    }
715                };
716                if let Some(p) = field_shape(f, ty) {
717                    find("E038", fat, p);
718                    items.push(None);
719                    clean = false;
720                    continue;
721                }
722                let name = f["name"].as_str().unwrap_or_default();
723                let optional = f.get("optional").and_then(Value::as_bool).unwrap_or(false);
724                sound.push((i, name, optional));
725                for key in ["values", "reserved"] {
726                    for r in repeats(strings(f.get(key))) {
727                        find("E042", fat.clone(), format!("{r:?} is repeated in `{key}`"));
728                        clean = false;
729                    }
730                }
731                match field_of(f, ty) {
732                    Ok(field) => items.push(Some(Item::Field(field))),
733                    Err((code, message)) => {
734                        find(code, fat, message);
735                        items.push(None);
736                        clean = false;
737                    }
738                }
739            }
740            for r in repeats(sound.iter().map(|(_, n, _)| *n)) {
741                find(
742                    "E042",
743                    at.clone(),
744                    format!("the field name {r:?} is repeated"),
745                );
746                clean = false;
747            }
748            let first_marker = list.iter().position(|v| v.as_str() == Some(MARKER));
749            for (i, item) in list.iter().enumerate() {
750                if item.as_str() == Some(MARKER) && i > 0 && list[i - 1].as_str() == Some(MARKER) {
751                    find(
752                        "E045",
753                        format!("{at}.fields[{i}]"),
754                        "a marker right after another".into(),
755                    );
756                    clean = false;
757                }
758            }
759            if let Some(m0) = first_marker {
760                for (i, n, optional) in &sound {
761                    if *i > m0 && !optional {
762                        find(
763                            "E045",
764                            format!("{at}.fields[{i}]"),
765                            format!("{n:?} is after a marker, and is not optional"),
766                        );
767                        clean = false;
768                    }
769                }
770            }
771            if objects == 0 {
772                find("E039", at.clone(), "a record with no field".into());
773                clean = false;
774            }
775            let layout = if clean {
776                items
777                    .into_iter()
778                    .collect::<Option<Vec<Item>>>()
779                    .map(Layout::new)
780            } else {
781                None
782            };
783            types.insert(name.clone(), layout);
784        }
785        Self { types, findings }
786    }
787}
788
789// --- The layout ---------------------------------------------------------------
790
791/// A type's layout: its items, its layout form and its tag (core §7.6).
792#[derive(Debug, Clone, PartialEq, Eq)]
793pub struct Layout {
794    pub items: Vec<Item>,
795    form: Value,
796    sha256: [u8; 32],
797}
798
799/// An item's width and start, as `describe` reports them.
800#[derive(Debug, Clone, PartialEq, Eq)]
801pub struct Slot {
802    /// `None` for a marker.
803    pub name: Option<String>,
804    pub width: u32,
805    pub optional: bool,
806    /// The bit where the item starts, `None` once an optional field or a
807    /// marker before it makes it vary.
808    pub offset: Option<u64>,
809}
810
811impl Field {
812    fn form(&self) -> Value {
813        let mut f = Map::new();
814        f.insert("type".into(), self.kind.as_str().into());
815        f.insert("width".into(), self.width.into());
816        f.insert("optional".into(), self.optional.into());
817        match &self.kind {
818            FieldKind::Int {
819                minimum,
820                maximum,
821                reserved,
822            } => {
823                f.insert("minimum".into(), (*minimum).into());
824                f.insert("maximum".into(), (*maximum).into());
825                f.insert("reserved".into(), reserved.clone().into());
826            }
827            FieldKind::Fixed {
828                minimum,
829                maximum,
830                resolution,
831                reserved,
832                ..
833            } => {
834                f.insert("minimum".into(), minimum.to_string().into());
835                f.insert("maximum".into(), maximum.to_string().into());
836                f.insert("resolution".into(), resolution.to_string().into());
837                f.insert("reserved".into(), reserved.clone().into());
838            }
839            FieldKind::Enum { values, escape } => {
840                f.insert("escape".into(), (*escape).into());
841                if !escape {
842                    f.insert("values".into(), values.len().into());
843                }
844            }
845            FieldKind::Time { ms } => {
846                f.insert("ms".into(), (*ms).into());
847            }
848            FieldKind::Bool | FieldKind::Counter => {}
849        }
850        Value::Object(f)
851    }
852
853    fn top(&self) -> u64 {
854        top_code(self.width)
855    }
856
857    fn reserved_code(&self, i: usize) -> u64 {
858        self.top() - i as u64
859    }
860}
861
862/// The all-ones code of a width from 1 to 64: the first reserved code, an
863/// enum's escape.
864#[must_use]
865pub const fn top_code(width: u32) -> u64 {
866    if width >= 64 {
867        u64::MAX
868    } else {
869        (1u64 << width) - 1
870    }
871}
872
873/// The reserved code `name` takes in a field of `width` whose `reserved`
874/// lists `declared` (core §7.6: the top codes, from all ones down, in
875/// [`RESERVED`]'s order), `None` when it does not declare it.
876#[must_use]
877pub fn reserved_code(width: u32, declared: &[&str], name: &str) -> Option<u64> {
878    RESERVED
879        .iter()
880        .filter(|r| declared.contains(r))
881        .position(|r| *r == name)
882        .map(|i| top_code(width) - i as u64)
883}
884
885/// The deployment epoch E of a deployment that states none (core §7.6:
886/// "One that states none has E = 0"): the Unix epoch, so a `time` field's
887/// 32 bits are Unix seconds, to 2106. The codec takes the epoch a
888/// deployment states as an `Option`, `None` where it states none, which
889/// reads and writes under this one; nothing carries one yet (#980's
890/// catalog will).
891pub const DEFAULT_EPOCH: i64 = 0;
892
893/// Why a writer refused a value (core §7.6, the vectors' tokens).
894#[derive(Debug, Clone, Copy, PartialEq, Eq)]
895pub enum WriteRefusal {
896    /// A field that is not optional is not given.
897    Missing,
898    /// A member the type does not have.
899    Unknown,
900    /// A value of the wrong JSON type, a name not declared, or a decimal
901    /// that does not read.
902    Value,
903    /// A value that has no code.
904    Range,
905}
906
907impl WriteRefusal {
908    #[must_use]
909    pub fn token(self) -> &'static str {
910        match self {
911            Self::Missing => "missing",
912            Self::Unknown => "unknown",
913            Self::Value => "value",
914            Self::Range => "range",
915        }
916    }
917
918    /// The refusal in words, its token first.
919    #[must_use]
920    pub fn reason(self) -> &'static str {
921        match self {
922            Self::Missing => "missing: a field that is not optional is not given",
923            Self::Unknown => "unknown: a member the type does not have",
924            Self::Value => "value: the wrong JSON type, a name not declared, or no decimal",
925            Self::Range => "range: a value that has no code",
926        }
927    }
928}
929
930impl std::fmt::Display for WriteRefusal {
931    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
932        f.write_str(self.reason())
933    }
934}
935
936impl std::error::Error for WriteRefusal {}
937
938/// Why a reader refused a record (core §7.6's order).
939#[derive(Debug, Clone, Copy, PartialEq, Eq)]
940pub enum ReadRefusal {
941    /// CH's tag is not the type's.
942    Tag,
943    /// The record ends before a bit its layout needs, or holds a byte after
944    /// its pad.
945    Length,
946    /// A field's code is unused.
947    Code,
948    /// A marker read as 1 is followed by no present field.
949    Extension,
950    /// A bit of the pad is 1.
951    Pad,
952    /// A time field whose instant, under the deployment epoch given, lies
953    /// past an `i64` of milliseconds: the reader's input, not the record's
954    /// fault, and no epoch within ±9.2 × 10^15 seconds does it. The
955    /// vectors have no such token; a deployment that states no epoch reads
956    /// under [`DEFAULT_EPOCH`].
957    Epoch,
958}
959
960impl ReadRefusal {
961    #[must_use]
962    pub fn token(self) -> &'static str {
963        match self {
964            Self::Tag => "tag",
965            Self::Length => "length",
966            Self::Code => "code",
967            Self::Extension => "extension",
968            Self::Pad => "pad",
969            Self::Epoch => "epoch",
970        }
971    }
972
973    /// The refusal in words, its token first.
974    #[must_use]
975    pub fn reason(self) -> &'static str {
976        match self {
977            Self::Tag => "tag: the envelope's tag is not the type's",
978            Self::Length => "length: the record is not as long as the layout reads it",
979            Self::Code => "code: a field's code is unused",
980            Self::Extension => "extension: a marker read as 1, and no field present after it",
981            Self::Pad => "pad: a bit of the pad is 1",
982            Self::Epoch => "epoch: the deployment epoch puts the instant past 64-bit milliseconds",
983        }
984    }
985}
986
987impl std::fmt::Display for ReadRefusal {
988    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
989        f.write_str(self.reason())
990    }
991}
992
993impl std::error::Error for ReadRefusal {}
994
995/// A record as a writer wrote it: its bytes, and how many of their bits
996/// are the record's (the rest is the pad).
997#[derive(Debug, Clone, PartialEq, Eq)]
998pub struct Record {
999    pub bytes: Vec<u8>,
1000    pub bits: u64,
1001}
1002
1003impl Record {
1004    /// The pad's zero bits, fewer than 8.
1005    #[must_use]
1006    pub fn pad(&self) -> u64 {
1007        self.bytes.len() as u64 * 8 - self.bits
1008    }
1009
1010    /// The record's bits before the pad, as `0` and `1`.
1011    #[must_use]
1012    pub fn bit_string(&self) -> String {
1013        (0..self.bits)
1014            .map(|i| {
1015                let b = (self.bytes[(i / 8) as usize] >> (7 - i % 8)) & 1;
1016                if b == 1 { '1' } else { '0' }
1017            })
1018            .collect()
1019    }
1020}
1021
1022/// A record being written, most significant bit first, with no padding
1023/// between fields (core §7.6's layout). [`BitWriter::finish`] adds the pad.
1024#[derive(Debug, Clone, Default)]
1025pub struct BitWriter {
1026    bytes: Vec<u8>,
1027    len: u64,
1028}
1029
1030impl BitWriter {
1031    #[must_use]
1032    pub fn new() -> Self {
1033        Self::default()
1034    }
1035
1036    /// Writes the low `width` bits of `v`, the most significant first: a
1037    /// code in its width (so a counter's count modulo 2^`width`).
1038    pub fn push(&mut self, v: u64, width: u32) {
1039        for i in (0..width).rev() {
1040            if self.len.is_multiple_of(8) {
1041                self.bytes.push(0);
1042            }
1043            if (v >> i) & 1 == 1 {
1044                let last = self.bytes.len() - 1;
1045                self.bytes[last] |= 0x80 >> (self.len % 8);
1046            }
1047            self.len += 1;
1048        }
1049    }
1050
1051    /// Writes one bit: a presence bit, or an extension marker.
1052    pub fn bit(&mut self, set: bool) {
1053        self.push(u64::from(set), 1);
1054    }
1055
1056    /// The record: its bits, then the zero pad up to a whole byte.
1057    #[must_use]
1058    pub fn finish(self) -> Record {
1059        Record {
1060            bytes: self.bytes,
1061            bits: self.len,
1062        }
1063    }
1064}
1065
1066/// A record being read under its layout, with core §7.6's length and pad
1067/// checks.
1068#[derive(Debug, Clone)]
1069pub struct BitReader<'a> {
1070    bytes: &'a [u8],
1071    pos: u64,
1072}
1073
1074impl<'a> BitReader<'a> {
1075    #[must_use]
1076    pub fn new(bytes: &'a [u8]) -> Self {
1077        Self { bytes, pos: 0 }
1078    }
1079
1080    fn total(&self) -> u64 {
1081        self.bytes.len() as u64 * 8
1082    }
1083
1084    /// The next `width` bits, as an unsigned integer: `length` when the
1085    /// record ends before them.
1086    ///
1087    /// # Errors
1088    /// [`ReadRefusal::Length`].
1089    pub fn take(&mut self, width: u32) -> Result<u64, ReadRefusal> {
1090        if self.pos + u64::from(width) > self.total() {
1091            return Err(ReadRefusal::Length);
1092        }
1093        let mut v = 0u64;
1094        for _ in 0..width {
1095            let b = (self.bytes[(self.pos / 8) as usize] >> (7 - self.pos % 8)) & 1;
1096            v = (v << 1) | u64::from(b);
1097            self.pos += 1;
1098        }
1099        Ok(v)
1100    }
1101
1102    /// The next bit: a presence bit, or an extension marker.
1103    ///
1104    /// # Errors
1105    /// [`ReadRefusal::Length`].
1106    pub fn bit(&mut self) -> Result<bool, ReadRefusal> {
1107        self.take(1).map(|b| b == 1)
1108    }
1109
1110    /// After a marker read as 1 that ends the reader's layout: the rest is
1111    /// a later revision's, and holds at least one bit.
1112    ///
1113    /// # Errors
1114    /// [`ReadRefusal::Length`].
1115    pub fn later(&self) -> Result<(), ReadRefusal> {
1116        if self.total() <= self.pos {
1117            Err(ReadRefusal::Length)
1118        } else {
1119            Ok(())
1120        }
1121    }
1122
1123    /// The record's end: no byte after its pad (`length`), then every pad
1124    /// bit 0 (`pad`).
1125    ///
1126    /// # Errors
1127    /// [`ReadRefusal::Length`], then [`ReadRefusal::Pad`].
1128    pub fn end(mut self) -> Result<(), ReadRefusal> {
1129        if self.bytes.len() as u64 != self.pos.div_ceil(8) {
1130            return Err(ReadRefusal::Length);
1131        }
1132        while self.pos < self.total() {
1133            if self.take(1)? == 1 {
1134                return Err(ReadRefusal::Pad);
1135            }
1136        }
1137        Ok(())
1138    }
1139}
1140
1141/// A JSON number or a decimal string, as a writer's decimal (`value` when
1142/// it does not read). Core §7.6: integer text from −2^63 to 2^64 − 1 is
1143/// that integer, exactly, and any other number the binary64 a JSON reader
1144/// holds for it, by its shortest decimal text. That is serde_json's
1145/// reading, which holds such integer text as an `i64` or a `u64` and any
1146/// other number as an `f64`.
1147///
1148/// # Errors
1149/// [`WriteRefusal::Value`].
1150pub fn json_decimal(v: &Value) -> Result<Decimal, WriteRefusal> {
1151    match v {
1152        Value::String(s) => Decimal::parse_input(s).ok_or(WriteRefusal::Value),
1153        // serde_json writes a float in its shortest round-trip text (ryu),
1154        // and an integer as its digits.
1155        Value::Number(n) => Decimal::parse_input(&n.to_string()).ok_or(WriteRefusal::Value),
1156        _ => Err(WriteRefusal::Value),
1157    }
1158}
1159
1160/// A JSON integer, an `int`'s, a `counter`'s or a `time`'s (core §7.6):
1161/// integer text from −2^63 to 2^64 − 1, read exactly, so a 64-bit counter
1162/// takes 2^64 − 1. Any other number is a binary64: `value`, a number of
1163/// the wrong type, below 2^63 in magnitude, and `range` from 2^63 on,
1164/// since a JSON reader without big integers holds integer text past 64
1165/// bits so.
1166///
1167/// # Errors
1168/// [`WriteRefusal::Value`] or [`WriteRefusal::Range`].
1169pub fn json_integer(v: &Value) -> Result<i128, WriteRefusal> {
1170    match v {
1171        Value::Number(n) => {
1172            if let Some(i) = n.as_i64() {
1173                Ok(i128::from(i))
1174            } else if let Some(u) = n.as_u64() {
1175                Ok(i128::from(u))
1176            } else {
1177                // Every float this large is an integer.
1178                if n.as_f64().unwrap_or(0.0).abs() >= 2f64.powi(63) {
1179                    Err(WriteRefusal::Range)
1180                } else {
1181                    Err(WriteRefusal::Value)
1182                }
1183            }
1184        }
1185        _ => Err(WriteRefusal::Value),
1186    }
1187}
1188
1189/// An `int` field's code for `x`: `x − minimum` (`range` outside
1190/// `minimum` to `maximum`).
1191///
1192/// # Errors
1193/// [`WriteRefusal::Range`].
1194pub fn int_code(x: i128, minimum: i64, maximum: i64) -> Result<u64, WriteRefusal> {
1195    if x < i128::from(minimum) || x > i128::from(maximum) {
1196        return Err(WriteRefusal::Range);
1197    }
1198    u64::try_from(x - i128::from(minimum)).map_err(|_| WriteRefusal::Range)
1199}
1200
1201/// An `int` field's value for a code that is no reserved one: `minimum +
1202/// code` (`code` past `maximum`).
1203///
1204/// # Errors
1205/// [`ReadRefusal::Code`].
1206pub fn int_value(code: u64, minimum: i64, maximum: i64) -> Result<i128, ReadRefusal> {
1207    let span = i128::from(maximum) - i128::from(minimum);
1208    if i128::from(code) > span {
1209        return Err(ReadRefusal::Code);
1210    }
1211    Ok(i128::from(minimum) + i128::from(code))
1212}
1213
1214/// A `fixed` field's code for `x`: round((x − `minimum`) / `resolution`),
1215/// a tie to the even code, in exact decimal arithmetic (`range` when it is
1216/// not one of the field's `values` codes).
1217///
1218/// # Errors
1219/// [`WriteRefusal::Range`].
1220pub fn fixed_code(
1221    x: &Decimal,
1222    minimum: &Decimal,
1223    resolution: &Decimal,
1224    values: u128,
1225) -> Result<u64, WriteRefusal> {
1226    match x.sub(minimum).div_round_even(resolution).to_u128() {
1227        Some(c) if c < values => u64::try_from(c).map_err(|_| WriteRefusal::Range),
1228        _ => Err(WriteRefusal::Range),
1229    }
1230}
1231
1232/// A `fixed` field's value for a code that is no reserved one: `minimum +
1233/// code × resolution` (`code` from `values` up).
1234///
1235/// # Errors
1236/// [`ReadRefusal::Code`].
1237pub fn fixed_value(
1238    code: u64,
1239    minimum: &Decimal,
1240    resolution: &Decimal,
1241    values: u128,
1242) -> Result<Decimal, ReadRefusal> {
1243    if u128::from(code) >= values {
1244        return Err(ReadRefusal::Code);
1245    }
1246    Ok(minimum.add(&resolution.mul_int(&BigInt::from(code))))
1247}
1248
1249/// A `fixed` field's declaration, read once: what generated code keeps in
1250/// a static, so its decimals are parsed once.
1251#[derive(Debug, Clone, PartialEq, Eq)]
1252pub struct Fixed {
1253    pub minimum: Decimal,
1254    pub resolution: Decimal,
1255    /// `(maximum − minimum) / resolution + 1`.
1256    pub values: u128,
1257}
1258
1259impl Fixed {
1260    /// # Panics
1261    /// When `minimum` or `resolution` is not a decimal string: a
1262    /// declaration the lints passed never is.
1263    #[must_use]
1264    pub fn new(minimum: &str, resolution: &str, values: u128) -> Self {
1265        Self {
1266            minimum: Decimal::parse(minimum).expect("a linted decimal"),
1267            resolution: Decimal::parse(resolution).expect("a linted decimal"),
1268            values,
1269        }
1270    }
1271
1272    /// [`fixed_code`].
1273    ///
1274    /// # Errors
1275    /// [`WriteRefusal::Range`].
1276    pub fn code(&self, x: &Decimal) -> Result<u64, WriteRefusal> {
1277        fixed_code(x, &self.minimum, &self.resolution, self.values)
1278    }
1279
1280    /// [`fixed_value`].
1281    ///
1282    /// # Errors
1283    /// [`ReadRefusal::Code`].
1284    pub fn value(&self, code: u64) -> Result<Decimal, ReadRefusal> {
1285        fixed_value(code, &self.minimum, &self.resolution, self.values)
1286    }
1287}
1288
1289/// A `time` field's code for an instant `t`, in milliseconds since the
1290/// Unix epoch, under the deployment epoch in seconds (`None`: the
1291/// deployment states none, [`DEFAULT_EPOCH`]): its seconds since the
1292/// epoch, then with `ms` its milliseconds in 10 bits (`range` outside the
1293/// epoch's 2^32 seconds).
1294///
1295/// # Errors
1296/// [`WriteRefusal::Range`].
1297pub fn time_code(t: i128, epoch: Option<i64>, ms: bool) -> Result<u64, WriteRefusal> {
1298    let e = epoch.unwrap_or(DEFAULT_EPOCH);
1299    let delta = t - 1000 * i128::from(e);
1300    let (s, m) = (delta.div_euclid(1000), delta.rem_euclid(1000));
1301    let s = u32::try_from(s).map_err(|_| WriteRefusal::Range)?;
1302    let m = u64::try_from(m).unwrap_or(0);
1303    Ok(if ms {
1304        (u64::from(s) << 10) | m
1305    } else {
1306        u64::from(s)
1307    })
1308}
1309
1310/// A `time` field's instant for a code, in milliseconds since the Unix
1311/// epoch, under the deployment epoch in seconds (`None`: the deployment
1312/// states none, [`DEFAULT_EPOCH`]); `code` for a millisecond code from
1313/// 1000 up.
1314///
1315/// # Errors
1316/// [`ReadRefusal::Code`].
1317pub fn time_value(code: u64, epoch: Option<i64>, ms: bool) -> Result<i128, ReadRefusal> {
1318    let (s, m) = if ms {
1319        (code >> 10, code & 0x3ff)
1320    } else {
1321        (code, 0)
1322    };
1323    if m >= 1000 {
1324        return Err(ReadRefusal::Code);
1325    }
1326    let e = epoch.unwrap_or(DEFAULT_EPOCH);
1327    Ok(1000 * i128::from(e) + 1000 * i128::from(s) + i128::from(m))
1328}
1329
1330impl Layout {
1331    fn new(items: Vec<Item>) -> Self {
1332        let mut form = Vec::new();
1333        for it in &items {
1334            match it {
1335                Item::Marker => {
1336                    form.push(Value::from(MARKER));
1337                    break;
1338                }
1339                Item::Field(f) => form.push(f.form()),
1340            }
1341        }
1342        let form = Value::Array(form);
1343        let sha256 = Sha256::digest(crate::schema::jcs(&form)).into();
1344        Self {
1345            items,
1346            form,
1347            sha256,
1348        }
1349    }
1350
1351    /// The layout form: the root's wire, without names (core §7.6).
1352    #[must_use]
1353    pub fn form(&self) -> &Value {
1354        &self.form
1355    }
1356
1357    /// The sha256 of the layout form's JCS bytes, in lowercase hex.
1358    #[must_use]
1359    pub fn sha256_hex(&self) -> String {
1360        let mut s = String::with_capacity(64);
1361        for b in self.sha256 {
1362            let _ = write!(s, "{b:02x}");
1363        }
1364        s
1365    }
1366
1367    /// The tag CH carries: the low four bits of the hash's last byte.
1368    #[must_use]
1369    pub fn tag(&self) -> u8 {
1370        self.sha256[31] & 0x0f
1371    }
1372
1373    /// Each item's width and start.
1374    #[must_use]
1375    pub fn slots(&self) -> Vec<Slot> {
1376        let (mut pos, mut fixed) = (0u64, true);
1377        let mut out = Vec::new();
1378        for it in &self.items {
1379            let offset = fixed.then_some(pos);
1380            match it {
1381                Item::Marker => {
1382                    out.push(Slot {
1383                        name: None,
1384                        width: 1,
1385                        optional: false,
1386                        offset,
1387                    });
1388                    fixed = false;
1389                }
1390                Item::Field(f) => {
1391                    out.push(Slot {
1392                        name: Some(f.name.clone()),
1393                        width: f.width,
1394                        optional: f.optional,
1395                        offset,
1396                    });
1397                    if f.optional {
1398                        fixed = false;
1399                    } else {
1400                        pos += u64::from(f.width);
1401                    }
1402                }
1403            }
1404        }
1405        out
1406    }
1407
1408    /// The shortest record this revision writes, before the pad: every
1409    /// optional field absent and the first marker 0.
1410    #[must_use]
1411    pub fn min_bits(&self) -> u64 {
1412        let mut n = 0;
1413        for it in &self.items {
1414            match it {
1415                Item::Marker => return n + 1,
1416                Item::Field(f) if f.optional => n += 1,
1417                Item::Field(f) => n += u64::from(f.width),
1418            }
1419        }
1420        n
1421    }
1422
1423    /// The longest: every field present, every marker before one 1, and
1424    /// the last marker 0.
1425    #[must_use]
1426    pub fn max_bits(&self) -> u64 {
1427        self.items
1428            .iter()
1429            .map(|it| match it {
1430                Item::Marker => 1,
1431                Item::Field(f) => u64::from(f.width) + u64::from(f.optional),
1432            })
1433            .sum()
1434    }
1435
1436    /// Its fields, the extension markers left out.
1437    pub fn fields(&self) -> impl Iterator<Item = &Field> {
1438        self.items.iter().filter_map(|it| match it {
1439            Item::Field(f) => Some(f),
1440            Item::Marker => None,
1441        })
1442    }
1443
1444    /// Writes a value, the JSON object core §7.6's reading spells, under
1445    /// the deployment epoch in seconds its `time` fields are written since
1446    /// (`None`: the deployment states none, [`DEFAULT_EPOCH`]).
1447    ///
1448    /// # Errors
1449    /// The writer's refusal: [`WriteRefusal`].
1450    pub fn write(&self, value: &Value, epoch: Option<i64>) -> Result<Record, WriteRefusal> {
1451        let Value::Object(obj) = value else {
1452            return Err(WriteRefusal::Value);
1453        };
1454        if obj
1455            .keys()
1456            .any(|k| !self.fields().any(|f| f.name == k.as_str()))
1457        {
1458            return Err(WriteRefusal::Unknown);
1459        }
1460        let mut bits = BitWriter::new();
1461        for (i, it) in self.items.iter().enumerate() {
1462            match it {
1463                Item::Marker => {
1464                    let later = self.items[i + 1..].iter().any(|x| match x {
1465                        Item::Field(f) => obj.contains_key(&f.name),
1466                        Item::Marker => false,
1467                    });
1468                    bits.bit(later);
1469                    if !later {
1470                        break;
1471                    }
1472                }
1473                Item::Field(f) => match obj.get(&f.name) {
1474                    None if f.optional => bits.bit(false),
1475                    None => return Err(WriteRefusal::Missing),
1476                    Some(v) => {
1477                        let code = f.code(v, epoch)?;
1478                        if f.optional {
1479                            bits.bit(true);
1480                        }
1481                        bits.push(code, f.width);
1482                    }
1483                },
1484            }
1485        }
1486        Ok(bits.finish())
1487    }
1488
1489    /// Reads a record under the tag its envelope's CH carries, refusing it
1490    /// for the first of core §7.6's checks that applies, its `time` fields
1491    /// under the deployment epoch (`None`: [`DEFAULT_EPOCH`]).
1492    ///
1493    /// # Errors
1494    /// The reader's refusal: [`ReadRefusal`].
1495    pub fn read(&self, tag: u8, bytes: &[u8], epoch: Option<i64>) -> Result<Value, ReadRefusal> {
1496        let mut out = Map::new();
1497        self.walk(tag, bytes, |f, code| {
1498            out.insert(f.name.clone(), f.value(code, epoch)?);
1499            Ok(())
1500        })?;
1501        Ok(Value::Object(out))
1502    }
1503
1504    /// [`Layout::read`]'s checks, with no value made and no epoch needed: a
1505    /// writer's or a reader's admission of a record (#979 B2's runtime).
1506    ///
1507    /// # Errors
1508    /// The reader's refusal, never [`ReadRefusal::Epoch`].
1509    pub fn check(&self, tag: u8, bytes: &[u8]) -> Result<(), ReadRefusal> {
1510        self.walk(tag, bytes, |f, code| f.check_code(code))
1511    }
1512
1513    /// Core §7.6's reading, in its order, each present field's code handed
1514    /// to `each` where it is read.
1515    fn walk(
1516        &self,
1517        tag: u8,
1518        bytes: &[u8],
1519        mut each: impl FnMut(&Field, u64) -> Result<(), ReadRefusal>,
1520    ) -> Result<(), ReadRefusal> {
1521        if tag != self.tag() {
1522            return Err(ReadRefusal::Tag);
1523        }
1524        let mut r = BitReader::new(bytes);
1525        let mut set_marker = false;
1526        let mut present_after = false;
1527        let last = self.items.len().saturating_sub(1);
1528        for (i, it) in self.items.iter().enumerate() {
1529            match it {
1530                Item::Marker => {
1531                    if !r.bit()? {
1532                        break;
1533                    }
1534                    if i == last {
1535                        // A later revision's bits: at least one of them.
1536                        return r.later();
1537                    }
1538                    set_marker = true;
1539                    present_after = false;
1540                }
1541                Item::Field(f) => {
1542                    if f.optional && !r.bit()? {
1543                        continue;
1544                    }
1545                    let code = r.take(f.width)?;
1546                    each(f, code)?;
1547                    present_after = true;
1548                }
1549            }
1550        }
1551        if set_marker && !present_after {
1552            return Err(ReadRefusal::Extension);
1553        }
1554        r.end()
1555    }
1556}
1557
1558impl Field {
1559    /// The code a writer gives `v`, the field's JSON value as §7.6's
1560    /// reading spells it, with the deployment epoch a `time` field needs: a
1561    /// frame's fields are written one by one (core §7.7).
1562    ///
1563    /// # Errors
1564    /// The writer's refusal: [`WriteRefusal`].
1565    pub fn code(&self, v: &Value, epoch: Option<i64>) -> Result<u64, WriteRefusal> {
1566        let reserved = |list: &[&'static str], s: &str| {
1567            reserved_code(self.width, list, s).ok_or(WriteRefusal::Value)
1568        };
1569        match &self.kind {
1570            FieldKind::Int {
1571                minimum,
1572                maximum,
1573                reserved: res,
1574            } => {
1575                if let Value::String(s) = v
1576                    && RESERVED.contains(&s.as_str())
1577                {
1578                    return reserved(res, s);
1579                }
1580                int_code(json_integer(v)?, *minimum, *maximum)
1581            }
1582            FieldKind::Fixed {
1583                minimum,
1584                resolution,
1585                reserved: res,
1586                values,
1587                ..
1588            } => {
1589                if let Value::String(s) = v
1590                    && RESERVED.contains(&s.as_str())
1591                {
1592                    return reserved(res, s);
1593                }
1594                fixed_code(&json_decimal(v)?, minimum, resolution, *values)
1595            }
1596            FieldKind::Enum { values, escape } => match v {
1597                Value::Null if *escape => Ok(self.top()),
1598                Value::String(s) => values
1599                    .iter()
1600                    .position(|x| x == s)
1601                    .map(|i| i as u64)
1602                    .ok_or(WriteRefusal::Value),
1603                _ => Err(WriteRefusal::Value),
1604            },
1605            FieldKind::Bool => v.as_bool().map(u64::from).ok_or(WriteRefusal::Value),
1606            FieldKind::Counter => {
1607                let c = json_integer(v)?;
1608                u64::try_from(c).map_err(|_| WriteRefusal::Range)
1609            }
1610            FieldKind::Time { ms } => time_code(json_integer(v)?, epoch, *ms),
1611        }
1612    }
1613
1614    /// The reserved code's name, when `code` is one this field declares:
1615    /// a code that is no value (core §7.6), as a frame's deadband reads it
1616    /// (§7.7).
1617    #[must_use]
1618    pub fn reserved_name(&self, code: u64) -> Option<&'static str> {
1619        let list = match &self.kind {
1620            FieldKind::Int { reserved, .. } | FieldKind::Fixed { reserved, .. } => reserved,
1621            _ => return None,
1622        };
1623        list.iter()
1624            .enumerate()
1625            .find(|(i, _)| code == self.reserved_code(*i))
1626            .map(|(_, r)| *r)
1627    }
1628
1629    /// The JSON value a reader reads from `code`, as §7.6's reading spells
1630    /// it.
1631    ///
1632    /// # Errors
1633    /// [`ReadRefusal::Code`] for an unused code, [`ReadRefusal::Epoch`] for
1634    /// a `time` field and no epoch.
1635    pub fn value(&self, code: u64, epoch: Option<i64>) -> Result<Value, ReadRefusal> {
1636        if let Some(r) = self.reserved_name(code) {
1637            return Ok(Value::from(r));
1638        }
1639        match &self.kind {
1640            FieldKind::Int {
1641                minimum, maximum, ..
1642            } => {
1643                let v = int_value(code, *minimum, *maximum)?;
1644                Ok(i64::try_from(v).map_or(Value::Null, Value::from))
1645            }
1646            FieldKind::Fixed {
1647                minimum,
1648                resolution,
1649                values,
1650                ..
1651            } => fixed_value(code, minimum, resolution, *values)
1652                .map(|x| Value::String(x.to_string())),
1653            FieldKind::Enum { values, escape } => match usize::try_from(code) {
1654                Ok(i) if i < values.len() => Ok(Value::String(values[i].clone())),
1655                _ if *escape => Ok(Value::Null),
1656                _ => Err(ReadRefusal::Code),
1657            },
1658            FieldKind::Bool => Ok(Value::Bool(code == 1)),
1659            FieldKind::Counter => Ok(Value::from(code)),
1660            FieldKind::Time { ms } => {
1661                let t = time_value(code, epoch, *ms)?;
1662                i64::try_from(t)
1663                    .map(Value::from)
1664                    .map_err(|_| ReadRefusal::Epoch)
1665            }
1666        }
1667    }
1668
1669    /// Whether `code` is one this field reads: [`Field::value`]'s `code`
1670    /// check alone.
1671    ///
1672    /// # Errors
1673    /// [`ReadRefusal::Code`].
1674    pub fn check_code(&self, code: u64) -> Result<(), ReadRefusal> {
1675        if self.reserved_name(code).is_some() {
1676            return Ok(());
1677        }
1678        let used = match &self.kind {
1679            FieldKind::Int {
1680                minimum, maximum, ..
1681            } => int_value(code, *minimum, *maximum).is_ok(),
1682            FieldKind::Fixed { values, .. } => u128::from(code) < *values,
1683            FieldKind::Enum { values, escape } => *escape || code < values.len() as u64,
1684            FieldKind::Bool | FieldKind::Counter => true,
1685            FieldKind::Time { ms } => !*ms || code & 0x3ff < 1000,
1686        };
1687        if used { Ok(()) } else { Err(ReadRefusal::Code) }
1688    }
1689}
1690
1691/// One type's layout in a packed document (an artifact's data): `Err`
1692/// names why there is none, a type the document does not define or one
1693/// whose declaration has a finding.
1694///
1695/// # Errors
1696/// The reason, in words.
1697pub fn layout_in(doc: &Value, name: &str) -> Result<Layout, String> {
1698    let read = PackedDoc::read(doc);
1699    match read.types.get(name) {
1700        Some(Some(layout)) => Ok(layout.clone()),
1701        Some(None) => Err(format!(
1702            "packed:{name}'s declaration does not read ({})",
1703            read.findings
1704                .iter()
1705                .map(|f| f.code)
1706                .collect::<Vec<_>>()
1707                .join(", ")
1708        )),
1709        None => Err(format!("the packed document defines no types/{name}")),
1710    }
1711}
1712
1713#[cfg(test)]
1714mod tests {
1715    use serde_json::json;
1716
1717    use super::*;
1718
1719    fn codes(doc: &Value) -> Vec<&'static str> {
1720        let mut c: Vec<_> = PackedDoc::read(doc)
1721            .findings
1722            .iter()
1723            .map(|f| f.code)
1724            .collect();
1725        c.sort_unstable();
1726        c
1727    }
1728
1729    #[test]
1730    fn decimals_read_exactly_and_write_shortest() {
1731        for (s, want) in [
1732            ("0", "0"),
1733            ("-0", "0"),
1734            ("2.00", "2"),
1735            ("-40", "-40"),
1736            ("0.10", "0.1"),
1737            ("1013.2", "1013.2"),
1738        ] {
1739            assert_eq!(Decimal::parse(s).unwrap().to_string(), want, "{s}");
1740        }
1741        for bad in ["", "01", "1.", ".5", "+1", "1e3", "1,5", "--1"] {
1742            assert!(Decimal::parse(bad).is_none(), "{bad}");
1743        }
1744        assert_eq!(Decimal::parse_input("5e-1").unwrap().to_string(), "0.5");
1745        assert_eq!(Decimal::parse_input("1.5E+2").unwrap().to_string(), "150");
1746        assert_eq!(
1747            Decimal::parse_input("1e21").unwrap().to_string(),
1748            "1000000000000000000000"
1749        );
1750        assert!(Decimal::parse_input("1e999999").is_none());
1751    }
1752
1753    #[test]
1754    fn ties_go_to_the_even_code() {
1755        let half = Decimal::parse("0.5").unwrap();
1756        let r = |s: &str| {
1757            Decimal::parse_input(s)
1758                .unwrap()
1759                .div_round_even(&half)
1760                .to_string()
1761        };
1762        assert_eq!(r("0.25"), "0");
1763        assert_eq!(r("0.75"), "2");
1764        assert_eq!(r("-0.25"), "0");
1765        assert_eq!(r("-0.75"), "-2");
1766        assert_eq!(r("0.2500000000000000000000000001"), "1");
1767    }
1768
1769    #[test]
1770    fn the_report_sensor_record_is_40_bits() {
1771        let doc = json!({"types": {"Sensor": {"fields": [
1772            {"name": "temperature", "type": "fixed", "minimum": "-40", "maximum": "85", "resolution": "0.1"},
1773            {"name": "humidity", "type": "fixed", "minimum": "0", "maximum": "100", "resolution": "0.5"},
1774            {"name": "pressure", "type": "fixed", "minimum": "300", "maximum": "1100", "resolution": "0.1"},
1775            {"name": "battery", "type": "fixed", "minimum": "2.00", "maximum": "4.20", "resolution": "0.01"}
1776        ]}}});
1777        let p = PackedDoc::read(&doc);
1778        assert!(p.findings.is_empty(), "{:?}", p.findings);
1779        let l = p.types["Sensor"].clone().unwrap();
1780        assert_eq!((l.min_bits(), l.max_bits()), (40, 40));
1781        let rec = l
1782            .write(
1783                &json!({"temperature": "21.5", "humidity": "43.5", "pressure": "1013.2", "battery": "3.70"}),
1784                None,
1785            )
1786            .unwrap();
1787        assert_eq!(rec.bytes, [0x4c, 0xea, 0xfb, 0xdc, 0xaa]);
1788        assert_eq!(rec.pad(), 0);
1789        let back = l.read(l.tag(), &rec.bytes, None).unwrap();
1790        assert_eq!(back["battery"], "3.7");
1791        assert_eq!(l.read(l.tag() ^ 1, &rec.bytes, None), Err(ReadRefusal::Tag));
1792        assert_eq!(
1793            l.read(l.tag(), &rec.bytes[..4], None),
1794            Err(ReadRefusal::Length)
1795        );
1796    }
1797
1798    #[test]
1799    fn lints_follow_cascade_seven() {
1800        assert_eq!(codes(&json!([])), ["E038"]);
1801        assert_eq!(codes(&json!({"types": {}, "x": 1})), ["E038"]);
1802        assert_eq!(codes(&json!({"types": {"bad": {"fields": []}}})), ["E038"]);
1803        assert_eq!(codes(&json!({"types": {"A": {"fields": []}}})), ["E039"]);
1804        assert_eq!(
1805            codes(&json!({"types": {"A": {"fields": [{"name": "a", "type": "float"}]}}})),
1806            ["E043"]
1807        );
1808        assert_eq!(
1809            codes(
1810                &json!({"types": {"A": {"fields": [{"name": "a", "type": "int", "minimum": 1}]}}})
1811            ),
1812            ["E038"]
1813        );
1814        assert_eq!(
1815            codes(&json!({"types": {"A": {"fields": [
1816                {"name": "a", "type": "int", "minimum": 2, "maximum": 1},
1817                {"name": "b", "type": "fixed", "minimum": "0", "maximum": "1", "resolution": "0.3"},
1818                {"name": "c", "type": "fixed", "minimum": "x", "maximum": "-1", "resolution": "0"},
1819                {"name": "d", "type": "counter", "width": 65},
1820                {"name": "e", "type": "int", "minimum": 0, "maximum": 0},
1821                {"name": "a", "type": "bool"},
1822                {"name": "f", "type": "enum", "values": ["x", "x"]},
1823                "...", "...",
1824                {"name": "g", "type": "bool"}
1825            ]}}})),
1826            [
1827                "E039", "E040", "E040", "E041", "E041", "E042", "E042", "E045", "E045"
1828            ]
1829        );
1830    }
1831
1832    #[test]
1833    fn appending_behind_a_marker_keeps_the_tag() {
1834        let v1 = json!({"types": {"L": {"fields": [{"name": "up", "type": "bool"}, "..."]}}});
1835        let v2 = json!({"types": {"L": {"fields": [
1836            {"name": "up", "type": "bool"}, "...",
1837            {"name": "q", "type": "int", "minimum": 0, "maximum": 100, "optional": true}, "..."
1838        ]}}});
1839        let a = PackedDoc::read(&v1).types["L"].clone().unwrap();
1840        let b = PackedDoc::read(&v2).types["L"].clone().unwrap();
1841        assert_eq!(a.tag(), b.tag());
1842        let new = b.write(&json!({"up": true, "q": 87}), None).unwrap();
1843        assert_eq!(
1844            a.read(a.tag(), &new.bytes, None).unwrap(),
1845            json!({"up": true})
1846        );
1847        let old = a.write(&json!({"up": false}), None).unwrap();
1848        assert_eq!(
1849            b.read(b.tag(), &old.bytes, None).unwrap(),
1850            json!({"up": false})
1851        );
1852    }
1853}