capsule_core/sidecar/shape.rs
1//! Tell a signed sidecar from anything else **without reading it**.
2//!
3//! The signed [`SidecarV1`](crate::sidecar::SidecarV1) carries its schema version at CBOR
4//! integer key `0`. A probe that looks at nothing but that key classifies a file, and it
5//! builds no model of the shape — which is what keeps it from being a second reader beside
6//! the signed one. Every other byte string, including the retired unsigned pre-signed-path
7//! record (text keys only, no key `0`), is [`SidecarShape::Unknown`]: no reader of that
8//! record's contents remains anywhere.
9
10use ciborium::value::Value;
11
12/// Which on-disk sidecar shape a `{uuid}.cbor` file has.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum SidecarShape {
15 /// A signed `SidecarV1`-family record: integer key `0` is present and carries `schema`.
16 /// Says nothing about whether the schema is one this build reads.
17 Signed {
18 /// The value at integer key `0`.
19 schema: u16,
20 },
21 /// Not a signed sidecar: not CBOR, not a map, a map without integer key `0` (the
22 /// retired unsigned pre-signed-path record among them), or a key `0` that is not a `u16`.
23 Unknown,
24}
25
26/// Classify sidecar bytes by their discriminating key alone.
27///
28/// Decodes the outer CBOR value once and inspects only the map's keys; every value except
29/// the one at integer key `0` is left unexamined. Never fails: undecodable bytes are
30/// [`SidecarShape::Unknown`], and so is a `0` key whose value is not a `u16`.
31pub fn probe(bytes: &[u8]) -> SidecarShape {
32 let Ok(Value::Map(entries)) = ciborium::de::from_reader::<Value, _>(bytes) else {
33 return SidecarShape::Unknown;
34 };
35 let schema_key = entries
36 .iter()
37 .find(|(key, _)| matches!(key, Value::Integer(i) if i128::from(*i) == 0));
38 match schema_key {
39 Some((_, Value::Integer(v))) => u16::try_from(i128::from(*v))
40 .map_or(SidecarShape::Unknown, |schema| SidecarShape::Signed {
41 schema,
42 }),
43 _ => SidecarShape::Unknown,
44 }
45}
46
47#[cfg(test)]
48mod tests;