Skip to main content

zenkey_model/
frame.rs

1//! Frames (core §7.7, 0.83; #981's K1): a plain stream's records of one
2//! packed type (§7.6) under one envelope (§7.5) and one time.
3//!
4//! ```text
5//! frame, a put's payload   CH · run · seq · body
6//! body       time · count · record · … · record · pad
7//! time       42 bits: record 0's measured time; all ones when unknown
8//! count      the records in the frame, less 1, in ⌈log₂ records⌉ bits
9//! record     full · when · offset · fields
10//! full       1 bit: 1 for a full record, 0 for a delta record
11//! when       1 bit, in record 1 and later only: 1 when the record is scheduled
12//! offset     when `when` is 0: the record's time, in ms after record 0's, in ⌈log₂ span⌉ bits
13//! fields     a full record: every field, as §7.6 writes it
14//!            a delta record: one bit per field, then each field whose bit is 1
15//! pad        zero bits up to the next whole byte, fewer than 8
16//! ```
17//!
18//! - **The declaration** is a resource's `frame` table ([`FrameParams`],
19//!   from authoring's [`FrameSpec`], E048 its findings), over a packed
20//!   record type with no extension marker ([`Layout::of`]).
21//! - **The tag** is §7.6's rule over the frame form ([`Layout::form`]): the
22//!   table's `records`, `step_ms`, `jitter_ms` and deadbands, and the
23//!   record's layout form. `keyframe_every` changes no bit, and is left out.
24//! - **A body** is read with its layout ([`Frame::parse`], refusing for the
25//!   first of §7.7's checks, [`ReadRefusal`]) and written back to its bytes
26//!   ([`Frame::write`]). A record's fields are [`Slot`]s: omitted, included
27//!   absent, or a code, which [`Frame::read_json`] spells as §7.6's JSON
28//!   reading does.
29//!
30//! - **A key's frames** are read by a [`Reader`] (#981's K2): what each
31//!   frame follows in the run it holds ([`Follows`]), and each record's
32//!   seq, time ([`When`]) and field states ([`FieldState`]: `known`,
33//!   `within`, `unknown` with why, `absent`), as §7.7's "The reader's
34//!   fields" says; [`Applied::reading`] spells them as
35//!   `spec/conformance/frame/apply.json` does, which observer §7.6's tools
36//!   show.
37//!
38//! - **A key's writer** is a [`Framer`] (#981's K3): the records an owner
39//!   measured ([`Measured`]) gathered into frames ([`Batch`]), each written
40//!   under its run ([`Framer::encode`]) as §7.7's "The owner's frames"
41//!   says, full where the run is new or `keyframe_every` asks, each delta
42//!   field included where it changed or passed its deadband.
43
44use std::collections::BTreeMap;
45use std::fmt::Write as _;
46use std::time::Duration;
47
48use serde_json::{Map, Value, json};
49use sha2::{Digest, Sha256};
50
51use crate::authoring::{FrameSpec, Kind};
52use crate::contract::{Body, Contract, Resource};
53use crate::packed::{self, BitReader, BitWriter, Decimal, Field, FieldKind, Item};
54use crate::wire::{Envelope, Run, Seq, Stamp, Tag};
55
56/// The most records one frame holds.
57pub const MAX_RECORDS: u64 = 256;
58/// The greatest `step_ms`, 2^32 − 1.
59pub const MAX_STEP_MS: u64 = u32::MAX as u64;
60/// The greatest `keyframe_every`, and a deadband's greatest `max_records`.
61pub const MAX_EVERY: u64 = 65_536;
62/// The time code that says the owner's clock is unknown: all 42 bits set.
63pub const TIME_UNKNOWN: u64 = (1 << 42) - 1;
64
65/// A field's deadband (core §7.7): the field may be omitted while within
66/// `delta` of the value last included, and is included at least once
67/// every `max_records` records.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Deadband {
70    /// Above 0, in the field's units. Compared as a value, so `"4.0"` and
71    /// `"4"` are one delta.
72    pub delta: Decimal,
73    /// From 1 to 65,536.
74    pub max_records: u32,
75}
76
77/// A frame resource's `frame` table, resolved (core §7.7): every key has
78/// its value, a default's included.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct FrameParams {
81    /// From 1 to 256.
82    pub records: u16,
83    /// From 1 to 2^32 − 1, exactly when `records` is above 1.
84    pub step_ms: Option<u32>,
85    /// From 0 to `step_ms` / 2; set exactly when `step_ms` is.
86    pub jitter_ms: Option<u32>,
87    /// From 1 to 65,536.
88    pub keyframe_every: u32,
89    /// By field name.
90    pub deadband: BTreeMap<String, Deadband>,
91}
92
93impl FrameParams {
94    /// The table as written, resolved; or E048's findings, one sentence
95    /// each, for every key and deadband member outside §7.7's table.
96    ///
97    /// # Errors
98    /// Each value out of range, in words.
99    pub fn resolve(spec: &FrameSpec) -> Result<Self, Vec<String>> {
100        let mut why = Vec::new();
101        let records = spec.records.unwrap_or(1);
102        if !(1..=MAX_RECORDS).contains(&records) {
103            why.push(format!("`records` = {records} is not from 1 to 256"));
104        }
105        match spec.step_ms {
106            Some(s) if !(1..=MAX_STEP_MS).contains(&s) => {
107                why.push(format!("`step_ms` = {s} is not from 1 to 2^32 - 1"));
108            }
109            Some(_) if records == 1 => {
110                why.push("`step_ms` with `records` = 1: a one-record frame has no step".to_owned())
111            }
112            None if records > 1 => why.push(format!(
113                "`records` = {records} and no `step_ms`: a frame of several records has a step"
114            )),
115            _ => {}
116        }
117        match (spec.jitter_ms, spec.step_ms) {
118            (Some(_), None) => why.push("`jitter_ms` without `step_ms`".to_owned()),
119            (Some(j), Some(s)) if j.saturating_mul(2) > s => {
120                why.push(format!("`jitter_ms` = {j} is above `step_ms` / 2"));
121            }
122            _ => {}
123        }
124        let keyframe_every = spec.keyframe_every.unwrap_or(1);
125        if !(1..=MAX_EVERY).contains(&keyframe_every) {
126            why.push(format!(
127                "`keyframe_every` = {keyframe_every} is not from 1 to 65,536"
128            ));
129        }
130        let mut deadband = BTreeMap::new();
131        for (name, d) in &spec.deadband {
132            // Kept in its shortest form, so `"4.0"` and `"4"` are one value.
133            let delta = Decimal::parse(&d.delta)
134                .filter(|x| *x > Decimal::from(0))
135                .and_then(|x| Decimal::parse(&x.to_string()));
136            if delta.is_none() {
137                why.push(format!(
138                    "`deadband.{name}.delta` = {:?} is not a decimal string above 0",
139                    d.delta
140                ));
141            }
142            if !(1..=MAX_EVERY).contains(&d.max_records) {
143                why.push(format!(
144                    "`deadband.{name}.max_records` = {} is not from 1 to 65,536",
145                    d.max_records
146                ));
147            }
148            if let (Some(delta), Ok(max_records)) = (delta, u32::try_from(d.max_records)) {
149                deadband.insert(name.clone(), Deadband { delta, max_records });
150            }
151        }
152        if !why.is_empty() {
153            return Err(why);
154        }
155        let step_ms = spec.step_ms.map(|s| u32::try_from(s).expect("checked"));
156        Ok(Self {
157            records: u16::try_from(records).expect("checked"),
158            step_ms,
159            jitter_ms: step_ms.map(|_| {
160                u32::try_from(spec.jitter_ms.unwrap_or(0)).expect("checked below the step")
161            }),
162            keyframe_every: u32::try_from(keyframe_every).expect("checked"),
163            deadband,
164        })
165    }
166
167    /// The span, `records` × `step_ms`, where the frame has a step.
168    #[must_use]
169    pub fn span_ms(&self) -> Option<u64> {
170        self.step_ms.map(|s| u64::from(self.records) * u64::from(s))
171    }
172
173    /// The frame resource's interval (core §7.7): its span where it has a
174    /// step, else the `timing.period_ms` its annotations declare as
175    /// `timing.v1` §2.2 reads them, else unstated.
176    #[must_use]
177    pub fn interval_ms(&self, annotations: &BTreeMap<String, Value>) -> Option<u64> {
178        self.span_ms().or_else(
179            || match crate::timing::declaration(Kind::Stream, annotations) {
180                crate::timing::Declaration::Declared(d) => d.period.map(millis),
181                _ => None,
182            },
183        )
184    }
185
186    /// Its canonical form's member (core §9.5): `records`, `step_ms` and
187    /// `jitter_ms` (`null` without a step), `keyframe_every`, and
188    /// `deadband` by field name, each `delta` in its shortest form.
189    #[must_use]
190    pub fn canonical(&self) -> Value {
191        let deadband: Map<String, Value> = self
192            .deadband
193            .iter()
194            .map(|(k, d)| {
195                (
196                    k.clone(),
197                    json!({"delta": d.delta.to_string(), "max_records": d.max_records}),
198                )
199            })
200            .collect();
201        json!({
202            "records": self.records,
203            "step_ms": self.step_ms,
204            "jitter_ms": self.jitter_ms,
205            "keyframe_every": self.keyframe_every,
206            "deadband": deadband,
207        })
208    }
209
210    /// Its canonical form's member read back, as a bundle carries it.
211    ///
212    /// # Errors
213    /// What is wrong with it, in words.
214    pub fn from_canonical(v: &Value) -> Result<Self, String> {
215        let m = v.as_object().ok_or("`frame` is not an object")?;
216        let int = |k: &str| -> Result<Option<u64>, String> {
217            match m.get(k) {
218                None => Err(format!("`frame` has no `{k}`")),
219                Some(Value::Null) => Ok(None),
220                Some(x) => x
221                    .as_u64()
222                    .map(Some)
223                    .ok_or_else(|| format!("`frame.{k}` is not an unsigned integer")),
224            }
225        };
226        let mut deadband = BTreeMap::new();
227        let db = m
228            .get("deadband")
229            .and_then(Value::as_object)
230            .ok_or("`frame.deadband` is not an object")?;
231        for (name, d) in db {
232            let delta = d
233                .get("delta")
234                .and_then(Value::as_str)
235                .ok_or_else(|| format!("`frame.deadband.{name}` has no `delta` string"))?;
236            let max_records = d
237                .get("max_records")
238                .and_then(Value::as_u64)
239                .ok_or_else(|| format!("`frame.deadband.{name}` has no `max_records`"))?;
240            deadband.insert(
241                name.clone(),
242                crate::authoring::DeadbandSpec {
243                    delta: delta.to_owned(),
244                    max_records,
245                },
246            );
247        }
248        let step_ms = int("step_ms")?;
249        let jitter_ms = int("jitter_ms")?;
250        if step_ms.is_some() != jitter_ms.is_some() {
251            return Err("`frame.jitter_ms` is null exactly when `step_ms` is".to_owned());
252        }
253        let spec = FrameSpec {
254            records: Some(int("records")?.ok_or("`frame.records` is null")?),
255            step_ms,
256            jitter_ms,
257            keyframe_every: Some(int("keyframe_every")?.ok_or("`frame.keyframe_every` is null")?),
258            deadband,
259        };
260        Self::resolve(&spec).map_err(|why| why.join("; "))
261    }
262}
263
264fn millis(d: Duration) -> u64 {
265    u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
266}
267
268/// ⌈log₂ n⌉, the fewest bits that hold n codes: 0 for one.
269fn bits_for(n: u64) -> u32 {
270    if n <= 1 {
271        0
272    } else {
273        64 - (n - 1).leading_zeros()
274    }
275}
276
277/// A frame resource's layout (core §7.7): its record type's fields, its
278/// table, and the frame form its tag comes from.
279#[derive(Debug, Clone, PartialEq, Eq)]
280pub struct Layout {
281    pub params: FrameParams,
282    fields: Vec<Field>,
283    /// Each field's deadband, in field order.
284    deadband: Vec<Option<Deadband>>,
285    form: Value,
286    sha256: [u8; 32],
287}
288
289impl Layout {
290    /// The layout of a frame of `record`'s type under `params`.
291    ///
292    /// # Errors
293    /// Why there is none: the record type has an extension marker (E047),
294    /// or a deadband names no field of it, or one that is not an `int`,
295    /// `fixed` or `counter` (E049).
296    pub fn of(record: &packed::Layout, params: &FrameParams) -> Result<Self, String> {
297        let mut fields = Vec::new();
298        for it in &record.items {
299            match it {
300                Item::Marker => {
301                    return Err(
302                        "the record type has an extension marker, which a frame's type never has"
303                            .to_owned(),
304                    );
305                }
306                Item::Field(f) => fields.push(f.clone()),
307            }
308        }
309        for name in params.deadband.keys() {
310            match fields.iter().find(|f| &f.name == name) {
311                None => return Err(format!("the deadband names {name:?}, no field of the type")),
312                Some(f) if !takes_deadband(f) => {
313                    return Err(format!(
314                        "the deadband names {name:?}, a {} field, which takes none",
315                        f.kind.as_str()
316                    ));
317                }
318                Some(_) => {}
319            }
320        }
321        let deadband: Vec<Option<Deadband>> = fields
322            .iter()
323            .map(|f| params.deadband.get(&f.name).cloned())
324            .collect();
325        let items: Vec<Value> = deadband
326            .iter()
327            .map(|d| match d {
328                None => Value::Null,
329                Some(d) => json!({"delta": d.delta.to_string(), "max_records": d.max_records}),
330            })
331            .collect();
332        let form = json!({
333            "frame": {
334                "records": params.records,
335                "step_ms": params.step_ms,
336                "jitter_ms": params.jitter_ms,
337                "deadband": items,
338            },
339            "record": record.form().clone(),
340        });
341        let sha256 = Sha256::digest(crate::schema::jcs(&form)).into();
342        Ok(Self {
343            params: params.clone(),
344            fields,
345            deadband,
346            form,
347            sha256,
348        })
349    }
350
351    /// The layout of a contract's frame resource: `None` for a resource
352    /// that is no frame resource.
353    ///
354    /// # Errors
355    /// Why a frame resource has none: its type's layout (an artifact
356    /// missing, or a declaration with a finding), or [`Layout::of`]'s.
357    pub fn of_resource(c: &Contract, r: &Resource) -> Result<Option<Self>, String> {
358        let Body::Data(d) = &r.body else {
359            return Ok(None);
360        };
361        let Some(params) = &d.frame else {
362            return Ok(None);
363        };
364        let record = c
365            .packed_layout(&d.type_)?
366            .ok_or_else(|| format!("{}: a frame resource's type is not packed", r.template))?;
367        Self::of(&record, params).map(Some)
368    }
369
370    /// The frame form: the root of the tag (core §7.7).
371    #[must_use]
372    pub fn form(&self) -> &Value {
373        &self.form
374    }
375
376    /// The sha256 of the frame form's JCS bytes, in lowercase hex.
377    #[must_use]
378    pub fn sha256_hex(&self) -> String {
379        let mut s = String::with_capacity(64);
380        for b in self.sha256 {
381            let _ = write!(s, "{b:02x}");
382        }
383        s
384    }
385
386    /// The tag CH carries: the low four bits of the hash's last byte.
387    #[must_use]
388    pub fn tag(&self) -> Tag {
389        Tag::new(self.sha256[31] & 0x0f).expect("four bits")
390    }
391
392    /// The count's width, ⌈log₂ records⌉: none for a one-record frame.
393    #[must_use]
394    pub fn count_bits(&self) -> u32 {
395        bits_for(u64::from(self.params.records))
396    }
397
398    /// The offset's width, ⌈log₂ span⌉, where the frame has a step.
399    #[must_use]
400    pub fn offset_bits(&self) -> Option<u32> {
401        self.params.span_ms().map(bits_for)
402    }
403
404    /// The span, where the frame has a step.
405    #[must_use]
406    pub fn span_ms(&self) -> Option<u64> {
407        self.params.span_ms()
408    }
409
410    /// The record type's fields, in order.
411    #[must_use]
412    pub fn fields(&self) -> &[Field] {
413        &self.fields
414    }
415
416    /// The deadband of the field at `index`, if it has one.
417    #[must_use]
418    pub fn deadband(&self, index: usize) -> Option<&Deadband> {
419        self.deadband.get(index).and_then(Option::as_ref)
420    }
421
422    /// A record's time as a span of milliseconds after record 0: a
423    /// scheduled record lies within `jitter_ms` of its instant.
424    fn bounds(&self, i: usize, at: Option<At>) -> (u64, u64) {
425        match at {
426            None => (0, 0),
427            Some(At::Offset(o)) => (o, o),
428            Some(At::Scheduled) => {
429                let step = u64::from(self.params.step_ms.unwrap_or(0));
430                let jitter = u64::from(self.params.jitter_ms.unwrap_or(0));
431                let t = step * i as u64;
432                (t.saturating_sub(jitter), t + jitter)
433            }
434        }
435    }
436}
437
438/// Whether a field takes a deadband: an `int`, `fixed` or `counter`.
439#[must_use]
440pub fn takes_deadband(f: &Field) -> bool {
441    matches!(
442        f.kind,
443        FieldKind::Int { .. } | FieldKind::Fixed { .. } | FieldKind::Counter
444    )
445}
446
447/// Record 0's time: seconds from the deployment epoch and milliseconds.
448#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
449pub struct Time {
450    pub s: u32,
451    /// From 0 to 999.
452    pub ms: u16,
453}
454
455/// A later record's time, after record 0.
456#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
457pub enum At {
458    /// `step_ms` × i after record 0, within `jitter_ms`: an instant and a
459    /// bound, never a measurement.
460    Scheduled,
461    /// Measured: this many milliseconds after record 0.
462    Offset(u64),
463}
464
465/// One field of a record, as the body carries it.
466#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
467pub enum Slot {
468    /// A delta record's field whose bit is 0.
469    Omitted,
470    /// Included, with its presence bit 0.
471    Absent,
472    /// Included, with this code.
473    Code(u64),
474}
475
476/// One record of a frame.
477#[derive(Debug, Clone, PartialEq, Eq)]
478pub struct Record {
479    /// A full record includes every field.
480    pub full: bool,
481    /// `None` for record 0, whose time is the frame's.
482    pub at: Option<At>,
483    /// One per field, in field order.
484    pub slots: Vec<Slot>,
485}
486
487/// A frame's body, read: record 0's time, `None` when the owner's clock
488/// was unknown, and its records.
489#[derive(Debug, Clone, PartialEq, Eq)]
490pub struct Frame {
491    pub time: Option<Time>,
492    pub records: Vec<Record>,
493}
494
495/// Why a reader refused a body (core §7.7's order).
496#[derive(Debug, Clone, Copy, PartialEq, Eq)]
497pub enum ReadRefusal {
498    /// CH's tag is not the frame's.
499    Tag,
500    /// The body ends before a bit its fields need, or holds a byte after
501    /// its pad.
502    Length,
503    /// A code is unused: a millisecond code from 1000 up but the unknown
504    /// time's, a count of `records` or more, an offset at or past the
505    /// span, or a field's unused code.
506    Code,
507    /// A record lies before the record before it.
508    Order,
509    /// A bit of the pad is 1.
510    Pad,
511}
512
513impl ReadRefusal {
514    /// The token `spec/conformance/frame/bodies.json` pins.
515    #[must_use]
516    pub const fn token(self) -> &'static str {
517        match self {
518            Self::Tag => "tag",
519            Self::Length => "length",
520            Self::Code => "code",
521            Self::Order => "order",
522            Self::Pad => "pad",
523        }
524    }
525
526    /// The refusal in words, its token first.
527    #[must_use]
528    pub const fn reason(self) -> &'static str {
529        match self {
530            Self::Tag => "tag: the envelope's tag is not the frame's",
531            Self::Length => "length: the body is not as long as its fields read it",
532            Self::Code => "code: a code is unused",
533            Self::Order => "order: a record lies before the record before it",
534            Self::Pad => "pad: a bit of the pad is 1",
535        }
536    }
537}
538
539impl std::fmt::Display for ReadRefusal {
540    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
541        f.write_str(self.reason())
542    }
543}
544
545impl std::error::Error for ReadRefusal {}
546
547impl From<packed::ReadRefusal> for ReadRefusal {
548    fn from(r: packed::ReadRefusal) -> Self {
549        match r {
550            packed::ReadRefusal::Pad => Self::Pad,
551            packed::ReadRefusal::Length => Self::Length,
552            packed::ReadRefusal::Tag => Self::Tag,
553            _ => Self::Code,
554        }
555    }
556}
557
558/// Why a writer refused a frame (core §7.7, the fixtures' tokens).
559#[derive(Debug, Clone, Copy, PartialEq, Eq)]
560pub enum WriteRefusal {
561    /// No record, or more than `records`.
562    Records,
563    /// A full record without a field that is not optional, or such a field
564    /// written absent.
565    Missing,
566    /// A field the type does not have.
567    Unknown,
568    /// A value of the wrong JSON type, a name not declared, or a record
569    /// whose time is not its place's (record 0 with one, a later one
570    /// without).
571    Value,
572    /// A value with no code, an offset at or past the span, or a time
573    /// outside its codes.
574    Range,
575    /// A record that lies before the record before it.
576    Order,
577}
578
579impl WriteRefusal {
580    /// The token `spec/conformance/frame/bodies.json` pins.
581    #[must_use]
582    pub const fn token(self) -> &'static str {
583        match self {
584            Self::Records => "records",
585            Self::Missing => "missing",
586            Self::Unknown => "unknown",
587            Self::Value => "value",
588            Self::Range => "range",
589            Self::Order => "order",
590        }
591    }
592}
593
594impl std::fmt::Display for WriteRefusal {
595    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
596        f.write_str(self.token())
597    }
598}
599
600impl std::error::Error for WriteRefusal {}
601
602impl From<packed::WriteRefusal> for WriteRefusal {
603    fn from(r: packed::WriteRefusal) -> Self {
604        match r {
605            packed::WriteRefusal::Missing => Self::Missing,
606            packed::WriteRefusal::Unknown => Self::Unknown,
607            packed::WriteRefusal::Value => Self::Value,
608            packed::WriteRefusal::Range => Self::Range,
609        }
610    }
611}
612
613impl Frame {
614    /// A body read under the tag its envelope's CH carries, refusing it for
615    /// the first of core §7.7's checks that applies.
616    ///
617    /// # Errors
618    /// The reader's refusal: [`ReadRefusal`].
619    pub fn parse(tag: Tag, body: &[u8], layout: &Layout) -> Result<Frame, ReadRefusal> {
620        if tag != layout.tag() {
621            return Err(ReadRefusal::Tag);
622        }
623        let mut r = BitReader::new(body);
624        let t = r.take(42)?;
625        let time = if t == TIME_UNKNOWN {
626            None
627        } else {
628            let ms = (t & 0x3ff) as u16;
629            if ms >= 1000 {
630                return Err(ReadRefusal::Code);
631            }
632            Some(Time {
633                s: u32::try_from(t >> 10).expect("32 bits"),
634                ms,
635            })
636        };
637        let count = r.take(layout.count_bits())?;
638        if count >= u64::from(layout.params.records) {
639            return Err(ReadRefusal::Code);
640        }
641        let n = usize::try_from(count).expect("below 256") + 1;
642        let mut records = Vec::with_capacity(n);
643        let mut earliest = 0;
644        for i in 0..n {
645            let full = r.bit()?;
646            let at = if i == 0 {
647                None
648            } else if r.bit()? {
649                Some(At::Scheduled)
650            } else {
651                let o = r.take(layout.offset_bits().unwrap_or(0))?;
652                if layout.span_ms().is_none_or(|span| o >= span) {
653                    return Err(ReadRefusal::Code);
654                }
655                Some(At::Offset(o))
656            };
657            let (lo, hi) = layout.bounds(i, at);
658            if hi < earliest {
659                return Err(ReadRefusal::Order);
660            }
661            earliest = lo;
662            let included: Vec<bool> = if full {
663                vec![true; layout.fields.len()]
664            } else {
665                (0..layout.fields.len())
666                    .map(|_| r.bit())
667                    .collect::<Result<_, _>>()?
668            };
669            let mut slots = Vec::with_capacity(layout.fields.len());
670            for (f, inc) in layout.fields.iter().zip(included) {
671                if !inc {
672                    slots.push(Slot::Omitted);
673                } else if f.optional && !r.bit()? {
674                    slots.push(Slot::Absent);
675                } else {
676                    let code = r.take(f.width)?;
677                    f.check_code(code)?;
678                    slots.push(Slot::Code(code));
679                }
680            }
681            records.push(Record { full, at, slots });
682        }
683        r.end()?;
684        Ok(Frame { time, records })
685    }
686
687    /// The body's bits, then the pad: what [`Frame::parse`] reads back.
688    ///
689    /// # Errors
690    /// The writer's refusal: [`WriteRefusal`].
691    pub fn write(&self, layout: &Layout) -> Result<packed::Record, WriteRefusal> {
692        let n = self.records.len();
693        if n == 0 || n > usize::from(layout.params.records) {
694            return Err(WriteRefusal::Records);
695        }
696        let mut w = BitWriter::new();
697        match self.time {
698            None => w.push(TIME_UNKNOWN, 42),
699            Some(t) if t.ms >= 1000 => return Err(WriteRefusal::Range),
700            Some(t) => w.push((u64::from(t.s) << 10) | u64::from(t.ms), 42),
701        }
702        w.push(n as u64 - 1, layout.count_bits());
703        let mut earliest = 0;
704        for (i, rec) in self.records.iter().enumerate() {
705            if rec.slots.len() != layout.fields.len() {
706                return Err(WriteRefusal::Value);
707            }
708            w.bit(rec.full);
709            match (i, rec.at) {
710                (0, None) => {}
711                (0, Some(_)) | (_, None) => return Err(WriteRefusal::Value),
712                (_, Some(At::Scheduled)) => w.bit(true),
713                (_, Some(At::Offset(o))) => {
714                    if layout.span_ms().is_none_or(|span| o >= span) {
715                        return Err(WriteRefusal::Range);
716                    }
717                    w.bit(false);
718                    w.push(o, layout.offset_bits().unwrap_or(0));
719                }
720            }
721            let (lo, hi) = layout.bounds(i, rec.at);
722            if hi < earliest {
723                return Err(WriteRefusal::Order);
724            }
725            earliest = lo;
726            if !rec.full {
727                for s in &rec.slots {
728                    w.bit(!matches!(s, Slot::Omitted));
729                }
730            }
731            for (f, s) in layout.fields.iter().zip(&rec.slots) {
732                match s {
733                    Slot::Omitted if rec.full => return Err(WriteRefusal::Missing),
734                    Slot::Omitted => {}
735                    Slot::Absent if !f.optional => return Err(WriteRefusal::Missing),
736                    Slot::Absent => w.bit(false),
737                    Slot::Code(c) => {
738                        if (f.width < 64 && *c >> f.width != 0) || f.check_code(*c).is_err() {
739                            return Err(WriteRefusal::Range);
740                        }
741                        if f.optional {
742                            w.bit(true);
743                        }
744                        w.push(*c, f.width);
745                    }
746                }
747            }
748        }
749        Ok(w.finish())
750    }
751
752    /// The put's payload: the frame's envelope, its tag the layout's, its
753    /// stamp record 0's, then the body.
754    ///
755    /// # Errors
756    /// [`Frame::write`]'s.
757    pub fn envelope(&self, layout: &Layout, stamp: Stamp) -> Result<Vec<u8>, WriteRefusal> {
758        let body = self.write(layout)?;
759        Ok(Envelope::frame(layout.tag(), stamp, &body.bytes).write())
760    }
761
762    /// The frame as `spec/conformance/frame/bodies.json` spells a value:
763    /// `time`, `{"s", "ms"}` or `null`, and `records`, each `full`, `at`
764    /// (after record 0: `"scheduled"` or its offset), `values` (the fields
765    /// included present, as §7.6's JSON reading spells them) and `absent`
766    /// (those included absent, in field order).
767    ///
768    /// # Errors
769    /// [`ReadRefusal::Code`] where a `time` field's instant lies past an
770    /// `i64` of milliseconds under `epoch` ([`packed::ReadRefusal::Epoch`]),
771    /// which no epoch within ±9.2 × 10^15 seconds gives.
772    pub fn read_json(&self, layout: &Layout, epoch: Option<i64>) -> Result<Value, ReadRefusal> {
773        let mut records = Vec::new();
774        for rec in &self.records {
775            let mut m = Map::new();
776            m.insert("full".into(), rec.full.into());
777            match rec.at {
778                None => {}
779                Some(At::Scheduled) => {
780                    m.insert("at".into(), "scheduled".into());
781                }
782                Some(At::Offset(o)) => {
783                    m.insert("at".into(), o.into());
784                }
785            }
786            let mut values = Map::new();
787            let mut absent = Vec::new();
788            for (f, s) in layout.fields.iter().zip(&rec.slots) {
789                match s {
790                    Slot::Omitted => {}
791                    Slot::Absent => absent.push(Value::from(f.name.clone())),
792                    Slot::Code(c) => {
793                        values.insert(f.name.clone(), f.value(*c, epoch)?);
794                    }
795                }
796            }
797            m.insert("values".into(), Value::Object(values));
798            m.insert("absent".into(), Value::Array(absent));
799            records.push(Value::Object(m));
800        }
801        let time = self
802            .time
803            .map_or(Value::Null, |t| json!({"s": t.s, "ms": t.ms}));
804        Ok(json!({"time": time, "records": records}))
805    }
806
807    /// A frame from [`Frame::read_json`]'s spelling, each field's value
808    /// coded as §7.6's writer codes it. A full record's optional field in
809    /// neither `values` nor `absent` is absent.
810    ///
811    /// # Errors
812    /// The writer's refusal: [`WriteRefusal`].
813    pub fn from_json(
814        v: &Value,
815        layout: &Layout,
816        epoch: Option<i64>,
817    ) -> Result<Frame, WriteRefusal> {
818        let time = match v.get("time") {
819            Some(Value::Null) => None,
820            Some(t) => {
821                let s = t
822                    .get("s")
823                    .and_then(Value::as_u64)
824                    .ok_or(WriteRefusal::Value)?;
825                let ms = t
826                    .get("ms")
827                    .and_then(Value::as_u64)
828                    .ok_or(WriteRefusal::Value)?;
829                Some(Time {
830                    s: u32::try_from(s).map_err(|_| WriteRefusal::Range)?,
831                    ms: u16::try_from(ms)
832                        .ok()
833                        .filter(|ms| *ms < 1000)
834                        .ok_or(WriteRefusal::Range)?,
835                })
836            }
837            None => return Err(WriteRefusal::Value),
838        };
839        let recs = v
840            .get("records")
841            .and_then(Value::as_array)
842            .ok_or(WriteRefusal::Value)?;
843        if recs.is_empty() || recs.len() > usize::from(layout.params.records) {
844            return Err(WriteRefusal::Records);
845        }
846        let mut records = Vec::with_capacity(recs.len());
847        for r in recs {
848            let full = r
849                .get("full")
850                .and_then(Value::as_bool)
851                .ok_or(WriteRefusal::Value)?;
852            let at = match r.get("at") {
853                None => None,
854                Some(Value::String(s)) if s == "scheduled" => Some(At::Scheduled),
855                Some(x) => Some(At::Offset(x.as_u64().ok_or(WriteRefusal::Value)?)),
856            };
857            let empty = Map::new();
858            let values = match r.get("values") {
859                None => &empty,
860                Some(x) => x.as_object().ok_or(WriteRefusal::Value)?,
861            };
862            let absent: Vec<&str> = match r.get("absent") {
863                None => Vec::new(),
864                Some(x) => x
865                    .as_array()
866                    .ok_or(WriteRefusal::Value)?
867                    .iter()
868                    .map(|n| n.as_str().ok_or(WriteRefusal::Value))
869                    .collect::<Result<_, _>>()?,
870            };
871            let known = |n: &str| layout.fields.iter().any(|f| f.name == n);
872            if values.keys().any(|k| !known(k)) || absent.iter().any(|k| !known(k)) {
873                return Err(WriteRefusal::Unknown);
874            }
875            let mut slots = Vec::with_capacity(layout.fields.len());
876            for f in &layout.fields {
877                let slot = match values.get(&f.name) {
878                    // A counter's count is written modulo 2^width (§7.6).
879                    Some(x) => Slot::Code(f.code(x, epoch)? & packed::top_code(f.width)),
880                    None if absent.contains(&f.name.as_str()) || (full && f.optional) => {
881                        if !f.optional {
882                            return Err(WriteRefusal::Missing);
883                        }
884                        Slot::Absent
885                    }
886                    None if full => return Err(WriteRefusal::Missing),
887                    None => Slot::Omitted,
888                };
889                slots.push(slot);
890            }
891            records.push(Record { full, at, slots });
892        }
893        Ok(Frame { time, records })
894    }
895}
896
897/// What a frame follows, in the run a reader holds (core §7.7, "The
898/// frames it expects").
899#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
900pub enum Follows {
901    /// The reader held no run: its first frame of the key.
902    First,
903    /// The seq after the last record it read, in the run it holds.
904    Continues,
905    /// A newer seq by core §4.3's serial order: `lost` records lost.
906    Gap { lost: u32 },
907    /// Any other seq of the run it holds, one exactly 2^23 ahead included:
908    /// the key restarted under a run it had used, which §4.3 forbids.
909    Rewind,
910    /// A run other than the one it holds.
911    Run,
912}
913
914impl Follows {
915    /// `spec/conformance/frame/apply.json`'s token.
916    #[must_use]
917    pub const fn token(self) -> &'static str {
918        match self {
919            Self::First => "first",
920            Self::Continues => "continues",
921            Self::Gap { .. } => "gap",
922            Self::Rewind => "rewind",
923            Self::Run => "run",
924        }
925    }
926
927    /// Whether the reader turned every field `unknown` at this frame.
928    #[must_use]
929    pub const fn resets(self) -> bool {
930        !matches!(self, Self::Continues)
931    }
932}
933
934/// Why a field is `unknown` (core §7.7's table).
935#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
936pub enum Unknown {
937    /// Not included since the reader's first frame of the key.
938    First,
939    /// Not included since a frame of a run the reader did not hold.
940    Run,
941    /// Not included since records were lost.
942    Gap,
943    /// Not included since a rewind.
944    Rewind,
945    /// `max_records` records after the record that included it.
946    Deadband,
947    /// Omitted under a deadband after an inclusion that was no value: the
948    /// field absent, or a reserved code.
949    NoValue,
950}
951
952impl Unknown {
953    /// `spec/conformance/frame/apply.json`'s token.
954    #[must_use]
955    pub const fn token(self) -> &'static str {
956        match self {
957            Self::First => "first",
958            Self::Run => "run",
959            Self::Gap => "gap",
960            Self::Rewind => "rewind",
961            Self::Deadband => "deadband",
962            Self::NoValue => "no_value",
963        }
964    }
965
966    /// Why, in words, for a person (observer §7.6).
967    #[must_use]
968    pub const fn words(self) -> &'static str {
969        match self {
970            Self::First => "not included since the first frame read",
971            Self::Run => "not included since a run not held",
972            Self::Gap => "not included since records were lost",
973            Self::Rewind => "not included since a rewind",
974            Self::Deadband => "max_records passed since it was included",
975            Self::NoValue => "omitted under a deadband after no value",
976        }
977    }
978
979    fn of(follows: Follows) -> Self {
980        match follows {
981            Follows::First => Self::First,
982            Follows::Run => Self::Run,
983            Follows::Gap { .. } => Self::Gap,
984            Follows::Rewind | Follows::Continues => Self::Rewind,
985        }
986    }
987}
988
989/// A field's state in one record (core §7.7, "The reader's fields").
990#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
991pub enum FieldState {
992    /// Its value, at the record's time: included in this record, or
993    /// omitted with no deadband and nothing lost since it was included.
994    Known(u64),
995    /// The last value included, give or take its deadband's `delta`:
996    /// omitted under a deadband, fewer than `max_records` records after a
997    /// record that included a value.
998    Within(u64),
999    /// Nothing, with why: never its last value, never 0.
1000    Unknown(Unknown),
1001    /// Nothing: the owner wrote it absent.
1002    Absent,
1003}
1004
1005impl FieldState {
1006    /// `spec/conformance/frame/apply.json`'s token.
1007    #[must_use]
1008    pub const fn token(self) -> &'static str {
1009        match self {
1010            Self::Known(_) => "known",
1011            Self::Within(_) => "within",
1012            Self::Unknown(_) => "unknown",
1013            Self::Absent => "absent",
1014        }
1015    }
1016
1017    /// The code it holds: a `known` field's value, or a `within` field's
1018    /// last value (give or take its delta). `None` for `unknown` and
1019    /// `absent`, which hold none.
1020    #[must_use]
1021    pub const fn code(self) -> Option<u64> {
1022        match self {
1023            Self::Known(c) | Self::Within(c) => Some(c),
1024            Self::Unknown(_) | Self::Absent => None,
1025        }
1026    }
1027}
1028
1029/// A record's time, as a reader reads it.
1030#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1031pub enum When {
1032    /// Measured: record 0's on the owner's wall clock, a later record's as
1033    /// its offset on the owner's monotonic clock from record 0.
1034    Measured,
1035    /// `step_ms` × its index after record 0, within `jitter_ms`: an
1036    /// instant and a bound, never a measurement (observer §7.6).
1037    Scheduled { jitter_ms: u32 },
1038    /// Record 0 of a frame whose time is unknown: the owner's clock was.
1039    Unknown,
1040}
1041
1042impl When {
1043    /// `spec/conformance/frame/apply.json`'s token.
1044    #[must_use]
1045    pub const fn token(self) -> &'static str {
1046        match self {
1047            Self::Measured => "measured",
1048            Self::Scheduled { .. } => "scheduled",
1049            Self::Unknown => "unknown",
1050        }
1051    }
1052}
1053
1054/// One record of a frame, read.
1055#[derive(Debug, Clone, PartialEq, Eq)]
1056pub struct RecordRead {
1057    /// Record 0's seq plus its index, modulo 2^24.
1058    pub seq: Seq,
1059    pub when: When,
1060    /// After record 0: its offset, or `step_ms` × its index when
1061    /// scheduled. 0 for record 0.
1062    pub after_ms: u64,
1063    /// Its instant in milliseconds from the deployment epoch: record 0's
1064    /// time plus `after_ms`, `None` when that time is unknown.
1065    pub at_ms: Option<u64>,
1066    /// One per field, in field order.
1067    pub fields: Vec<FieldState>,
1068}
1069
1070/// A frame as a [`Reader`] read it.
1071#[derive(Debug, Clone, PartialEq, Eq)]
1072pub struct Applied {
1073    /// The envelope's: record 0's seq.
1074    pub stamp: Stamp,
1075    pub follows: Follows,
1076    pub records: Vec<RecordRead>,
1077    /// Record 0's seq of each frame of the run it holds that its layout
1078    /// refused since the frame before this one ([`Reader::refuse`]), in
1079    /// arrival order. Their records are among a gap's `lost`: a refused
1080    /// frame's body is not read, so how many records it held is not known
1081    /// to the reader, and only the next frame's seq tells it.
1082    pub refused: Vec<Seq>,
1083}
1084
1085impl Applied {
1086    /// The frame as `spec/conformance/frame/apply.json` spells a reading:
1087    /// `run`, `seq`, `follows` (and `lost` for a gap), then each record's
1088    /// `seq`, `time`, `after_ms` and `jitter_ms` where they apply, `at`
1089    /// (`{s, ms}`) where its instant is known, and `fields` by name, each
1090    /// `{state}` with its `value` (§7.6's JSON reading), a `within`
1091    /// field's `delta`, and an `unknown` field's `why`.
1092    ///
1093    /// # Errors
1094    /// [`Frame::read_json`]'s: a `time` field's instant past an `i64` of
1095    /// milliseconds under `epoch`.
1096    pub fn reading(&self, layout: &Layout, epoch: Option<i64>) -> Result<Value, ReadRefusal> {
1097        let mut records = Vec::with_capacity(self.records.len());
1098        for (index, rec) in self.records.iter().enumerate() {
1099            let mut m = Map::new();
1100            m.insert("seq".into(), rec.seq.get().into());
1101            m.insert("time".into(), rec.when.token().into());
1102            if index > 0 {
1103                m.insert("after_ms".into(), rec.after_ms.into());
1104            }
1105            if let When::Scheduled { jitter_ms } = rec.when {
1106                m.insert("jitter_ms".into(), jitter_ms.into());
1107            }
1108            if let Some(at) = rec.at_ms {
1109                m.insert("at".into(), json!({"s": at / 1000, "ms": at % 1000}));
1110            }
1111            let mut fields = Map::new();
1112            for (i, (f, s)) in layout.fields.iter().zip(&rec.fields).enumerate() {
1113                let mut v = Map::new();
1114                v.insert("state".into(), s.token().into());
1115                match s {
1116                    FieldState::Known(c) => {
1117                        v.insert("value".into(), f.value(*c, epoch)?);
1118                    }
1119                    FieldState::Within(c) => {
1120                        v.insert("value".into(), f.value(*c, epoch)?);
1121                        if let Some(d) = layout.deadband(i) {
1122                            v.insert("delta".into(), d.delta.to_string().into());
1123                        }
1124                    }
1125                    FieldState::Unknown(why) => {
1126                        v.insert("why".into(), why.token().into());
1127                    }
1128                    FieldState::Absent => {}
1129                }
1130                fields.insert(f.name.clone(), Value::Object(v));
1131            }
1132            m.insert("fields".into(), Value::Object(fields));
1133            records.push(Value::Object(m));
1134        }
1135        let mut out = Map::new();
1136        out.insert("run".into(), self.stamp.run.hex().into());
1137        out.insert("seq".into(), self.stamp.seq.get().into());
1138        out.insert("follows".into(), self.follows.token().into());
1139        if let Follows::Gap { lost } = self.follows {
1140            out.insert("lost".into(), lost.into());
1141        }
1142        out.insert("records".into(), Value::Array(records));
1143        Ok(Value::Object(out))
1144    }
1145}
1146
1147/// What a field's last inclusion was, since the reader last reset.
1148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1149enum Last {
1150    /// Not included since the reset.
1151    Never,
1152    Absent,
1153    /// A value's code.
1154    Value(u64),
1155    /// A reserved code: present, and no value.
1156    Reserved(u64),
1157}
1158
1159#[derive(Debug, Clone, Copy)]
1160struct Track {
1161    last: Last,
1162    /// Records since its last inclusion.
1163    since: u32,
1164}
1165
1166#[derive(Debug, Clone)]
1167struct Held {
1168    run: Run,
1169    /// The seq after the last record read.
1170    next: Seq,
1171    /// Why every field turned unknown at the last reset.
1172    reset: Unknown,
1173    /// The layout's hash: another layout is read as another run.
1174    layout: [u8; 32],
1175    tracks: Vec<Track>,
1176    /// Frames of this run its layout refused since the last one read.
1177    refused: Vec<Seq>,
1178}
1179
1180/// One key's reader (core §7.7, "The reader's fields"): what it holds of
1181/// the key's frames, in the run it holds. A consumer or a tool keeps one
1182/// per frame key and hands it each frame in the order it arrived
1183/// ([`Reader::apply`]). A frame refused by its layout is never applied: its
1184/// body is not read, so neither its fields nor how many records it held
1185/// are known, and the next frame's seq reads its records as lost, a gap
1186/// (core §7.7, "The frames it expects": a seq newer than the one expected
1187/// follows records lost, whatever lost them; `spec/conformance/frame/
1188/// apply.json` reads a gap so). [`Reader::refuse`] notes it, so the next
1189/// frame says which of its lost records were refused ([`Applied::refused`]).
1190#[derive(Debug, Clone, Default)]
1191pub struct Reader {
1192    held: Option<Held>,
1193}
1194
1195impl Reader {
1196    /// A reader that holds nothing: its first frame is [`Follows::First`].
1197    #[must_use]
1198    pub fn new() -> Self {
1199        Self::default()
1200    }
1201
1202    /// The run it holds, and the seq it expects next.
1203    #[must_use]
1204    pub fn expects(&self) -> Option<Stamp> {
1205        self.held.as_ref().map(|h| Stamp {
1206            run: h.run,
1207            seq: h.next,
1208        })
1209    }
1210
1211    /// Notes a frame at `stamp` whose layout refused it (core §7.7's
1212    /// refusals). It is never applied: the reader still expects the seq
1213    /// after the last record it read, so the next frame follows a gap
1214    /// counting the refused frame's records, and lists its seq in
1215    /// [`Applied::refused`]. A refused frame of a run it does not hold is
1216    /// forgotten: the next frame of that run resets every field anyway.
1217    pub fn refuse(&mut self, stamp: Stamp) {
1218        if let Some(h) = &mut self.held
1219            && h.run == stamp.run
1220            && h.refused.len() < usize::from(u16::MAX)
1221        {
1222            h.refused.push(stamp.seq);
1223        }
1224    }
1225
1226    /// What a frame at `stamp` would follow, read under `layout`.
1227    #[must_use]
1228    pub fn follows(&self, layout: &Layout, stamp: Stamp) -> Follows {
1229        let Some(h) = &self.held else {
1230            return Follows::First;
1231        };
1232        if h.run != stamp.run || h.layout != layout.sha256 {
1233            return Follows::Run;
1234        }
1235        const SPACE: u32 = 1 << 24;
1236        const HALF: u32 = 1 << 23;
1237        let d = stamp.seq.get().wrapping_sub(h.next.get()) & (SPACE - 1);
1238        match d {
1239            0 => Follows::Continues,
1240            d if d < HALF => Follows::Gap { lost: d },
1241            _ => Follows::Rewind,
1242        }
1243    }
1244
1245    /// Reads a frame of the key, `stamp` its envelope's, `frame` its body
1246    /// read under `layout` ([`Frame::parse`]): every field turns
1247    /// `unknown` at a gap, a rewind and a run not held (its first frame
1248    /// included), then each record is read in turn, a field `known` or
1249    /// `absent` where included, carried where omitted with no deadband,
1250    /// `within` under its deadband until `max_records` records after it
1251    /// was included with a value, and `unknown` past it.
1252    ///
1253    /// A reader holds one layout: a frame under another (another revision
1254    /// of the resource) is read as one of a run it does not hold.
1255    pub fn apply(&mut self, layout: &Layout, stamp: Stamp, frame: &Frame) -> Applied {
1256        let follows = self.follows(layout, stamp);
1257        let n = layout.fields.len();
1258        // A frame refused in the run held is among what this one follows.
1259        let refused = self
1260            .held
1261            .as_mut()
1262            .filter(|h| h.run == stamp.run)
1263            .map(|h| std::mem::take(&mut h.refused))
1264            .unwrap_or_default();
1265        let held = match (&mut self.held, follows.resets()) {
1266            (Some(h), false) => h,
1267            (slot, _) => slot.insert(Held {
1268                run: stamp.run,
1269                next: stamp.seq,
1270                reset: Unknown::of(follows),
1271                layout: layout.sha256,
1272                tracks: vec![
1273                    Track {
1274                        last: Last::Never,
1275                        since: 0,
1276                    };
1277                    n
1278                ],
1279                refused: Vec::new(),
1280            }),
1281        };
1282        let base = frame.time.map(|t| u64::from(t.s) * 1000 + u64::from(t.ms));
1283        let mut records = Vec::with_capacity(frame.records.len());
1284        for (i, rec) in frame.records.iter().enumerate() {
1285            let seq = Seq::new((stamp.seq.get() + i as u32) & Seq::MAX.get()).expect("24 bits");
1286            let (when, after_ms) = match rec.at {
1287                None if base.is_none() => (When::Unknown, 0),
1288                None => (When::Measured, 0),
1289                Some(At::Offset(o)) => (When::Measured, o),
1290                Some(At::Scheduled) => (
1291                    When::Scheduled {
1292                        jitter_ms: layout.params.jitter_ms.unwrap_or(0),
1293                    },
1294                    u64::from(layout.params.step_ms.unwrap_or(0)) * i as u64,
1295                ),
1296            };
1297            let mut fields = Vec::with_capacity(n);
1298            for (k, (f, slot)) in layout.fields.iter().zip(&rec.slots).enumerate() {
1299                let t = &mut held.tracks[k];
1300                let state = match slot {
1301                    Slot::Code(c) => {
1302                        *t = Track {
1303                            last: if f.reserved_name(*c).is_some() {
1304                                Last::Reserved(*c)
1305                            } else {
1306                                Last::Value(*c)
1307                            },
1308                            since: 0,
1309                        };
1310                        FieldState::Known(*c)
1311                    }
1312                    Slot::Absent => {
1313                        *t = Track {
1314                            last: Last::Absent,
1315                            since: 0,
1316                        };
1317                        FieldState::Absent
1318                    }
1319                    Slot::Omitted => {
1320                        t.since = t.since.saturating_add(1);
1321                        match (t.last, layout.deadband(k)) {
1322                            (Last::Never, _) => FieldState::Unknown(held.reset),
1323                            (Last::Absent, None) => FieldState::Absent,
1324                            (Last::Value(c) | Last::Reserved(c), None) => FieldState::Known(c),
1325                            (Last::Absent | Last::Reserved(_), Some(_)) => {
1326                                FieldState::Unknown(Unknown::NoValue)
1327                            }
1328                            (Last::Value(_), Some(d)) if t.since >= d.max_records => {
1329                                FieldState::Unknown(Unknown::Deadband)
1330                            }
1331                            (Last::Value(c), Some(_)) => FieldState::Within(c),
1332                        }
1333                    }
1334                };
1335                fields.push(state);
1336            }
1337            records.push(RecordRead {
1338                seq,
1339                when,
1340                after_ms,
1341                at_ms: base.map(|b| b + after_ms),
1342                fields,
1343            });
1344        }
1345        let count = u32::try_from(frame.records.len()).expect("at most 256");
1346        held.next = Seq::new((stamp.seq.get() + count) & Seq::MAX.get()).expect("24 bits");
1347        Applied {
1348            stamp,
1349            follows,
1350            records,
1351            refused,
1352        }
1353    }
1354}
1355
1356// ── The owner's frames (core §7.7, "The owner's frames"; #981's K3) ─────
1357
1358impl Time {
1359    /// The time of an instant `t`, in milliseconds since the Unix epoch,
1360    /// under the deployment epoch `epoch` in seconds: `None` for one before
1361    /// the epoch or 2^32 seconds after it, which the owner writes as
1362    /// unknown.
1363    #[must_use]
1364    pub fn from_unix_ms(t: i128, epoch: i64) -> Option<Time> {
1365        let delta = t - 1000 * i128::from(epoch);
1366        let (s, ms) = (delta.div_euclid(1000), delta.rem_euclid(1000));
1367        Some(Time {
1368            s: u32::try_from(s).ok()?,
1369            ms: u16::try_from(ms).expect("below 1000"),
1370        })
1371    }
1372
1373    /// The instant in milliseconds since the Unix epoch, under `epoch`.
1374    #[must_use]
1375    pub fn unix_ms(self, epoch: i64) -> i128 {
1376        1000 * (i128::from(epoch) + i128::from(self.s)) + i128::from(self.ms)
1377    }
1378}
1379
1380impl Layout {
1381    /// A §7.6 record of the frame's record type read into a full record's
1382    /// slots: each field absent or its code. The record's own tag is not
1383    /// asked: its bytes are the type's.
1384    ///
1385    /// # Errors
1386    /// [`ReadRefusal::Length`], [`ReadRefusal::Code`] or
1387    /// [`ReadRefusal::Pad`], as §7.6's reader refuses the record.
1388    pub fn slots_of(&self, record: &[u8]) -> Result<Vec<Slot>, ReadRefusal> {
1389        let mut r = BitReader::new(record);
1390        let mut slots = Vec::with_capacity(self.fields.len());
1391        for f in &self.fields {
1392            if f.optional && !r.bit()? {
1393                slots.push(Slot::Absent);
1394                continue;
1395            }
1396            let code = r.take(f.width)?;
1397            f.check_code(code)?;
1398            slots.push(Slot::Code(code));
1399        }
1400        r.end()?;
1401        Ok(slots)
1402    }
1403
1404    /// A record in §7.6's JSON reading, a field's name to its value, read
1405    /// into a full record's slots: an optional field left out or `null` is
1406    /// absent. A `time` field counts from `epoch`.
1407    ///
1408    /// # Errors
1409    /// [`WriteRefusal`]: `value` for a value that is no object, `unknown`
1410    /// for a name the type does not have, `missing` for a field that is not
1411    /// optional left out, and §7.6's refusals of a value.
1412    pub fn slots_of_json(&self, v: &Value, epoch: Option<i64>) -> Result<Vec<Slot>, WriteRefusal> {
1413        let m = v.as_object().ok_or(WriteRefusal::Value)?;
1414        if m.keys().any(|k| !self.fields.iter().any(|f| &f.name == k)) {
1415            return Err(WriteRefusal::Unknown);
1416        }
1417        self.fields
1418            .iter()
1419            .map(|f| match m.get(&f.name) {
1420                None | Some(Value::Null) if f.optional => Ok(Slot::Absent),
1421                None => Err(WriteRefusal::Missing),
1422                Some(x) => Ok(Slot::Code(f.code(x, epoch)? & packed::top_code(f.width))),
1423            })
1424            .collect()
1425    }
1426
1427    /// The bits of the largest frame an owner writes (link.v1 §2.8's
1428    /// `frame_over_batch`, 0.16, F-470): `records` records, every optional
1429    /// field present, and every record after record 0 measured, with its
1430    /// offset. As many of them as `keyframe_every` allows are delta records
1431    /// that include every field, each a bit per field longer than a full
1432    /// record (core §7.7): a full record comes at least once every
1433    /// `keyframe_every`, so `records` − ⌊`records` / `keyframe_every`⌋ of
1434    /// them, none at 1. The rest are full.
1435    #[must_use]
1436    pub fn largest_body_bits(&self) -> u64 {
1437        let mut fields = 0u64;
1438        let mut record = 1u64;
1439        for f in &self.fields {
1440            fields += 1;
1441            record += u64::from(f.width) + u64::from(f.optional);
1442        }
1443        let n = u64::from(self.params.records);
1444        let deltas = n - n / u64::from(self.params.keyframe_every.max(1));
1445        let later = n.saturating_sub(1) * (1 + u64::from(self.offset_bits().unwrap_or(0)));
1446        42 + u64::from(self.count_bits()) + n * record + deltas * fields + later
1447    }
1448
1449    /// The payload of that largest frame, in bytes: its body after an
1450    /// envelope of a 32-bit run, 8 bytes (core §7.5).
1451    #[must_use]
1452    pub fn largest_payload_bytes(&self) -> u64 {
1453        8 + self.largest_body_bits().div_ceil(8)
1454    }
1455
1456    /// The value of a field's code a deadband weighs: an `int`'s integer,
1457    /// a `fixed`'s decimal, a `counter`'s count. `None` for a reserved code,
1458    /// which holds no value, and for a field that takes no deadband.
1459    fn weighed(&self, index: usize, code: u64) -> Option<Decimal> {
1460        let f = &self.fields[index];
1461        if f.reserved_name(code).is_some() {
1462            return None;
1463        }
1464        match &f.kind {
1465            FieldKind::Int {
1466                minimum, maximum, ..
1467            } => packed::int_value(code, *minimum, *maximum)
1468                .ok()
1469                .map(Decimal::of_i128),
1470            FieldKind::Fixed {
1471                minimum,
1472                resolution,
1473                values,
1474                ..
1475            } => packed::fixed_value(code, minimum, resolution, *values).ok(),
1476            FieldKind::Counter => Some(Decimal::of_i128(i128::from(code))),
1477            _ => None,
1478        }
1479    }
1480}
1481
1482/// One record an owner measured: each field absent or its code
1483/// ([`Slot::Absent`], [`Slot::Code`]), when it measured it on its
1484/// monotonic clock (`at`), and its wall clock's time then, `None` while
1485/// its clock is unknown. Only record 0's wall time is written: a later
1486/// record's time is its offset on the monotonic clock (core §7.7,
1487/// "Times").
1488#[derive(Debug, Clone, PartialEq, Eq)]
1489pub struct Measured {
1490    pub slots: Vec<Slot>,
1491    pub at: crate::timing::Mono,
1492    pub wall: Option<Time>,
1493}
1494
1495/// The records of one frame, in the order they were measured: what a
1496/// [`Framer`] hands its owner to write ([`Framer::encode`]).
1497#[derive(Debug, Clone, PartialEq, Eq)]
1498pub struct Batch(Vec<Measured>);
1499
1500impl Batch {
1501    /// How many records it holds, and so how many seqs its frame takes
1502    /// (core §4.3).
1503    #[must_use]
1504    #[allow(clippy::len_without_is_empty)]
1505    pub fn len(&self) -> u32 {
1506        u32::try_from(self.0.len()).expect("at most 256")
1507    }
1508
1509    /// Its records.
1510    #[must_use]
1511    pub fn records(&self) -> &[Measured] {
1512        &self.0
1513    }
1514}
1515
1516/// What the key's readers hold after the last frame an owner sent, in the
1517/// run it was sent under: what the next delta record is written against.
1518#[derive(Debug, Clone, PartialEq, Eq)]
1519struct Sent {
1520    run: Run,
1521    /// The last record sent, every field absent or a code.
1522    prev: Vec<Slot>,
1523    /// Each field as the last record that included it held it.
1524    included: Vec<Slot>,
1525    /// Records since each field was last included.
1526    since: Vec<u32>,
1527    /// Records since the last full record.
1528    since_full: u32,
1529}
1530
1531/// A batch written as a frame under a run ([`Framer::encode`]), and what
1532/// the key's readers hold once it is sent: [`Framer::sent`] keeps that.
1533#[derive(Debug, Clone, PartialEq, Eq)]
1534pub struct Encoded {
1535    pub frame: Frame,
1536    next: Sent,
1537}
1538
1539/// One frame key's writer (core §7.7, "The owner's frames"): a pure state
1540/// machine an owner hands each record it measures, in the order it
1541/// measured them ([`Framer::push`]), which says when a frame is complete
1542/// and writes it ([`Framer::encode`]). The owner takes the frame's seqs,
1543/// one per record (§4.3), puts it, and tells the framer it was sent
1544/// ([`Framer::sent`]). A frame never sent leaves nothing behind: the
1545/// next is written against the last one sent.
1546///
1547/// - **Frames.** A frame holds up to `records` records. A record that
1548///   would lie at or past the open frame's span ends it, and opens the
1549///   next as its record 0. [`Framer::flush`] ends the open frame early.
1550/// - **Full records.** Record 0 of the first frame written under a run is
1551///   full, and so is a record `keyframe_every` records after the last full
1552///   one. A delta record that would include every field is written full.
1553/// - **Delta records** include each field with no deadband whose code or
1554///   presence differs from the record before. A field with a deadband is
1555///   omitted while it holds a value within `delta` of the value last
1556///   included, as that inclusion did, and fewer than `max_records`
1557///   records passed since; else it is included.
1558/// - **Times.** Record 0 carries its wall time. A later record is
1559///   scheduled when its offset from record 0, on the monotonic clock, lies
1560///   within `jitter_ms` of `step_ms` × its index, and carries its offset,
1561///   in whole milliseconds, otherwise.
1562#[derive(Debug, Clone)]
1563pub struct Framer {
1564    layout: Layout,
1565    open: Vec<Measured>,
1566    last_at: Option<crate::timing::Mono>,
1567    sent: Option<Sent>,
1568}
1569
1570impl Framer {
1571    /// A framer of `layout`'s frames that has sent none.
1572    #[must_use]
1573    pub fn new(layout: Layout) -> Self {
1574        Self {
1575            layout,
1576            open: Vec::new(),
1577            last_at: None,
1578            sent: None,
1579        }
1580    }
1581
1582    /// Its layout.
1583    #[must_use]
1584    pub fn layout(&self) -> &Layout {
1585        &self.layout
1586    }
1587
1588    /// How many records the open frame holds.
1589    #[must_use]
1590    pub fn open(&self) -> usize {
1591        self.open.len()
1592    }
1593
1594    /// The run the last frame sent was written under.
1595    #[must_use]
1596    pub fn run(&self) -> Option<Run> {
1597        self.sent.as_ref().map(|s| s.run)
1598    }
1599
1600    /// Takes a measured record, refused before anything is kept: a slot
1601    /// omitted, one per field missing, a field that is not optional
1602    /// written absent, a code its field does not use, or a record measured
1603    /// before the last one.
1604    ///
1605    /// Returns the frame now complete, if one is: the open frame, when
1606    /// this record lies at or past its span (this record then opens the
1607    /// next frame), or the open frame with this record, when that holds
1608    /// `records` records. A one-record frame is complete at once.
1609    ///
1610    /// # Errors
1611    /// [`WriteRefusal`]: `value` for a slot omitted or the wrong count,
1612    /// `missing`, `range`, `order`.
1613    pub fn push(&mut self, m: Measured) -> Result<Option<Batch>, WriteRefusal> {
1614        if m.slots.len() != self.layout.fields.len() {
1615            return Err(WriteRefusal::Value);
1616        }
1617        for (f, s) in self.layout.fields.iter().zip(&m.slots) {
1618            match s {
1619                Slot::Omitted => return Err(WriteRefusal::Value),
1620                Slot::Absent if !f.optional => return Err(WriteRefusal::Missing),
1621                Slot::Absent => {}
1622                Slot::Code(c) => {
1623                    if (f.width < 64 && *c >> f.width != 0) || f.check_code(*c).is_err() {
1624                        return Err(WriteRefusal::Range);
1625                    }
1626                }
1627            }
1628        }
1629        if self.last_at.is_some_and(|l| m.at < l) {
1630            return Err(WriteRefusal::Order);
1631        }
1632        self.last_at = Some(m.at);
1633        let past_span = match (self.open.first(), self.layout.params.span_ms()) {
1634            (Some(first), Some(span)) => {
1635                m.at.since_origin().saturating_sub(first.at.since_origin())
1636                    >= Duration::from_millis(span)
1637            }
1638            _ => false,
1639        };
1640        let ended = if past_span {
1641            Some(Batch(std::mem::take(&mut self.open)))
1642        } else {
1643            None
1644        };
1645        self.open.push(m);
1646        if ended.is_some() {
1647            return Ok(ended);
1648        }
1649        if self.open.len() >= usize::from(self.layout.params.records) {
1650            return Ok(Some(Batch(std::mem::take(&mut self.open))));
1651        }
1652        Ok(None)
1653    }
1654
1655    /// Ends the open frame now, if it holds a record: an owner that puts
1656    /// what it measured so far, or stops.
1657    pub fn flush(&mut self) -> Option<Batch> {
1658        (!self.open.is_empty()).then(|| Batch(std::mem::take(&mut self.open)))
1659    }
1660
1661    /// `batch` written as a frame under `run`: record 0 full when the last
1662    /// frame sent was another run's, or none was; each later record's time
1663    /// and fields as [`Framer`] says.
1664    #[must_use]
1665    pub fn encode(&self, batch: &Batch, run: Run) -> Encoded {
1666        let l = &self.layout;
1667        let n = l.fields.len();
1668        let mut state = self.sent.clone().filter(|s| s.run == run);
1669        let origin = batch.0[0].at.since_origin();
1670        let mut records = Vec::with_capacity(batch.0.len());
1671        for (i, m) in batch.0.iter().enumerate() {
1672            let at = (i > 0).then(|| {
1673                let off = m.at.since_origin().saturating_sub(origin);
1674                let scheduled = l.params.step_ms.is_some_and(|step| {
1675                    let instant = Duration::from_millis(u64::from(step) * i as u64);
1676                    let jitter = Duration::from_millis(u64::from(l.params.jitter_ms.unwrap_or(0)));
1677                    off.abs_diff(instant) <= jitter
1678                });
1679                if scheduled {
1680                    At::Scheduled
1681                } else {
1682                    At::Offset(u64::try_from(off.as_millis()).unwrap_or(u64::MAX))
1683                }
1684            });
1685            let (full, slots, next) = match state {
1686                None => (true, m.slots.clone(), None),
1687                Some(ref s) => {
1688                    let include: Vec<bool> =
1689                        (0..n).map(|k| self.includes(s, k, m.slots[k])).collect();
1690                    let full =
1691                        s.since_full + 1 >= l.params.keyframe_every || include.iter().all(|x| *x);
1692                    let slots = if full {
1693                        m.slots.clone()
1694                    } else {
1695                        m.slots
1696                            .iter()
1697                            .zip(&include)
1698                            .map(|(slot, inc)| if *inc { *slot } else { Slot::Omitted })
1699                            .collect()
1700                    };
1701                    (full, slots, Some(s))
1702                }
1703            };
1704            let mut s = next.cloned().unwrap_or(Sent {
1705                run,
1706                prev: m.slots.clone(),
1707                included: m.slots.clone(),
1708                since: vec![0; n],
1709                since_full: 0,
1710            });
1711            for (k, slot) in slots.iter().enumerate() {
1712                if matches!(slot, Slot::Omitted) {
1713                    s.since[k] = s.since[k].saturating_add(1);
1714                } else {
1715                    s.included[k] = *slot;
1716                    s.since[k] = 0;
1717                }
1718            }
1719            s.since_full = if full { 0 } else { s.since_full + 1 };
1720            s.prev = m.slots.clone();
1721            state = Some(s);
1722            records.push(Record { full, at, slots });
1723        }
1724        Encoded {
1725            frame: Frame {
1726                time: batch.0[0].wall,
1727                records,
1728            },
1729            next: state.expect("a record at least"),
1730        }
1731    }
1732
1733    /// Whether a delta record after `s` includes field `k`, now `slot`.
1734    fn includes(&self, s: &Sent, k: usize, slot: Slot) -> bool {
1735        let Some(d) = self.layout.deadband(k) else {
1736            return slot != s.prev[k];
1737        };
1738        let (Slot::Code(now), Slot::Code(then)) = (slot, s.included[k]) else {
1739            return true;
1740        };
1741        if s.since[k] + 1 >= d.max_records {
1742            return true;
1743        }
1744        match (self.layout.weighed(k, now), self.layout.weighed(k, then)) {
1745            (Some(a), Some(b)) => a.distance(&b) > d.delta,
1746            _ => true,
1747        }
1748    }
1749
1750    /// `e` was sent: the next frame is written against it.
1751    pub fn sent(&mut self, e: Encoded) {
1752        self.sent = Some(e.next);
1753    }
1754}
1755
1756#[cfg(test)]
1757mod tests {
1758    use super::*;
1759
1760    fn link() -> packed::Layout {
1761        let doc = json!({"types": {"Link": {"fields": [
1762            {"name": "dropped", "type": "counter", "width": 32, "optional": true},
1763            {"name": "queue_depth", "type": "int", "minimum": 0, "maximum": 1022,
1764             "reserved": ["out_of_range"], "optional": true},
1765            {"name": "duty_available", "type": "int", "minimum": 0, "maximum": 1, "optional": true},
1766            {"name": "duty_wait_ms", "type": "fixed", "minimum": "0", "maximum": "3600000",
1767             "resolution": "100", "reserved": ["out_of_range"], "optional": true}
1768        ]}}});
1769        packed::layout_in(&doc, "Link").expect("a layout")
1770    }
1771
1772    fn one() -> FrameParams {
1773        FrameParams::resolve(&FrameSpec::default()).expect("the defaults")
1774    }
1775
1776    /// zenoh-modem's four link readings, one record a frame (#981's §3):
1777    /// a 63-bit record, so a keyframe's body is 14 bytes and its payload 20.
1778    #[test]
1779    fn zenoh_modems_link_frame() {
1780        let l = Layout::of(&link(), &one()).expect("a frame layout");
1781        assert_eq!(
1782            (l.count_bits(), l.offset_bits(), l.span_ms()),
1783            (0, None, None)
1784        );
1785        let all = json!({"time": {"s": 3600, "ms": 250}, "records": [{"full": true,
1786            "values": {"dropped": 7, "queue_depth": 12, "duty_available": 1, "duty_wait_ms": "1500"},
1787            "absent": []}]});
1788        let f = Frame::from_json(&all, &l, None).expect("a frame");
1789        let body = f.write(&l).expect("written");
1790        assert_eq!((body.bits, body.bytes.len()), (106, 14));
1791        let stamp = Stamp {
1792            run: crate::wire::Run::U16(1),
1793            seq: crate::wire::Seq::new(12).unwrap(),
1794        };
1795        let put = f.envelope(&l, stamp).expect("an envelope");
1796        assert_eq!(put.len(), 20);
1797        let e = Envelope::parse(&put).expect("parsed");
1798        assert!(e.is_frame());
1799        let back = Frame::parse(e.tag, e.record, &l).expect("read back");
1800        assert_eq!(back, f);
1801        assert_eq!(back.read_json(&l, None).unwrap(), all);
1802        // A delta record with the queue and the wait changed: 10 bytes.
1803        let d = json!({"time": {"s": 3660, "ms": 0}, "records": [{"full": false,
1804            "values": {"queue_depth": 30, "duty_wait_ms": "2500"}, "absent": []}]});
1805        let body = Frame::from_json(&d, &l, None).unwrap().write(&l).unwrap();
1806        assert_eq!((body.bits, body.bytes.len()), (75, 10));
1807        // Nothing changed: 6 bytes.
1808        let d = json!({"time": {"s": 3720, "ms": 0}, "records": [{"full": false}]});
1809        let body = Frame::from_json(&d, &l, None).unwrap().write(&l).unwrap();
1810        assert_eq!((body.bits, body.bytes.len()), (47, 6));
1811    }
1812
1813    #[test]
1814    fn the_table_resolves_or_names_each_finding() {
1815        let p = one();
1816        assert_eq!(
1817            (p.records, p.step_ms, p.jitter_ms, p.keyframe_every),
1818            (1, None, None, 1)
1819        );
1820        let p = FrameParams::resolve(&FrameSpec {
1821            records: Some(3),
1822            step_ms: Some(10_000),
1823            ..FrameSpec::default()
1824        })
1825        .unwrap();
1826        assert_eq!((p.jitter_ms, p.span_ms()), (Some(0), Some(30_000)));
1827        let bad = FrameParams::resolve(&FrameSpec {
1828            records: Some(0),
1829            jitter_ms: Some(1),
1830            keyframe_every: Some(0),
1831            ..FrameSpec::default()
1832        })
1833        .unwrap_err();
1834        assert_eq!(bad.len(), 3, "{bad:?}");
1835        assert_eq!(FrameParams::from_canonical(&p.canonical()), Ok(p));
1836    }
1837
1838    /// A frame its layout refuses is never applied (core §7.7): the next
1839    /// frame follows a gap that counts its records, and names it.
1840    #[test]
1841    fn a_refused_frame_reads_as_lost_and_is_named() {
1842        let l = Layout::of(&link(), &one()).unwrap();
1843        let stamp = |seq| Stamp {
1844            run: crate::wire::Run::U16(1),
1845            seq: Seq::new(seq).unwrap(),
1846        };
1847        let full = Frame::from_json(
1848            &json!({"time": {"s": 1, "ms": 0}, "records": [{"full": true, "values": {"dropped": 1}}]}),
1849            &l,
1850            None,
1851        )
1852        .unwrap();
1853        let mut r = Reader::new();
1854        assert!(r.apply(&l, stamp(10), &full).refused.is_empty());
1855        r.refuse(stamp(11));
1856        let next = r.apply(&l, stamp(12), &full);
1857        assert_eq!(next.follows, Follows::Gap { lost: 1 });
1858        assert_eq!(next.refused, [Seq::new(11).unwrap()]);
1859        // Noted once: the frame after reads none.
1860        assert!(r.apply(&l, stamp(13), &full).refused.is_empty());
1861        // Another run's refusal is forgotten.
1862        r.refuse(Stamp {
1863            run: crate::wire::Run::U16(2),
1864            seq: Seq::new(0).unwrap(),
1865        });
1866        assert!(r.apply(&l, stamp(14), &full).refused.is_empty());
1867    }
1868
1869    fn sample() -> packed::Layout {
1870        let doc = json!({"types": {"Sample": {"fields": [
1871            {"name": "temperature", "type": "fixed", "minimum": "-40", "maximum": "85",
1872             "resolution": "0.5"},
1873            {"name": "rssi", "type": "int", "minimum": -140, "maximum": -20,
1874             "reserved": ["not_available"]},
1875            {"name": "link_up", "type": "bool"},
1876            {"name": "mode", "type": "enum", "values": ["idle", "rx", "tx"], "escape": true,
1877             "optional": true}
1878        ]}}});
1879        packed::layout_in(&doc, "Sample").expect("a layout")
1880    }
1881
1882    fn params(spec: FrameSpec) -> FrameParams {
1883        FrameParams::resolve(&spec).expect("a table")
1884    }
1885
1886    fn measured(l: &Layout, v: Value, ms: u64) -> Measured {
1887        Measured {
1888            slots: l.slots_of_json(&v, None).expect("slots"),
1889            at: crate::timing::Mono::after(Duration::from_millis(ms)),
1890            wall: Some(Time { s: 100, ms: 0 }),
1891        }
1892    }
1893
1894    fn base(queue: u64) -> Value {
1895        json!({"dropped": 7, "queue_depth": queue, "duty_available": 1, "duty_wait_ms": "1500"})
1896    }
1897
1898    /// Writes each batch under `run` from seq `next`, as an owner would,
1899    /// and reads it back through a reader.
1900    fn send(f: &mut Framer, r: &mut Reader, batch: &Batch, run: Run, next: &mut u32) -> Applied {
1901        let e = f.encode(batch, run);
1902        let l = f.layout().clone();
1903        let stamp = Stamp {
1904            run,
1905            seq: Seq::new(*next).unwrap(),
1906        };
1907        let put = e.frame.envelope(&l, stamp).expect("written");
1908        let env = Envelope::parse(&put).unwrap();
1909        let back = Frame::parse(env.tag, env.record, &l).expect("read back");
1910        assert_eq!(back, e.frame);
1911        *next += batch.len();
1912        f.sent(e);
1913        r.apply(&l, stamp, &back)
1914    }
1915
1916    /// The owner's rules (core §7.7): its first frame in a run full, a full
1917    /// record every `keyframe_every`, a delta record including what
1918    /// changed, a deadband omitted within `delta` and included every
1919    /// `max_records`, and a new run full again; a reader of its frames
1920    /// reads every field known or within.
1921    #[test]
1922    fn a_framer_writes_the_owners_frames() {
1923        let p = params(FrameSpec {
1924            keyframe_every: Some(4),
1925            deadband: [(
1926                "queue_depth".to_owned(),
1927                crate::authoring::DeadbandSpec {
1928                    delta: "4".to_owned(),
1929                    max_records: 3,
1930                },
1931            )]
1932            .into(),
1933            ..FrameSpec::default()
1934        });
1935        let l = Layout::of(&link(), &p).unwrap();
1936        let mut f = Framer::new(l.clone());
1937        let mut r = Reader::new();
1938        let (run, mut next) = (Run::U16(1), 0);
1939        let one = |f: &mut Framer, r: &mut Reader, v: Value, ms: u64, run: Run, next: &mut u32| {
1940            let b = f
1941                .push(measured(&l, v, ms))
1942                .unwrap()
1943                .expect("one record a frame");
1944            send(f, r, &b, run, next)
1945        };
1946        let a = one(&mut f, &mut r, base(12), 0, run, &mut next);
1947        assert!(
1948            a.records[0]
1949                .fields
1950                .iter()
1951                .all(|s| matches!(s, FieldState::Known(_)))
1952        );
1953        // Within 4 of 12, the rest unchanged: nothing included.
1954        let a = one(&mut f, &mut r, base(15), 1000, run, &mut next);
1955        assert_eq!(a.follows, Follows::Continues);
1956        assert_eq!(a.records[0].fields[1], FieldState::Within(12));
1957        let a = one(&mut f, &mut r, base(9), 2000, run, &mut next);
1958        assert_eq!(a.records[0].fields[1], FieldState::Within(12));
1959        // Three records after its inclusion: included, 13.
1960        let a = one(&mut f, &mut r, base(13), 3000, run, &mut next);
1961        assert_eq!(a.records[0].fields[1], FieldState::Known(13));
1962        // Four records after the full one: full again.
1963        let mut v = base(13);
1964        v["duty_wait_ms"] = json!("2500");
1965        let e = f.encode(
1966            &f.clone()
1967                .push(measured(&l, v.clone(), 4000))
1968                .unwrap()
1969                .unwrap(),
1970            run,
1971        );
1972        assert!(e.frame.records[0].full);
1973        let a = one(&mut f, &mut r, v, 4000, run, &mut next);
1974        assert_eq!(a.records[0].fields[3], FieldState::Known(25));
1975        // A delta: the wait changed alone.
1976        let mut v = base(13);
1977        v["duty_wait_ms"] = json!("1500");
1978        let e = f.encode(
1979            &f.clone()
1980                .push(measured(&l, v.clone(), 5000))
1981                .unwrap()
1982                .unwrap(),
1983            run,
1984        );
1985        assert!(!e.frame.records[0].full);
1986        assert_eq!(
1987            e.frame.records[0].slots,
1988            vec![Slot::Omitted, Slot::Omitted, Slot::Omitted, Slot::Code(15)]
1989        );
1990        // A field turned absent is included, its presence bit 0.
1991        let a = one(&mut f, &mut r, v, 5000, run, &mut next);
1992        let mut v = base(13);
1993        v.as_object_mut().unwrap().remove("dropped");
1994        let a2 = one(&mut f, &mut r, v, 6000, run, &mut next);
1995        assert_eq!(a.records[0].fields[0], FieldState::Known(7));
1996        assert_eq!(a2.records[0].fields[0], FieldState::Absent);
1997        // A new run: full, whatever changed.
1998        let b = f.push(measured(&l, base(13), 7000)).unwrap().unwrap();
1999        let e = f.encode(&b, Run::U16(2));
2000        assert!(e.frame.records[0].full);
2001        // A frame never sent leaves nothing: the next is written against
2002        // the last one sent, `dropped` present again, and the queue three
2003        // records after its inclusion.
2004        let e = f.encode(&b, run);
2005        assert_eq!(
2006            e.frame.records[0].slots,
2007            vec![Slot::Code(7), Slot::Code(13), Slot::Omitted, Slot::Omitted]
2008        );
2009    }
2010
2011    /// Times (core §7.7): a record within the jitter of its instant is
2012    /// scheduled, another measured; a record at or past the span ends the
2013    /// frame and opens the next; a record measured before the last is
2014    /// refused.
2015    #[test]
2016    fn a_framer_schedules_and_ends_frames() {
2017        let p = params(FrameSpec {
2018            records: Some(3),
2019            step_ms: Some(10_000),
2020            jitter_ms: Some(500),
2021            keyframe_every: Some(3),
2022            ..FrameSpec::default()
2023        });
2024        let l = Layout::of(&sample(), &p).unwrap();
2025        let mut f = Framer::new(l.clone());
2026        let v = |t: &str, rssi: i64, mode: &str| json!({"temperature": t, "rssi": rssi, "link_up": true, "mode": mode});
2027        assert_eq!(f.push(measured(&l, v("21.5", -80, "rx"), 0)).unwrap(), None);
2028        assert_eq!(
2029            f.push(measured(&l, v("21.5", -82, "rx"), 10_200)).unwrap(),
2030            None
2031        );
2032        let b = f
2033            .push(measured(&l, v("22", -82, "tx"), 20_700))
2034            .unwrap()
2035            .expect("three records");
2036        let e = f.encode(&b, Run::U16(1));
2037        let at: Vec<_> = e.frame.records.iter().map(|r| r.at).collect();
2038        assert_eq!(
2039            at,
2040            vec![None, Some(At::Scheduled), Some(At::Offset(20_700))]
2041        );
2042        assert_eq!(e.frame.records[1].slots[1], Slot::Code(58));
2043        assert!(matches!(e.frame.records[1].slots[0], Slot::Omitted));
2044        f.sent(e);
2045        assert_eq!(
2046            f.push(measured(&l, v("22", -82, "tx"), 30_100)).unwrap(),
2047            None
2048        );
2049        assert_eq!(
2050            f.push(measured(&l, v("22", -82, "tx"), 39_700)).unwrap(),
2051            None
2052        );
2053        let b = f
2054            .push(measured(&l, v("22", -82, "tx"), 65_100))
2055            .unwrap()
2056            .expect("past the span");
2057        assert_eq!(b.len(), 2);
2058        let e = f.encode(&b, Run::U16(1));
2059        assert!(e.frame.records[0].full, "three records after the last full");
2060        assert_eq!(e.frame.records[1].at, Some(At::Scheduled));
2061        assert_eq!(f.open(), 1);
2062        assert_eq!(
2063            f.push(measured(&l, v("22", -82, "tx"), 65_000)),
2064            Err(WriteRefusal::Order)
2065        );
2066        assert_eq!(f.flush().map(|b| b.len()), Some(1));
2067        assert_eq!(f.flush(), None);
2068        // A slot omitted, or a code its field does not use, is refused.
2069        let mut m = measured(&l, v("22", -82, "tx"), 70_000);
2070        m.slots[0] = Slot::Omitted;
2071        assert_eq!(f.push(m), Err(WriteRefusal::Value));
2072        let mut m = measured(&l, v("22", -82, "tx"), 70_000);
2073        m.slots[0] = Slot::Code(251);
2074        assert_eq!(f.push(m), Err(WriteRefusal::Range));
2075    }
2076
2077    /// The largest frame (link.v1 §2.8): `records` full records with every
2078    /// optional field and every offset.
2079    #[test]
2080    fn the_largest_frame() {
2081        let l = Layout::of(&link(), &one()).unwrap();
2082        assert_eq!(
2083            (l.largest_body_bits(), l.largest_payload_bytes()),
2084            (106, 22)
2085        );
2086        let p = params(FrameSpec {
2087            records: Some(3),
2088            step_ms: Some(10_000),
2089            ..FrameSpec::default()
2090        });
2091        let l = Layout::of(&sample(), &p).unwrap();
2092        // 42 + 2 + 3 × (1 + 19) + 2 × (1 + 15).
2093        assert_eq!(l.largest_body_bits(), 136);
2094        let all = json!({"temperature": "85", "rssi": -20, "link_up": true, "mode": "tx"});
2095        let slots = l.slots_of_json(&all, None).unwrap();
2096        let frame = Frame {
2097            time: Some(Time { s: 1, ms: 2 }),
2098            records: (0..3)
2099                .map(|i| Record {
2100                    full: true,
2101                    at: (i > 0).then_some(At::Offset(29_999)),
2102                    slots: slots.clone(),
2103                })
2104                .collect(),
2105        };
2106        assert_eq!(frame.write(&l).unwrap().bits, l.largest_body_bits());
2107        // keyframe_every 3 (F-470): two of the three records may be delta
2108        // records that include every field, a bit per field longer.
2109        let p = params(FrameSpec {
2110            records: Some(3),
2111            step_ms: Some(10_000),
2112            keyframe_every: Some(3),
2113            ..FrameSpec::default()
2114        });
2115        let k3 = Layout::of(&sample(), &p).unwrap();
2116        assert_eq!(k3.largest_body_bits(), 136 + 2 * 4);
2117        let deltas = Frame {
2118            records: frame
2119                .records
2120                .iter()
2121                .enumerate()
2122                .map(|(i, r)| Record {
2123                    full: i == 0,
2124                    ..r.clone()
2125                })
2126                .collect(),
2127            ..frame.clone()
2128        };
2129        assert_eq!(deltas.write(&k3).unwrap().bits, k3.largest_body_bits());
2130        // One record a frame, at keyframe_every 15: that record may be a
2131        // delta, 4 bits longer than a keyframe's.
2132        let p = params(FrameSpec {
2133            keyframe_every: Some(15),
2134            ..FrameSpec::default()
2135        });
2136        let k15 = Layout::of(&link(), &p).unwrap();
2137        assert_eq!(
2138            (k15.largest_body_bits(), k15.largest_payload_bytes()),
2139            (110, 22)
2140        );
2141        // A record's bytes read into its slots as its JSON does.
2142        let record = sample().write(&all, None).unwrap();
2143        assert_eq!(l.slots_of(&record.bytes).unwrap(), slots);
2144        assert_eq!(Time::from_unix_ms(1_500, 1), Some(Time { s: 0, ms: 500 }));
2145        assert_eq!(Time::from_unix_ms(500, 1), None);
2146        assert_eq!(Time { s: 0, ms: 500 }.unix_ms(1), 1_500);
2147    }
2148
2149    #[test]
2150    fn widths() {
2151        assert_eq!(
2152            (
2153                bits_for(1),
2154                bits_for(2),
2155                bits_for(3),
2156                bits_for(256),
2157                bits_for(257)
2158            ),
2159            (0, 1, 2, 8, 9)
2160        );
2161        assert_eq!(bits_for(256 * MAX_STEP_MS), 40);
2162    }
2163}