Skip to main content

zenkey_model/descriptor/
compact.rs

1//! The compact descriptor (core §3.3, "The compact form"; #980 C5a).
2//!
3//! A descriptor's second form, in bytes: §7.5's mutation form on the
4//! instance key under `zenoh/bytes`, its record a body that names each
5//! revision by its index in the deployment catalog (§8.6) and states
6//! capabilities as bits. [`decode`] gives today's [`Descriptor`], so
7//! [`super::check_descriptor`] reads it as it reads JSON; [`encode`] writes
8//! one back. A reader reads both forms, and an owner on a first hop given
9//! a catalog writes this one (core §3.3, §8.1; C5c).
10//!
11//! The reading takes §3.3's three steps: [`Head::parse`] with no catalog and
12//! no contract, [`Head::pairs`] through the catalogs held, then the rest
13//! with each entry's revision. Every [`Refusal`] is the first, in §3.3's
14//! order, field by field. `spec/conformance/descriptors/compact/` pins
15//! them.
16
17use std::collections::{BTreeMap, BTreeSet};
18
19use thiserror::Error;
20
21use super::{Cause, Descriptor, FORMAT, InterfaceEntry, Unavailable};
22use crate::canonical::Fingerprint;
23use crate::catalog::{self, Catalog, CatalogId, ReadRefusal};
24use crate::collection::{IntegerRefusal, read_integer, write_integer};
25use crate::contract::Contract;
26use crate::grammar::{Addr, IfaceId, InstanceId};
27use crate::packed::BitWriter;
28use crate::wire::{Form, Header, Run, Seq, Stamp, Tag};
29
30/// The most entries a compact descriptor lists: its count is 4 bits.
31pub const MAX_ENTRIES: usize = 15;
32
33/// The most items an unavailable or a cardinality list holds: its count
34/// is 8 bits.
35pub const MAX_ITEMS: usize = 255;
36
37/// An entry's bits: its index (10) and its four flags.
38pub const ENTRY_BITS: u32 = 14;
39
40/// An entry's index: 10 bits, as an owner heartbeat's group's (§7.5).
41pub const INDEX_BITS: u32 = 10;
42
43/// The zid: 128 bits.
44pub const ZID_BITS: u32 = 128;
45
46/// The profile a set `minted` bit lists: today's one derivation-only
47/// profile (core §10).
48pub const MINTED_PROFILE: &str = "hostid.v1";
49
50/// A compact descriptor's value: the descriptor it decodes to, its
51/// envelope's seq (the instance's as-of mark when it put it, core §5.1) and
52/// its `minted` bit. The bytes write back from these three (§3.3,
53/// "Writing").
54#[derive(Debug, Clone, PartialEq)]
55pub struct Compact {
56    pub descriptor: Descriptor,
57    pub seq: Seq,
58    /// The instance's system is minted, so it follows `hostid.v1`: its
59    /// decoded `profiles` list it. A revision that lists `hostid.v1` in
60    /// `uses` puts it there either way, so only the bit says which.
61    pub minted: bool,
62}
63
64/// One entry as the head writes it: the revision's index and the four bits.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct EntryBits {
67    pub index: u16,
68    pub token: bool,
69    pub standby: bool,
70    /// The entry's unavailable list follows.
71    pub has_unav: bool,
72    /// The entry's cardinality list follows.
73    pub has_card: bool,
74}
75
76/// What a compact descriptor's head holds (§3.3 "Reading", step 1): what
77/// a reader reads with no catalog and no contract.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct Head {
80    /// The envelope's run and seq.
81    pub stamp: Stamp,
82    /// The catalog the instance writes under.
83    pub catalog: CatalogId,
84    pub minted: bool,
85    /// The zid follows.
86    pub has_zid: bool,
87    /// From 1 to 15, ordered by index, an index possibly twice.
88    pub entries: Vec<EntryBits>,
89}
90
91/// Why a reader refuses a compact descriptor (core §3.3, "Reading"), in
92/// the text's order.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
94pub enum Refusal {
95    /// No byte, or the bytes end before a field.
96    #[error("short: the bytes end before a field")]
97    Short,
98    /// CH's form is not 0, or its tag is not 0.
99    #[error("form: CH is not a mutation's with the tag 0")]
100    Form,
101    /// A count of 0: of entries, or of a list's items.
102    #[error("count: a count of 0")]
103    Count,
104    /// An extension bit is 1.
105    #[error("extension: an extension bit is 1")]
106    Extension,
107    /// An entry's index below the one before it, or a list's resource not
108    /// above the one before it.
109    #[error("order: an index or a resource out of order")]
110    Order,
111    /// No held catalog is the one named, or succeeds it (core §8.6).
112    #[error("unknown_catalog: no held catalog is or succeeds the one named")]
113    UnknownCatalog,
114    /// An index at or above the count read through (core §8.6).
115    #[error("unknown_index: an index at or above the count read through")]
116    UnknownIndex,
117    /// No held revision of the pair an index names.
118    #[error("unknown_revision: no held revision of the pair an index names")]
119    UnknownRevision,
120    /// A capability's bit not the one an earlier bitmap holds for it.
121    #[error("capability: two bitmaps disagree on a capability")]
122    Capability,
123    /// A resource at or above its revision's count of resources.
124    #[error("resource: a resource past its revision's")]
125    Resource,
126    /// A cause of 0.
127    #[error("cause: a cause of 0")]
128    Cause,
129    /// A bound refused as a snapshot's integer is (core §7.5).
130    #[error("leb128: a bound that is not LEB128 in its shortest form, at most 2^32 − 1")]
131    Leb128,
132    /// A byte after the pad.
133    #[error("trailing: a byte after the pad")]
134    Trailing,
135    /// A pad bit is 1.
136    #[error("pad: a pad bit is 1")]
137    Pad,
138}
139
140impl Refusal {
141    /// The fixtures' token.
142    #[must_use]
143    pub fn token(self) -> &'static str {
144        match self {
145            Self::Short => "short",
146            Self::Form => "form",
147            Self::Count => "count",
148            Self::Extension => "extension",
149            Self::Order => "order",
150            Self::UnknownCatalog => "unknown_catalog",
151            Self::UnknownIndex => "unknown_index",
152            Self::UnknownRevision => "unknown_revision",
153            Self::Capability => "capability",
154            Self::Resource => "resource",
155            Self::Cause => "cause",
156            Self::Leb128 => "leb128",
157            Self::Trailing => "trailing",
158            Self::Pad => "pad",
159        }
160    }
161}
162
163impl From<ReadRefusal> for Refusal {
164    fn from(r: ReadRefusal) -> Self {
165        match r {
166            ReadRefusal::UnknownCatalog => Self::UnknownCatalog,
167            ReadRefusal::UnknownIndex => Self::UnknownIndex,
168        }
169    }
170}
171
172/// Why a descriptor has no compact form (core §3.3, "Which descriptors
173/// have one"): its owner writes it as JSON.
174#[derive(Debug, Clone, PartialEq, Eq, Error)]
175pub enum EncodeError {
176    /// It states no run, or misspells it (D002).
177    #[error("no run: the envelope needs one")]
178    Run,
179    /// It names no catalog, or misspells its id (D002).
180    #[error("no catalog: an index needs one")]
181    Catalog,
182    /// No catalog held is the one it names, or succeeds it.
183    #[error("the catalog it names is not held: {0}")]
184    Unheld(ReadRefusal),
185    /// It lists no interface, or more than [`MAX_ENTRIES`].
186    #[error("{0} interfaces: a compact descriptor lists from 1 to 15")]
187    Count(usize),
188    /// It lists a requirement.
189    #[error("a requirement: no catalog indexes a binding")]
190    Requires,
191    /// An entry's revision is not among those the catalog lists.
192    #[error("{iface} {contract}: not in the catalog it names")]
193    Uncatalogued { iface: String, contract: String },
194    /// No revision given is the entry's.
195    #[error("{iface} {contract}: its revision is not held")]
196    Revision { iface: String, contract: String },
197    /// An unavailable resource or a cardinality key that names no resource
198    /// of the entry's revision.
199    #[error("{iface}: {resource:?} is not one of its resources")]
200    Resource { iface: String, resource: String },
201    /// One entry's unavailable list names a resource twice.
202    #[error("{iface}: {resource:?} is listed unavailable twice")]
203    Twice { iface: String, resource: String },
204    /// A list of more than [`MAX_ITEMS`].
205    #[error("{iface}: a list of {items} items, above 255")]
206    Items { iface: String, items: usize },
207    /// A bound above 2^32 − 1.
208    #[error("{iface}: the bound {bound} is above 2^32 − 1")]
209    Bound { iface: String, bound: u64 },
210    /// A `meta.zid` that is not 1 to 32 lowercase hex digits.
211    #[error("meta.zid {0} is not 1 to 32 lowercase hex digits")]
212    Zid(String),
213}
214
215/// The capabilities a revision gates on (core §3.3, "The bitmaps"): each
216/// `<n>` of a `capability:<n>` gate among its resources, once, sorted as
217/// strings, bytewise.
218#[must_use]
219pub fn gated(revision: &Contract) -> Vec<String> {
220    let caps: BTreeSet<&str> = revision
221        .resources
222        .iter()
223        .flat_map(|r| r.gate.iter())
224        .filter_map(|g| g.strip_prefix("capability:"))
225        .collect();
226    caps.into_iter().map(str::to_owned).collect()
227}
228
229/// The bits a revision writes a resource in (core §3.3, "A resource"):
230/// ⌈log₂ n⌉ for n resources, none where n is 0 or 1.
231#[must_use]
232pub fn resource_bits(revision: &Contract) -> u32 {
233    let n = revision.resources.len();
234    if n <= 1 {
235        0
236    } else {
237        usize::BITS - (n - 1).leading_zeros()
238    }
239}
240
241/// A revision's resources by name, `<kind token>/<template>`, in the
242/// canonical form's order (core §9.5): an item's resource is its place here.
243#[must_use]
244pub fn resource_names(revision: &Contract) -> Vec<String> {
245    revision
246        .resources
247        .iter()
248        .map(|r| format!("{}/{}", r.token.as_str(), r.template))
249        .collect()
250}
251
252/// The code §7.5's error byte gives a cause: 1 build, 2 config, 3
253/// capability.
254fn cause_code(c: Cause) -> u64 {
255    match c {
256        Cause::Build => 1,
257        Cause::Config => 2,
258        Cause::Capability => 3,
259    }
260}
261
262fn cause_of(code: u64) -> Option<Cause> {
263    match code {
264        1 => Some(Cause::Build),
265        2 => Some(Cause::Config),
266        3 => Some(Cause::Capability),
267        _ => None,
268    }
269}
270
271/// The revisions held, each with its fingerprint, computed once.
272struct Held<'c>(Vec<(Fingerprint, &'c Contract)>);
273
274impl<'c> Held<'c> {
275    fn new(revisions: &[&'c Contract]) -> Self {
276        Held(revisions.iter().map(|c| (Fingerprint::of(c), *c)).collect())
277    }
278
279    fn of(&self, e: &catalog::Entry) -> Option<&'c Contract> {
280        self.0
281            .iter()
282            .find(|(fp, c)| *fp == e.contract && c.iface == e.iface)
283            .map(|(_, c)| *c)
284    }
285}
286
287/// Bits read in order, `short` where they end.
288struct Bits<'a> {
289    bytes: &'a [u8],
290    pos: u64,
291}
292
293impl<'a> Bits<'a> {
294    fn new(bytes: &'a [u8]) -> Self {
295        Bits { bytes, pos: 0 }
296    }
297
298    fn left(&self) -> u64 {
299        self.bytes.len() as u64 * 8 - self.pos
300    }
301
302    fn take(&mut self, width: u32) -> Result<u64, Refusal> {
303        debug_assert!(width <= 64);
304        if u64::from(width) > self.left() {
305            return Err(Refusal::Short);
306        }
307        let mut v = 0u64;
308        for _ in 0..width {
309            let b = (self.bytes[(self.pos / 8) as usize] >> (7 - self.pos % 8)) & 1;
310            v = (v << 1) | u64::from(b);
311            self.pos += 1;
312        }
313        Ok(v)
314    }
315
316    fn bit(&mut self) -> Result<bool, Refusal> {
317        self.take(1).map(|b| b == 1)
318    }
319
320    /// §7.5's integer, each byte the next 8 bits wherever they fall.
321    fn integer(&mut self) -> Result<u32, Refusal> {
322        read_integer(|| self.take(8).ok().map(|b| b as u8)).map_err(|e| match e {
323            IntegerRefusal::Short => Refusal::Short,
324            IntegerRefusal::Leb128 => Refusal::Leb128,
325        })
326    }
327
328    /// No byte after the pad (`trailing`), then every pad bit 0 (`pad`).
329    fn end(mut self) -> Result<(), Refusal> {
330        if self.bytes.len() as u64 != self.pos.div_ceil(8) {
331            return Err(Refusal::Trailing);
332        }
333        while self.left() > 0 {
334            if self.bit()? {
335                return Err(Refusal::Pad);
336            }
337        }
338        Ok(())
339    }
340}
341
342impl Head {
343    /// The head (§3.3 "Reading", step 1), with no catalog and no contract:
344    /// the refusals `short`, `form`, `count`, `extension` and `order`, the
345    /// first that applies.
346    ///
347    /// # Errors
348    /// The refusal.
349    pub fn parse(bytes: &[u8]) -> Result<Head, Refusal> {
350        Self::read(bytes).map(|(h, _)| h)
351    }
352
353    /// The head and the bits after it.
354    fn read(bytes: &[u8]) -> Result<(Head, Bits<'_>), Refusal> {
355        let ch = *bytes.first().ok_or(Refusal::Short)?;
356        let header = Header::from_byte(ch);
357        if header.form != Form::Mutation || header.tag != Tag::NONE {
358            return Err(Refusal::Form);
359        }
360        let run_bytes = if header.wide { 4 } else { 2 };
361        // CH, the run, the seq, the catalog id and the flags.
362        if bytes.len() < 1 + run_bytes + 3 + 4 + 1 {
363            return Err(Refusal::Short);
364        }
365        let run = if header.wide {
366            Run::U32(u32::from_be_bytes(bytes[1..5].try_into().expect("4 bytes")))
367        } else {
368            Run::U16(u16::from_be_bytes(bytes[1..3].try_into().expect("2 bytes")))
369        };
370        let at = 1 + run_bytes;
371        let seq = Seq::new(
372            (u32::from(bytes[at]) << 16)
373                | (u32::from(bytes[at + 1]) << 8)
374                | u32::from(bytes[at + 2]),
375        )
376        .expect("24 bits");
377        let mut r = Bits::new(&bytes[at + 3..]);
378        let id = u32::try_from(r.take(32)?).expect("32 bits");
379        let catalog = CatalogId::from_hex(&format!("{id:08x}")).expect("8 hex digits");
380        let count = r.take(4)?;
381        if count == 0 {
382            return Err(Refusal::Count);
383        }
384        let minted = r.bit()?;
385        let has_zid = r.bit()?;
386        if r.take(2)? != 0 {
387            return Err(Refusal::Extension);
388        }
389        let mut entries: Vec<EntryBits> = Vec::new();
390        for _ in 0..count {
391            if r.left() < u64::from(ENTRY_BITS) {
392                return Err(Refusal::Short);
393            }
394            let index = u16::try_from(r.take(INDEX_BITS)?).expect("10 bits");
395            if entries.last().is_some_and(|e| index < e.index) {
396                return Err(Refusal::Order);
397            }
398            entries.push(EntryBits {
399                index,
400                token: r.bit()?,
401                standby: r.bit()?,
402                has_unav: r.bit()?,
403                has_card: r.bit()?,
404            });
405        }
406        Ok((
407            Head {
408                stamp: Stamp { run, seq },
409                catalog,
410                minted,
411                has_zid,
412                entries,
413            },
414            r,
415        ))
416    }
417
418    /// The pair each entry's index names, read through the catalogs held
419    /// (§3.3 "Reading", step 2, without the revisions): what a reader
420    /// retrieves before it reads the rest (core §8.4).
421    ///
422    /// # Errors
423    /// `unknown_catalog`, then `unknown_index` for the first entry whose
424    /// index the catalog read through does not hold.
425    pub fn pairs<'h>(&self, held: &'h [Catalog]) -> Result<Vec<&'h catalog::Entry>, Refusal> {
426        let through = catalog::through(held, self.catalog)?;
427        self.entries
428            .iter()
429            .map(|e| through.entry(e.index).map_err(Refusal::from))
430            .collect()
431    }
432}
433
434/// Decodes a compact descriptor (core §3.3, "Decoding" and "Reading") that
435/// came on the instance key of `addr` and `instance`, with the catalogs
436/// and the revisions the reader holds.
437///
438/// # Errors
439/// The first refusal in §3.3's order.
440pub fn decode(
441    bytes: &[u8],
442    addr: &Addr,
443    instance: &InstanceId,
444    held: &[Catalog],
445    revisions: &[&Contract],
446) -> Result<Compact, Refusal> {
447    // 1. The head.
448    let (head, mut r) = Head::read(bytes)?;
449    // 2. The catalog: the id, then each entry's index and revision.
450    let through = catalog::through(held, head.catalog)?;
451    let held_revisions = Held::new(revisions);
452    let mut revs: Vec<(&catalog::Entry, &Contract)> = Vec::with_capacity(head.entries.len());
453    for e in &head.entries {
454        let pair = through.entry(e.index)?;
455        let rev = held_revisions.of(pair).ok_or(Refusal::UnknownRevision)?;
456        revs.push((pair, rev));
457    }
458    // 3. The rest, field by field.
459    let mut bits: BTreeMap<String, bool> = BTreeMap::new();
460    for (_, rev) in &revs {
461        for cap in gated(rev) {
462            let b = r.bit()?;
463            if bits.get(&cap).is_some_and(|held| *held != b) {
464                return Err(Refusal::Capability);
465            }
466            bits.insert(cap, b);
467        }
468    }
469    let mut unavailable: Vec<Vec<Unavailable>> = vec![Vec::new(); revs.len()];
470    for (i, (e, (_, rev))) in head.entries.iter().zip(&revs).enumerate() {
471        if !e.has_unav {
472            continue;
473        }
474        let names = resource_names(rev);
475        let mut last = None;
476        for _ in 0..list_count(&mut r)? {
477            let k = item_resource(&mut r, rev, &mut last)?;
478            let cause = cause_of(r.take(2)?).ok_or(Refusal::Cause)?;
479            unavailable[i].push(Unavailable {
480                resource: names[k].clone(),
481                cause,
482                reason: None,
483            });
484        }
485    }
486    let mut cardinality: Vec<BTreeMap<String, u64>> = vec![BTreeMap::new(); revs.len()];
487    for (i, (e, (_, rev))) in head.entries.iter().zip(&revs).enumerate() {
488        if !e.has_card {
489            continue;
490        }
491        let names = resource_names(rev);
492        let mut last = None;
493        for _ in 0..list_count(&mut r)? {
494            let k = item_resource(&mut r, rev, &mut last)?;
495            let bound = r.integer()?;
496            cardinality[i].insert(names[k].clone(), u64::from(bound));
497        }
498    }
499    let zid = if head.has_zid {
500        let hi = u128::from(r.take(64)?);
501        let lo = u128::from(r.take(64)?);
502        Some((hi << 64) | lo)
503    } else {
504        None
505    };
506    r.end()?;
507
508    // The descriptor.
509    let interfaces = head
510        .entries
511        .iter()
512        .zip(&revs)
513        .zip(unavailable.into_iter().zip(cardinality))
514        .map(
515            |((e, (pair, _)), (unavailable, cardinality))| InterfaceEntry {
516                iface: pair.iface.to_string(),
517                contract: pair.contract.to_string(),
518                minor: None,
519                standby: e.standby,
520                token: e.token,
521                unavailable,
522                cardinality,
523            },
524        )
525        .collect();
526    let capabilities = bits
527        .into_iter()
528        .filter(|(_, held)| *held)
529        .map(|(cap, _)| cap)
530        .collect();
531    let mut profiles: BTreeSet<IfaceId> = revs
532        .iter()
533        .flat_map(|(_, rev)| rev.uses.iter().cloned())
534        .collect();
535    if head.minted {
536        profiles.insert(MINTED_PROFILE.parse().expect("an interface id"));
537    }
538    let mut meta = BTreeMap::new();
539    if let Some(zid) = zid {
540        meta.insert(
541            "zid".to_owned(),
542            serde_json::Value::String(format!("{zid:x}")),
543        );
544    }
545    Ok(Compact {
546        descriptor: Descriptor {
547            format: FORMAT.to_owned(),
548            service: addr.to_string(),
549            instance: instance.to_string(),
550            run: Some(head.stamp.run.hex()),
551            catalog: Some(head.catalog.hex()),
552            interfaces,
553            capabilities,
554            requires: Vec::new(),
555            profiles: profiles.iter().map(ToString::to_string).collect(),
556            meta,
557        },
558        seq: head.stamp.seq,
559        minted: head.minted,
560    })
561}
562
563/// A list's count of items: `count` at 0.
564fn list_count(r: &mut Bits<'_>) -> Result<u64, Refusal> {
565    match r.take(8)? {
566        0 => Err(Refusal::Count),
567        n => Ok(n),
568    }
569}
570
571/// An item's resource: `resource` past its revision's, then `order` where
572/// not above the one before it in its list.
573fn item_resource(
574    r: &mut Bits<'_>,
575    rev: &Contract,
576    last: &mut Option<u64>,
577) -> Result<usize, Refusal> {
578    let k = r.take(resource_bits(rev))?;
579    if k >= rev.resources.len() as u64 {
580        return Err(Refusal::Resource);
581    }
582    if last.is_some_and(|l| k <= l) {
583        return Err(Refusal::Order);
584    }
585    *last = Some(k);
586    Ok(usize::try_from(k).expect("below the count of resources"))
587}
588
589/// Writes a descriptor's compact form (core §3.3, "The layout" and
590/// "Writing"), with the catalogs its owner holds and the revisions it
591/// implements: the entries ordered by index (an index twice in the order
592/// given), each list's items by resource, every bit of one capability
593/// alike. Its `minor`, `profiles`, each `reason`, `meta` but its `zid`,
594/// and a capability no listed revision gates on are left out.
595///
596/// # Errors
597/// Why the descriptor has no compact form.
598pub fn encode(
599    c: &Compact,
600    held: &[Catalog],
601    revisions: &[&Contract],
602) -> Result<Vec<u8>, EncodeError> {
603    let d = &c.descriptor;
604    let run = d.stated_run().ok_or(EncodeError::Run)?;
605    let id = d.stated_catalog().ok_or(EncodeError::Catalog)?;
606    let through = catalog::through(held, id).map_err(EncodeError::Unheld)?;
607    if d.interfaces.is_empty() || d.interfaces.len() > MAX_ENTRIES {
608        return Err(EncodeError::Count(d.interfaces.len()));
609    }
610    if !d.requires.is_empty() {
611        return Err(EncodeError::Requires);
612    }
613    let zid = match d.meta.get("zid") {
614        None => None,
615        Some(v) => {
616            let text = v.as_str().unwrap_or_default();
617            let ok = (1..=32).contains(&text.len())
618                && text
619                    .bytes()
620                    .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
621            if !ok {
622                return Err(EncodeError::Zid(v.to_string()));
623            }
624            Some(u128::from_str_radix(text, 16).expect("hex digits"))
625        }
626    };
627    let held_revisions = Held::new(revisions);
628    // Each entry's index and revision, then the entries by index.
629    let mut entries = Vec::with_capacity(d.interfaces.len());
630    for e in &d.interfaces {
631        let iface: Option<IfaceId> = e.iface.parse().ok();
632        let contract = Fingerprint::parse(&e.contract).ok();
633        let index = iface.zip(contract).and_then(|(iface, contract)| {
634            through.catalog().entries()[..usize::from(through.count())]
635                .iter()
636                .position(|x| x.iface == iface && x.contract == contract)
637        });
638        let Some(index) = index else {
639            return Err(EncodeError::Uncatalogued {
640                iface: e.iface.clone(),
641                contract: e.contract.clone(),
642            });
643        };
644        let pair = &through.catalog().entries()[index];
645        let rev = held_revisions
646            .of(pair)
647            .ok_or_else(|| EncodeError::Revision {
648                iface: e.iface.clone(),
649                contract: e.contract.clone(),
650            })?;
651        entries.push((u16::try_from(index).expect("at most 1,024 entries"), e, rev));
652    }
653    entries.sort_by_key(|(index, _, _)| *index);
654
655    let mut w = BitWriter::new();
656    w.push(u64::from(u32::from_be_bytes(id.bytes())), 32);
657    w.push(entries.len() as u64, 4);
658    w.bit(c.minted);
659    w.bit(zid.is_some());
660    w.push(0, 2);
661    for (index, e, _) in &entries {
662        w.push(u64::from(*index), INDEX_BITS);
663        w.bit(e.token);
664        w.bit(e.standby);
665        w.bit(!e.unavailable.is_empty());
666        w.bit(!e.cardinality.is_empty());
667    }
668    for (_, _, rev) in &entries {
669        for cap in gated(rev) {
670            w.bit(d.capabilities.contains(&cap));
671        }
672    }
673    for (_, e, rev) in &entries {
674        if e.unavailable.is_empty() {
675            continue;
676        }
677        let names = resource_names(rev);
678        let mut items = Vec::with_capacity(e.unavailable.len());
679        for u in &e.unavailable {
680            let k = place(&names, &e.iface, &u.resource)?;
681            items.push((k, cause_code(u.cause)));
682        }
683        items.sort_unstable();
684        if let Some(w) = items.windows(2).find(|w| w[0].0 == w[1].0) {
685            return Err(EncodeError::Twice {
686                iface: e.iface.clone(),
687                resource: names[w[0].0].clone(),
688            });
689        }
690        list(&mut w, &e.iface, items.len())?;
691        for (k, cause) in items {
692            w.push(k as u64, resource_bits(rev));
693            w.push(cause, 2);
694        }
695    }
696    for (_, e, rev) in &entries {
697        if e.cardinality.is_empty() {
698            continue;
699        }
700        let names = resource_names(rev);
701        let mut items = Vec::with_capacity(e.cardinality.len());
702        for (name, bound) in &e.cardinality {
703            let k = place(&names, &e.iface, name)?;
704            let bound = u32::try_from(*bound).map_err(|_| EncodeError::Bound {
705                iface: e.iface.clone(),
706                bound: *bound,
707            })?;
708            items.push((k, bound));
709        }
710        items.sort_unstable();
711        list(&mut w, &e.iface, items.len())?;
712        for (k, bound) in items {
713            w.push(k as u64, resource_bits(rev));
714            let mut leb = Vec::with_capacity(5);
715            write_integer(&mut leb, bound);
716            for b in leb {
717                w.push(u64::from(b), 8);
718            }
719        }
720    }
721    if let Some(zid) = zid {
722        w.push((zid >> 64) as u64, 64);
723        w.push(zid as u64, 64);
724    }
725    let body = w.finish();
726    let stamp = Stamp { run, seq: c.seq };
727    let header = Header {
728        form: Form::Mutation,
729        wide: run.is_wide(),
730        tag: Tag::NONE,
731    };
732    let mut out = Vec::with_capacity(stamp.envelope_bytes() + body.bytes.len());
733    out.push(header.byte());
734    stamp.write_to(&mut out);
735    out.extend_from_slice(&body.bytes);
736    Ok(out)
737}
738
739/// A resource's place in its revision.
740fn place(names: &[String], iface: &str, resource: &str) -> Result<usize, EncodeError> {
741    names
742        .iter()
743        .position(|n| n == resource)
744        .ok_or_else(|| EncodeError::Resource {
745            iface: iface.to_owned(),
746            resource: resource.to_owned(),
747        })
748}
749
750/// A list's count, at most [`MAX_ITEMS`].
751fn list(w: &mut BitWriter, iface: &str, items: usize) -> Result<(), EncodeError> {
752    if items > MAX_ITEMS {
753        return Err(EncodeError::Items {
754            iface: iface.to_owned(),
755            items,
756        });
757    }
758    w.push(items as u64, 8);
759    Ok(())
760}
761
762#[cfg(test)]
763mod tests {
764    use super::*;
765
766    fn contract(toml: &str) -> Contract {
767        let l = crate::contract::load_str(toml, std::path::Path::new("."), None);
768        l.contract.unwrap_or_else(|| panic!("{}", l.report))
769    }
770
771    /// ⌈log₂ n⌉ bits for n resources, none for one or none.
772    #[test]
773    fn a_resource_takes_the_fewest_bits_that_hold_every_index() {
774        let res = |n: usize| -> String {
775            (0..n)
776                .map(|i| {
777                    format!(
778                        "[resources.r{i}]\nkind = \"state\"\ntype = {{ raw = \"text/plain\" }}\n"
779                    )
780                })
781                .collect()
782        };
783        for (n, bits) in [
784            (1, 0),
785            (2, 1),
786            (3, 2),
787            (4, 2),
788            (5, 3),
789            (8, 3),
790            (9, 4),
791            (108, 7),
792            (128, 7),
793            (129, 8),
794        ] {
795            let c = contract(&format!(
796                "[interface]\nname = \"t\"\nmajor = 1\nminor = 0\n{}",
797                res(n)
798            ));
799            assert_eq!(resource_bits(&c), bits, "{n} resources");
800        }
801    }
802
803    /// The writer's own refusals: no run, no catalog, a requirement, no
804    /// interface, an uncatalogued revision, a resource that is none of the
805    /// revision's, a bound above 2^32 − 1 and a malformed zid.
806    #[test]
807    fn a_descriptor_without_a_compact_form_is_refused_by_the_writer() {
808        let c = contract(
809            "[interface]\nname = \"t\"\nmajor = 1\nminor = 0\n\
810             [resources.\"a/{x}\"]\nkind = \"state\"\ntype = { raw = \"text/plain\" }\n\
811             params = { x = \"string\" }\ncardinality = 9\n",
812        );
813        let mut catalog = Catalog::new(0).unwrap();
814        catalog.push(c.iface.clone(), Fingerprint::of(&c)).unwrap();
815        let held = [catalog];
816        let fp = Fingerprint::of(&c).to_string();
817        let base = Compact {
818            descriptor: serde_json::from_str(&format!(
819                r#"{{"format": "zk2-descriptor/0.1", "service": "s/t", "instance": "000000000000000a",
820                    "run": "0001", "catalog": "{}", "interfaces": [{{"iface": "t.v1", "contract": "{fp}"}}]}}"#,
821                held[0].id()
822            ))
823            .unwrap(),
824            seq: Seq::default(),
825            minted: false,
826        };
827        let bytes = encode(&base, &held, &[&c]).unwrap();
828        let addr = Addr::new("s", "t").unwrap();
829        let instance: InstanceId = "000000000000000a".parse().unwrap();
830        assert_eq!(
831            decode(&bytes, &addr, &instance, &held, &[&c]).unwrap(),
832            base
833        );
834
835        let refused = |f: &dyn Fn(&mut Compact)| {
836            let mut v = base.clone();
837            f(&mut v);
838            encode(&v, &held, &[&c]).unwrap_err()
839        };
840        assert_eq!(refused(&|v| v.descriptor.run = None), EncodeError::Run);
841        assert_eq!(
842            refused(&|v| v.descriptor.catalog = None),
843            EncodeError::Catalog
844        );
845        assert!(matches!(
846            refused(&|v| v.descriptor.catalog = Some("00000000".into())),
847            EncodeError::Unheld(ReadRefusal::UnknownCatalog)
848        ));
849        assert_eq!(
850            refused(&|v| v.descriptor.interfaces.clear()),
851            EncodeError::Count(0)
852        );
853        assert_eq!(
854            refused(&|v| {
855                let e = v.descriptor.interfaces[0].clone();
856                v.descriptor.interfaces = vec![e; 16];
857            }),
858            EncodeError::Count(16)
859        );
860        assert_eq!(
861            refused(&|v| v.descriptor.requires =
862                serde_json::from_str(r#"[{"role": "r", "interface": "u.v1", "bindings": []}]"#)
863                    .unwrap()),
864            EncodeError::Requires
865        );
866        assert!(matches!(
867            refused(&|v| v.descriptor.interfaces[0].iface = "u.v1".into()),
868            EncodeError::Uncatalogued { .. }
869        ));
870        assert!(matches!(
871            encode(&base, &held, &[]).unwrap_err(),
872            EncodeError::Revision { .. }
873        ));
874        assert!(matches!(
875            refused(&|v| {
876                v.descriptor.interfaces[0]
877                    .cardinality
878                    .insert("state/b/{x}".into(), 1);
879            }),
880            EncodeError::Resource { .. }
881        ));
882        assert!(matches!(
883            refused(&|v| {
884                v.descriptor.interfaces[0]
885                    .cardinality
886                    .insert("state/a/{x}".into(), 1 << 32);
887            }),
888            EncodeError::Bound { .. }
889        ));
890        for zid in ["", "0A", &"1".repeat(33), "x"] {
891            assert!(matches!(
892                refused(&|v| {
893                    v.descriptor.meta.insert("zid".into(), zid.into());
894                }),
895                EncodeError::Zid(_)
896            ));
897        }
898    }
899}