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