1use 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
30pub const MAX_ENTRIES: usize = 15;
32
33pub const MAX_ITEMS: usize = 255;
36
37pub const ENTRY_BITS: u32 = 14;
39
40pub const INDEX_BITS: u32 = 10;
42
43pub const ZID_BITS: u32 = 128;
45
46pub const MINTED_PROFILE: &str = "hostid.v1";
49
50#[derive(Debug, Clone, PartialEq)]
55pub struct Compact {
56 pub descriptor: Descriptor,
57 pub seq: Seq,
58 pub minted: bool,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct EntryBits {
67 pub index: u16,
68 pub token: bool,
69 pub standby: bool,
70 pub has_unav: bool,
72 pub has_card: bool,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct Head {
80 pub stamp: Stamp,
82 pub catalog: CatalogId,
84 pub minted: bool,
85 pub has_zid: bool,
87 pub entries: Vec<EntryBits>,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
94pub enum Refusal {
95 #[error("short: the bytes end before a field")]
97 Short,
98 #[error("form: CH is not a mutation's with the tag 0")]
100 Form,
101 #[error("count: a count of 0")]
103 Count,
104 #[error("extension: an extension bit is 1")]
106 Extension,
107 #[error("order: an index or a resource out of order")]
110 Order,
111 #[error("unknown_catalog: no held catalog is or succeeds the one named")]
113 UnknownCatalog,
114 #[error("unknown_index: an index at or above the count read through")]
116 UnknownIndex,
117 #[error("unknown_revision: no held revision of the pair an index names")]
119 UnknownRevision,
120 #[error("capability: two bitmaps disagree on a capability")]
122 Capability,
123 #[error("resource: a resource past its revision's")]
125 Resource,
126 #[error("cause: a cause of 0")]
128 Cause,
129 #[error("leb128: a bound that is not LEB128 in its shortest form, at most 2^32 − 1")]
131 Leb128,
132 #[error("trailing: a byte after the pad")]
134 Trailing,
135 #[error("pad: a pad bit is 1")]
137 Pad,
138}
139
140impl Refusal {
141 #[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#[derive(Debug, Clone, PartialEq, Eq, Error)]
175pub enum EncodeError {
176 #[error("no run: the envelope needs one")]
178 Run,
179 #[error("no catalog: an index needs one")]
181 Catalog,
182 #[error("the catalog it names is not held: {0}")]
184 Unheld(ReadRefusal),
185 #[error("{0} interfaces: a compact descriptor lists from 1 to 15")]
187 Count(usize),
188 #[error("a requirement: no catalog indexes a binding")]
190 Requires,
191 #[error("{iface} {contract}: not in the catalog it names")]
193 Uncatalogued { iface: String, contract: String },
194 #[error("{iface} {contract}: its revision is not held")]
196 Revision { iface: String, contract: String },
197 #[error("{iface}: {resource:?} is not one of its resources")]
200 Resource { iface: String, resource: String },
201 #[error("{iface}: {resource:?} is listed unavailable twice")]
203 Twice { iface: String, resource: String },
204 #[error("{iface}: a list of {items} items, above 255")]
206 Items { iface: String, items: usize },
207 #[error("{iface}: the bound {bound} is above 2^32 − 1")]
209 Bound { iface: String, bound: u64 },
210 #[error("meta.zid {0} is not 1 to 32 lowercase hex digits")]
212 Zid(String),
213}
214
215#[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#[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#[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
252fn 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
271struct 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
287struct 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 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 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 pub fn parse(bytes: &[u8]) -> Result<Head, Refusal> {
350 Self::read(bytes).map(|(h, _)| h)
351 }
352
353 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 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 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
434pub fn decode(
441 bytes: &[u8],
442 addr: &Addr,
443 instance: &InstanceId,
444 held: &[Catalog],
445 revisions: &[&Contract],
446) -> Result<Compact, Refusal> {
447 let (head, mut r) = Head::read(bytes)?;
449 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 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 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
563fn 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
571fn 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
589pub 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 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
739fn 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
750fn 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 #[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 #[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}