1use std::collections::{BTreeMap, BTreeSet};
21use std::fmt::Write as _;
22
23use num_bigint::{BigInt, Sign};
24use num_integer::Integer as _;
25use num_traits::{One as _, Signed as _, ToPrimitive as _, Zero as _};
26use serde_json::{Map, Value};
27use sha2::{Digest, Sha256};
28
29pub const MARKER: &str = "...";
31
32pub const FIELD_TYPES: &[&str] = &["int", "fixed", "enum", "bool", "counter", "time"];
34
35pub const RESERVED: &[&str] = &["not_available", "error", "out_of_range"];
37
38const INPUT_DIGITS: u32 = 1024;
42
43#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Decimal {
48 m: BigInt,
49 e: u32,
50}
51
52impl Decimal {
53 #[must_use]
55 pub fn parse(s: &str) -> Option<Self> {
56 let body = s.strip_prefix('-').unwrap_or(s);
57 let (int, frac) = match body.split_once('.') {
58 Some((i, f)) => (i, Some(f)),
59 None => (body, None),
60 };
61 let digits = |t: &str| !t.is_empty() && t.bytes().all(|b| b.is_ascii_digit());
62 if !digits(int) || (int.len() > 1 && int.starts_with('0')) {
63 return None;
64 }
65 if frac.is_some_and(|f| !digits(f)) {
66 return None;
67 }
68 Self::from_parts(s.starts_with('-'), int, frac.unwrap_or(""), 0)
69 }
70
71 #[must_use]
75 pub fn parse_input(s: &str) -> Option<Self> {
76 let neg = s.starts_with('-');
77 let body = s.strip_prefix('-').unwrap_or(s);
78 let (mant, exp) = match body.find(['e', 'E']) {
79 Some(i) => (&body[..i], Some(&body[i + 1..])),
80 None => (body, None),
81 };
82 let (int, frac) = match mant.split_once('.') {
83 Some((i, f)) => (i, f),
84 None => (mant, ""),
85 };
86 let digits = |t: &str| !t.is_empty() && t.bytes().all(|b| b.is_ascii_digit());
87 if !digits(int) || (int.len() > 1 && int.starts_with('0')) {
88 return None;
89 }
90 if mant.contains('.') && !digits(frac) {
91 return None;
92 }
93 let exp: i64 = match exp {
94 None => 0,
95 Some(x) => {
96 let d = x.strip_prefix(['+', '-']).unwrap_or(x);
97 if !digits(d) || d.len() > 9 {
98 return None;
99 }
100 x.parse().ok()?
101 }
102 };
103 Self::from_parts(neg, int, frac, exp)
104 }
105
106 fn from_parts(neg: bool, int: &str, frac: &str, exp: i64) -> Option<Self> {
107 let text = format!("{int}{frac}");
108 let mut m: BigInt = text.parse().ok()?;
109 let scale = i64::try_from(frac.len()).ok()? - exp;
110 let width = i64::try_from(int.len()).ok()? + exp;
111 if scale > i64::from(INPUT_DIGITS) || width > i64::from(INPUT_DIGITS) {
112 return None;
113 }
114 let e = if scale < 0 {
115 m *= pow10(u32::try_from(-scale).ok()?);
116 0
117 } else {
118 u32::try_from(scale).ok()?
119 };
120 if neg {
121 m = -m;
122 }
123 Some(Self { m, e }.normalized())
124 }
125
126 fn normalized(mut self) -> Self {
127 let ten = BigInt::from(10);
128 while self.e > 0 && (&self.m % &ten).is_zero() {
129 self.m /= &ten;
130 self.e -= 1;
131 }
132 self
133 }
134
135 fn at(&self, e: u32) -> BigInt {
137 &self.m * pow10(e - self.e)
138 }
139
140 fn sub(&self, o: &Self) -> Self {
141 let e = self.e.max(o.e);
142 Self {
143 m: self.at(e) - o.at(e),
144 e,
145 }
146 .normalized()
147 }
148
149 fn add(&self, o: &Self) -> Self {
150 let e = self.e.max(o.e);
151 Self {
152 m: self.at(e) + o.at(e),
153 e,
154 }
155 .normalized()
156 }
157
158 fn mul_int(&self, k: &BigInt) -> Self {
159 Self {
160 m: &self.m * k,
161 e: self.e,
162 }
163 .normalized()
164 }
165
166 fn is_positive(&self) -> bool {
167 self.m.is_positive()
168 }
169
170 pub(crate) fn of_i128(v: i128) -> Self {
172 Self {
173 m: BigInt::from(v),
174 e: 0,
175 }
176 }
177
178 pub(crate) fn distance(&self, o: &Self) -> Self {
181 let d = self.sub(o);
182 Self {
183 m: d.m.abs(),
184 e: d.e,
185 }
186 }
187
188 fn div_exact(&self, o: &Self) -> Option<BigInt> {
190 let e = self.e.max(o.e);
191 let (q, r) = self.at(e).div_mod_floor(&o.at(e));
192 r.is_zero().then_some(q)
193 }
194
195 fn div_round_even(&self, o: &Self) -> BigInt {
197 let e = self.e.max(o.e);
198 let d = o.at(e);
199 let (q, r) = self.at(e).div_mod_floor(&d);
200 let twice: BigInt = &r * BigInt::from(2u8);
201 let up = match twice.cmp(&d) {
202 std::cmp::Ordering::Less => false,
203 std::cmp::Ordering::Greater => true,
204 std::cmp::Ordering::Equal => q.is_odd(),
205 };
206 if up { q + BigInt::one() } else { q }
207 }
208}
209
210impl PartialOrd for Decimal {
211 fn partial_cmp(&self, o: &Self) -> Option<std::cmp::Ordering> {
212 Some(self.cmp(o))
213 }
214}
215
216impl Ord for Decimal {
217 fn cmp(&self, o: &Self) -> std::cmp::Ordering {
218 let e = self.e.max(o.e);
219 self.at(e).cmp(&o.at(e))
220 }
221}
222
223impl std::fmt::Display for Decimal {
224 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227 let n = self.clone().normalized();
228 if n.m.is_zero() {
229 return f.write_str("0");
230 }
231 let digits = n.m.abs().to_string();
232 let e = n.e as usize;
233 let sign = if n.m.sign() == Sign::Minus { "-" } else { "" };
234 if e == 0 {
235 return write!(f, "{sign}{digits}");
236 }
237 let padded = format!("{digits:0>width$}", width = e + 1);
238 let (int, frac) = padded.split_at(padded.len() - e);
239 write!(f, "{sign}{int}.{frac}")
240 }
241}
242
243impl std::str::FromStr for Decimal {
244 type Err = WriteRefusal;
245
246 fn from_str(s: &str) -> Result<Self, WriteRefusal> {
249 Self::parse_input(s).ok_or(WriteRefusal::Value)
250 }
251}
252
253impl From<i64> for Decimal {
254 fn from(v: i64) -> Self {
255 Self {
256 m: BigInt::from(v),
257 e: 0,
258 }
259 }
260}
261
262impl Decimal {
263 #[must_use]
267 pub fn from_f64(x: f64) -> Option<Self> {
268 if !x.is_finite() {
269 return None;
270 }
271 Self::parse_input(&format!("{x}"))
272 }
273
274 #[must_use]
277 pub fn to_f64(&self) -> f64 {
278 self.to_string().parse().unwrap_or(f64::NAN)
279 }
280}
281
282fn pow10(n: u32) -> BigInt {
283 num_traits::pow(BigInt::from(10), n as usize)
284}
285
286fn bits_for(codes: &BigInt) -> u64 {
288 if codes <= &BigInt::one() {
289 0
290 } else {
291 (codes - 1u32).bits()
292 }
293}
294
295#[derive(Debug, Clone, PartialEq, Eq)]
299pub struct Finding {
300 pub code: &'static str,
301 pub at: String,
304 pub message: String,
305}
306
307#[derive(Debug, Clone, PartialEq, Eq)]
309pub enum FieldKind {
310 Int {
311 minimum: i64,
312 maximum: i64,
313 reserved: Vec<&'static str>,
314 },
315 Fixed {
316 minimum: Decimal,
317 maximum: Decimal,
318 resolution: Decimal,
319 reserved: Vec<&'static str>,
320 values: u128,
322 },
323 Enum {
324 values: Vec<String>,
325 escape: bool,
326 },
327 Bool,
328 Counter,
329 Time {
330 ms: bool,
331 },
332}
333
334impl FieldKind {
335 #[must_use]
336 pub fn as_str(&self) -> &'static str {
337 match self {
338 Self::Int { .. } => "int",
339 Self::Fixed { .. } => "fixed",
340 Self::Enum { .. } => "enum",
341 Self::Bool => "bool",
342 Self::Counter => "counter",
343 Self::Time { .. } => "time",
344 }
345 }
346}
347
348#[derive(Debug, Clone, PartialEq, Eq)]
350pub struct Field {
351 pub name: String,
352 pub kind: FieldKind,
353 pub width: u32,
355 pub optional: bool,
356}
357
358#[derive(Debug, Clone, PartialEq, Eq)]
360pub enum Item {
361 Field(Field),
362 Marker,
364}
365
366#[derive(Debug, Clone, Default)]
369pub struct PackedDoc {
370 pub types: BTreeMap<String, Option<Layout>>,
372 pub findings: Vec<Finding>,
373}
374
375fn is_type_name(s: &str) -> bool {
376 let mut b = s.bytes();
377 b.next().is_some_and(|c| c.is_ascii_uppercase()) && b.all(|c| c.is_ascii_alphanumeric())
378}
379
380fn is_field_name(s: &str) -> bool {
381 let mut b = s.bytes();
382 b.next().is_some_and(|c| c.is_ascii_lowercase())
383 && b.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_')
384}
385
386fn is_value_name(s: &str) -> bool {
387 let mut b = s.bytes();
388 b.next().is_some_and(|c| c.is_ascii_alphabetic())
389 && b.all(|c| c.is_ascii_alphanumeric() || c == b'_')
390}
391
392fn members(ty: &str) -> (&'static [&'static str], &'static [&'static str]) {
395 match ty {
396 "int" => (&["minimum", "maximum", "reserved"], &["minimum", "maximum"]),
397 "fixed" => (
398 &["minimum", "maximum", "resolution", "reserved"],
399 &["minimum", "maximum", "resolution"],
400 ),
401 "enum" => (&["values", "escape", "width"], &["values"]),
402 "counter" => (&["width"], &["width"]),
403 "time" => (&["ms"], &[]),
404 _ => (&[], &[]),
405 }
406}
407
408fn field_shape(m: &Map<String, Value>, ty: &str) -> Option<String> {
410 let (takes, needs) = members(ty);
411 for k in m.keys() {
412 if !["name", "type", "optional", "description"].contains(&k.as_str())
413 && !takes.contains(&k.as_str())
414 {
415 return Some(format!("a `{ty}` field takes no member {k:?}"));
416 }
417 }
418 for k in std::iter::once(&"name").chain(needs) {
419 if !m.contains_key(*k) {
420 return Some(format!("a `{ty}` field needs `{k}`"));
421 }
422 }
423 match m.get("name") {
424 Some(Value::String(n)) if is_field_name(n) => {}
425 Some(v) => return Some(format!("`name` {v} is not [a-z][a-z0-9_]*")),
426 None => {}
427 }
428 let is_bool = |k: &str| m.get(k).is_none_or(Value::is_boolean);
429 let is_int = |k: &str| m.get(k).is_none_or(|v| v.as_i64().is_some());
430 let is_str = |k: &str| m.get(k).is_none_or(Value::is_string);
431 if !is_bool("optional") {
432 return Some("`optional` is not a boolean".into());
433 }
434 if !is_str("description") {
435 return Some("`description` is not a string".into());
436 }
437 let list_of = |k: &str, ok: &dyn Fn(&str) -> bool| match m.get(k) {
438 None => true,
439 Some(Value::Array(a)) => a.iter().all(|v| v.as_str().is_some_and(ok)),
440 Some(_) => false,
441 };
442 let problem = match ty {
443 "int" if !is_int("minimum") || !is_int("maximum") => {
444 Some("`minimum` and `maximum` are integers")
445 }
446 "fixed" if !is_str("minimum") || !is_str("maximum") || !is_str("resolution") => {
447 Some("`minimum`, `maximum` and `resolution` are decimal strings")
448 }
449 "int" | "fixed" if !list_of("reserved", &|s| RESERVED.contains(&s)) => {
450 Some("`reserved` lists not_available, error and out_of_range")
451 }
452 "enum" if !list_of("values", &is_value_name) => {
453 Some("`values` is a list of names [A-Za-z][A-Za-z0-9_]*")
454 }
455 "enum" if !is_bool("escape") => Some("`escape` is not a boolean"),
456 "enum" | "counter" if !is_int("width") => Some("`width` is not an integer"),
457 "time" if !is_bool("ms") => Some("`ms` is not a boolean"),
458 _ => None,
459 };
460 problem.map(str::to_owned)
461}
462
463fn repeats<'a>(names: impl IntoIterator<Item = &'a str>) -> Vec<&'a str> {
465 let mut seen = BTreeSet::new();
466 names.into_iter().filter(|n| !seen.insert(*n)).collect()
467}
468
469fn strings(v: Option<&Value>) -> Vec<&str> {
470 v.and_then(Value::as_array)
471 .map(|a| a.iter().filter_map(Value::as_str).collect())
472 .unwrap_or_default()
473}
474
475fn reserved_of(m: &Map<String, Value>) -> Vec<&'static str> {
476 let listed = strings(m.get("reserved"));
477 RESERVED
478 .iter()
479 .copied()
480 .filter(|r| listed.contains(r))
481 .collect()
482}
483
484fn field_of(m: &Map<String, Value>, ty: &str) -> Result<Field, (&'static str, String)> {
487 let name = m["name"].as_str().unwrap_or_default().to_owned();
488 let optional = m.get("optional").and_then(Value::as_bool).unwrap_or(false);
489 let wide = |codes: &BigInt| -> Result<u32, (&'static str, String)> {
490 let w = bits_for(codes);
491 if (1..=64).contains(&w) {
492 Ok(u32::try_from(w).unwrap_or(64))
493 } else {
494 Err((
495 "E041",
496 format!("{codes} codes need {w} bits; a field is 1 to 64"),
497 ))
498 }
499 };
500 let (kind, width) = match ty {
501 "int" => {
502 let (lo, hi) = (
503 m["minimum"].as_i64().unwrap_or(0),
504 m["maximum"].as_i64().unwrap_or(0),
505 );
506 if lo > hi {
507 return Err(("E039", format!("`minimum` {lo} is above `maximum` {hi}")));
508 }
509 let reserved = reserved_of(m);
510 let codes = BigInt::from(hi) - BigInt::from(lo) + BigInt::from(1 + reserved.len());
511 let width = wide(&codes)?;
512 (
513 FieldKind::Int {
514 minimum: lo,
515 maximum: hi,
516 reserved,
517 },
518 width,
519 )
520 }
521 "fixed" => {
522 let read = |k: &str| {
523 let s = m[k].as_str().unwrap_or_default();
524 Decimal::parse(s).ok_or_else(|| ("E040", format!("`{k}` {s:?} is not a decimal")))
525 };
526 let (lo, hi, res) = (read("minimum")?, read("maximum")?, read("resolution")?);
527 if lo > hi {
528 return Err(("E039", format!("`minimum` {lo} is above `maximum` {hi}")));
529 }
530 if !res.is_positive() {
531 return Err(("E040", format!("`resolution` {res} is not above 0")));
532 }
533 let Some(steps) = hi.sub(&lo).div_exact(&res) else {
534 return Err((
535 "E040",
536 format!("`resolution` {res} does not divide {hi} − {lo}"),
537 ));
538 };
539 let reserved = reserved_of(m);
540 let values: BigInt = steps + BigInt::one();
541 let width = wide(&(&values + BigInt::from(reserved.len())))?;
542 (
543 FieldKind::Fixed {
544 minimum: lo,
545 maximum: hi,
546 resolution: res,
547 reserved,
548 values: values.to_u128().unwrap_or(u128::MAX),
549 },
550 width,
551 )
552 }
553 "enum" => {
554 let values: Vec<String> = strings(m.get("values"))
555 .into_iter()
556 .map(str::to_owned)
557 .collect();
558 if values.is_empty() {
559 return Err(("E039", "an enum with no value".into()));
560 }
561 let escape = m.get("escape").and_then(Value::as_bool).unwrap_or(false);
562 let need = bits_for(&BigInt::from(values.len() + usize::from(escape)));
563 let width = match m.get("width").and_then(Value::as_i64) {
564 Some(w) if !(1..=64).contains(&w) || u64::try_from(w).unwrap_or(0) < need => {
565 return Err((
566 "E041",
567 format!("`width` {w}: the enum needs {need} bits, and a field is 1 to 64"),
568 ));
569 }
570 Some(w) => u32::try_from(w).unwrap_or(64),
571 None => wide(&BigInt::from(values.len() + usize::from(escape)))?,
572 };
573 (FieldKind::Enum { values, escape }, width)
574 }
575 "bool" => (FieldKind::Bool, 1),
576 "counter" => {
577 let w = m["width"].as_i64().unwrap_or(0);
578 if !(1..=64).contains(&w) {
579 return Err(("E041", format!("a counter's `width` {w} is not 1 to 64")));
580 }
581 (FieldKind::Counter, u32::try_from(w).unwrap_or(64))
582 }
583 "time" => {
584 let ms = m.get("ms").and_then(Value::as_bool).unwrap_or(false);
585 (FieldKind::Time { ms }, if ms { 42 } else { 32 })
586 }
587 _ => unreachable!("checked by E043"),
588 };
589 Ok(Field {
590 name,
591 kind,
592 width,
593 optional,
594 })
595}
596
597impl PackedDoc {
598 #[must_use]
601 #[allow(clippy::too_many_lines)]
602 pub fn read(doc: &Value) -> Self {
603 let mut findings = Vec::new();
604 let mut find = |code: &'static str, at: String, message: String| {
605 findings.push(Finding { code, at, message });
606 };
607 let Value::Object(top) = doc else {
608 find(
609 "E038",
610 String::new(),
611 "the top level is not an object".into(),
612 );
613 return Self {
614 types: BTreeMap::new(),
615 findings,
616 };
617 };
618 let mut types: BTreeMap<String, Option<Layout>> = BTreeMap::new();
619 let problem = top
620 .keys()
621 .find(|k| *k != "types" && *k != "description")
622 .map(|k| format!("the top level takes no member {k:?}"))
623 .or_else(|| {
624 (!top.get("description").is_none_or(Value::is_string))
625 .then(|| "`description` is not a string".to_owned())
626 })
627 .or_else(|| match top.get("types") {
628 Some(Value::Object(_)) => None,
629 Some(_) => Some("`types` is not an object".into()),
630 None => Some("there is no `types`".into()),
631 });
632 if let Some(p) = problem {
633 find("E038", String::new(), p);
634 }
635 let Some(Value::Object(defs)) = top.get("types") else {
636 return Self { types, findings };
637 };
638 for (name, record) in defs {
639 let at = format!("types.{name}");
640 if !is_type_name(name) {
641 find(
642 "E038",
643 at,
644 format!("{name:?} is not a type name [A-Z][A-Za-z0-9]*"),
645 );
646 continue;
647 }
648 let mut clean = true;
649 let Value::Object(rec) = record else {
650 find("E038", at, "a record is an object".into());
651 types.insert(name.clone(), None);
652 continue;
653 };
654 let problem = rec
655 .keys()
656 .find(|k| *k != "fields" && *k != "description")
657 .map(|k| format!("a record takes no member {k:?}"))
658 .or_else(|| {
659 (!rec.get("description").is_none_or(Value::is_string))
660 .then(|| "`description` is not a string".to_owned())
661 })
662 .or_else(|| match rec.get("fields") {
663 Some(Value::Array(_)) => None,
664 Some(_) => Some("`fields` is not a list".into()),
665 None => Some("a record needs `fields`".into()),
666 });
667 if let Some(p) = problem {
668 find("E038", at.clone(), p);
669 clean = false;
670 }
671 let Some(Value::Array(list)) = rec.get("fields") else {
672 types.insert(name.clone(), None);
673 continue;
674 };
675 let mut items: Vec<Option<Item>> = Vec::new();
678 let mut sound: Vec<(usize, &str, bool)> = Vec::new();
679 let mut objects = 0;
680 for (i, item) in list.iter().enumerate() {
681 let fat = format!("{at}.fields[{i}]");
682 if item.as_str() == Some(MARKER) {
683 items.push(Some(Item::Marker));
684 continue;
685 }
686 let Value::Object(f) = item else {
687 find(
688 "E038",
689 fat,
690 "an item is a field object or the marker \"...\"".into(),
691 );
692 items.push(None);
693 clean = false;
694 continue;
695 };
696 objects += 1;
697 let ty = match f.get("type") {
698 Some(Value::String(t)) if FIELD_TYPES.contains(&t.as_str()) => t.as_str(),
699 Some(Value::String(t)) => {
700 find(
701 "E043",
702 fat,
703 format!("`type` {t:?} names no field type of core §7.6"),
704 );
705 items.push(None);
706 clean = false;
707 continue;
708 }
709 _ => {
710 find("E038", fat, "a field needs `type`, a string".into());
711 items.push(None);
712 clean = false;
713 continue;
714 }
715 };
716 if let Some(p) = field_shape(f, ty) {
717 find("E038", fat, p);
718 items.push(None);
719 clean = false;
720 continue;
721 }
722 let name = f["name"].as_str().unwrap_or_default();
723 let optional = f.get("optional").and_then(Value::as_bool).unwrap_or(false);
724 sound.push((i, name, optional));
725 for key in ["values", "reserved"] {
726 for r in repeats(strings(f.get(key))) {
727 find("E042", fat.clone(), format!("{r:?} is repeated in `{key}`"));
728 clean = false;
729 }
730 }
731 match field_of(f, ty) {
732 Ok(field) => items.push(Some(Item::Field(field))),
733 Err((code, message)) => {
734 find(code, fat, message);
735 items.push(None);
736 clean = false;
737 }
738 }
739 }
740 for r in repeats(sound.iter().map(|(_, n, _)| *n)) {
741 find(
742 "E042",
743 at.clone(),
744 format!("the field name {r:?} is repeated"),
745 );
746 clean = false;
747 }
748 let first_marker = list.iter().position(|v| v.as_str() == Some(MARKER));
749 for (i, item) in list.iter().enumerate() {
750 if item.as_str() == Some(MARKER) && i > 0 && list[i - 1].as_str() == Some(MARKER) {
751 find(
752 "E045",
753 format!("{at}.fields[{i}]"),
754 "a marker right after another".into(),
755 );
756 clean = false;
757 }
758 }
759 if let Some(m0) = first_marker {
760 for (i, n, optional) in &sound {
761 if *i > m0 && !optional {
762 find(
763 "E045",
764 format!("{at}.fields[{i}]"),
765 format!("{n:?} is after a marker, and is not optional"),
766 );
767 clean = false;
768 }
769 }
770 }
771 if objects == 0 {
772 find("E039", at.clone(), "a record with no field".into());
773 clean = false;
774 }
775 let layout = if clean {
776 items
777 .into_iter()
778 .collect::<Option<Vec<Item>>>()
779 .map(Layout::new)
780 } else {
781 None
782 };
783 types.insert(name.clone(), layout);
784 }
785 Self { types, findings }
786 }
787}
788
789#[derive(Debug, Clone, PartialEq, Eq)]
793pub struct Layout {
794 pub items: Vec<Item>,
795 form: Value,
796 sha256: [u8; 32],
797}
798
799#[derive(Debug, Clone, PartialEq, Eq)]
801pub struct Slot {
802 pub name: Option<String>,
804 pub width: u32,
805 pub optional: bool,
806 pub offset: Option<u64>,
809}
810
811impl Field {
812 fn form(&self) -> Value {
813 let mut f = Map::new();
814 f.insert("type".into(), self.kind.as_str().into());
815 f.insert("width".into(), self.width.into());
816 f.insert("optional".into(), self.optional.into());
817 match &self.kind {
818 FieldKind::Int {
819 minimum,
820 maximum,
821 reserved,
822 } => {
823 f.insert("minimum".into(), (*minimum).into());
824 f.insert("maximum".into(), (*maximum).into());
825 f.insert("reserved".into(), reserved.clone().into());
826 }
827 FieldKind::Fixed {
828 minimum,
829 maximum,
830 resolution,
831 reserved,
832 ..
833 } => {
834 f.insert("minimum".into(), minimum.to_string().into());
835 f.insert("maximum".into(), maximum.to_string().into());
836 f.insert("resolution".into(), resolution.to_string().into());
837 f.insert("reserved".into(), reserved.clone().into());
838 }
839 FieldKind::Enum { values, escape } => {
840 f.insert("escape".into(), (*escape).into());
841 if !escape {
842 f.insert("values".into(), values.len().into());
843 }
844 }
845 FieldKind::Time { ms } => {
846 f.insert("ms".into(), (*ms).into());
847 }
848 FieldKind::Bool | FieldKind::Counter => {}
849 }
850 Value::Object(f)
851 }
852
853 fn top(&self) -> u64 {
854 top_code(self.width)
855 }
856
857 fn reserved_code(&self, i: usize) -> u64 {
858 self.top() - i as u64
859 }
860}
861
862#[must_use]
865pub const fn top_code(width: u32) -> u64 {
866 if width >= 64 {
867 u64::MAX
868 } else {
869 (1u64 << width) - 1
870 }
871}
872
873#[must_use]
877pub fn reserved_code(width: u32, declared: &[&str], name: &str) -> Option<u64> {
878 RESERVED
879 .iter()
880 .filter(|r| declared.contains(r))
881 .position(|r| *r == name)
882 .map(|i| top_code(width) - i as u64)
883}
884
885pub const DEFAULT_EPOCH: i64 = 0;
892
893#[derive(Debug, Clone, Copy, PartialEq, Eq)]
895pub enum WriteRefusal {
896 Missing,
898 Unknown,
900 Value,
903 Range,
905}
906
907impl WriteRefusal {
908 #[must_use]
909 pub fn token(self) -> &'static str {
910 match self {
911 Self::Missing => "missing",
912 Self::Unknown => "unknown",
913 Self::Value => "value",
914 Self::Range => "range",
915 }
916 }
917
918 #[must_use]
920 pub fn reason(self) -> &'static str {
921 match self {
922 Self::Missing => "missing: a field that is not optional is not given",
923 Self::Unknown => "unknown: a member the type does not have",
924 Self::Value => "value: the wrong JSON type, a name not declared, or no decimal",
925 Self::Range => "range: a value that has no code",
926 }
927 }
928}
929
930impl std::fmt::Display for WriteRefusal {
931 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
932 f.write_str(self.reason())
933 }
934}
935
936impl std::error::Error for WriteRefusal {}
937
938#[derive(Debug, Clone, Copy, PartialEq, Eq)]
940pub enum ReadRefusal {
941 Tag,
943 Length,
946 Code,
948 Extension,
950 Pad,
952 Epoch,
958}
959
960impl ReadRefusal {
961 #[must_use]
962 pub fn token(self) -> &'static str {
963 match self {
964 Self::Tag => "tag",
965 Self::Length => "length",
966 Self::Code => "code",
967 Self::Extension => "extension",
968 Self::Pad => "pad",
969 Self::Epoch => "epoch",
970 }
971 }
972
973 #[must_use]
975 pub fn reason(self) -> &'static str {
976 match self {
977 Self::Tag => "tag: the envelope's tag is not the type's",
978 Self::Length => "length: the record is not as long as the layout reads it",
979 Self::Code => "code: a field's code is unused",
980 Self::Extension => "extension: a marker read as 1, and no field present after it",
981 Self::Pad => "pad: a bit of the pad is 1",
982 Self::Epoch => "epoch: the deployment epoch puts the instant past 64-bit milliseconds",
983 }
984 }
985}
986
987impl std::fmt::Display for ReadRefusal {
988 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
989 f.write_str(self.reason())
990 }
991}
992
993impl std::error::Error for ReadRefusal {}
994
995#[derive(Debug, Clone, PartialEq, Eq)]
998pub struct Record {
999 pub bytes: Vec<u8>,
1000 pub bits: u64,
1001}
1002
1003impl Record {
1004 #[must_use]
1006 pub fn pad(&self) -> u64 {
1007 self.bytes.len() as u64 * 8 - self.bits
1008 }
1009
1010 #[must_use]
1012 pub fn bit_string(&self) -> String {
1013 (0..self.bits)
1014 .map(|i| {
1015 let b = (self.bytes[(i / 8) as usize] >> (7 - i % 8)) & 1;
1016 if b == 1 { '1' } else { '0' }
1017 })
1018 .collect()
1019 }
1020}
1021
1022#[derive(Debug, Clone, Default)]
1025pub struct BitWriter {
1026 bytes: Vec<u8>,
1027 len: u64,
1028}
1029
1030impl BitWriter {
1031 #[must_use]
1032 pub fn new() -> Self {
1033 Self::default()
1034 }
1035
1036 pub fn push(&mut self, v: u64, width: u32) {
1039 for i in (0..width).rev() {
1040 if self.len.is_multiple_of(8) {
1041 self.bytes.push(0);
1042 }
1043 if (v >> i) & 1 == 1 {
1044 let last = self.bytes.len() - 1;
1045 self.bytes[last] |= 0x80 >> (self.len % 8);
1046 }
1047 self.len += 1;
1048 }
1049 }
1050
1051 pub fn bit(&mut self, set: bool) {
1053 self.push(u64::from(set), 1);
1054 }
1055
1056 #[must_use]
1058 pub fn finish(self) -> Record {
1059 Record {
1060 bytes: self.bytes,
1061 bits: self.len,
1062 }
1063 }
1064}
1065
1066#[derive(Debug, Clone)]
1069pub struct BitReader<'a> {
1070 bytes: &'a [u8],
1071 pos: u64,
1072}
1073
1074impl<'a> BitReader<'a> {
1075 #[must_use]
1076 pub fn new(bytes: &'a [u8]) -> Self {
1077 Self { bytes, pos: 0 }
1078 }
1079
1080 fn total(&self) -> u64 {
1081 self.bytes.len() as u64 * 8
1082 }
1083
1084 pub fn take(&mut self, width: u32) -> Result<u64, ReadRefusal> {
1090 if self.pos + u64::from(width) > self.total() {
1091 return Err(ReadRefusal::Length);
1092 }
1093 let mut v = 0u64;
1094 for _ in 0..width {
1095 let b = (self.bytes[(self.pos / 8) as usize] >> (7 - self.pos % 8)) & 1;
1096 v = (v << 1) | u64::from(b);
1097 self.pos += 1;
1098 }
1099 Ok(v)
1100 }
1101
1102 pub fn bit(&mut self) -> Result<bool, ReadRefusal> {
1107 self.take(1).map(|b| b == 1)
1108 }
1109
1110 pub fn later(&self) -> Result<(), ReadRefusal> {
1116 if self.total() <= self.pos {
1117 Err(ReadRefusal::Length)
1118 } else {
1119 Ok(())
1120 }
1121 }
1122
1123 pub fn end(mut self) -> Result<(), ReadRefusal> {
1129 if self.bytes.len() as u64 != self.pos.div_ceil(8) {
1130 return Err(ReadRefusal::Length);
1131 }
1132 while self.pos < self.total() {
1133 if self.take(1)? == 1 {
1134 return Err(ReadRefusal::Pad);
1135 }
1136 }
1137 Ok(())
1138 }
1139}
1140
1141pub fn json_decimal(v: &Value) -> Result<Decimal, WriteRefusal> {
1151 match v {
1152 Value::String(s) => Decimal::parse_input(s).ok_or(WriteRefusal::Value),
1153 Value::Number(n) => Decimal::parse_input(&n.to_string()).ok_or(WriteRefusal::Value),
1156 _ => Err(WriteRefusal::Value),
1157 }
1158}
1159
1160pub fn json_integer(v: &Value) -> Result<i128, WriteRefusal> {
1170 match v {
1171 Value::Number(n) => {
1172 if let Some(i) = n.as_i64() {
1173 Ok(i128::from(i))
1174 } else if let Some(u) = n.as_u64() {
1175 Ok(i128::from(u))
1176 } else {
1177 if n.as_f64().unwrap_or(0.0).abs() >= 2f64.powi(63) {
1179 Err(WriteRefusal::Range)
1180 } else {
1181 Err(WriteRefusal::Value)
1182 }
1183 }
1184 }
1185 _ => Err(WriteRefusal::Value),
1186 }
1187}
1188
1189pub fn int_code(x: i128, minimum: i64, maximum: i64) -> Result<u64, WriteRefusal> {
1195 if x < i128::from(minimum) || x > i128::from(maximum) {
1196 return Err(WriteRefusal::Range);
1197 }
1198 u64::try_from(x - i128::from(minimum)).map_err(|_| WriteRefusal::Range)
1199}
1200
1201pub fn int_value(code: u64, minimum: i64, maximum: i64) -> Result<i128, ReadRefusal> {
1207 let span = i128::from(maximum) - i128::from(minimum);
1208 if i128::from(code) > span {
1209 return Err(ReadRefusal::Code);
1210 }
1211 Ok(i128::from(minimum) + i128::from(code))
1212}
1213
1214pub fn fixed_code(
1221 x: &Decimal,
1222 minimum: &Decimal,
1223 resolution: &Decimal,
1224 values: u128,
1225) -> Result<u64, WriteRefusal> {
1226 match x.sub(minimum).div_round_even(resolution).to_u128() {
1227 Some(c) if c < values => u64::try_from(c).map_err(|_| WriteRefusal::Range),
1228 _ => Err(WriteRefusal::Range),
1229 }
1230}
1231
1232pub fn fixed_value(
1238 code: u64,
1239 minimum: &Decimal,
1240 resolution: &Decimal,
1241 values: u128,
1242) -> Result<Decimal, ReadRefusal> {
1243 if u128::from(code) >= values {
1244 return Err(ReadRefusal::Code);
1245 }
1246 Ok(minimum.add(&resolution.mul_int(&BigInt::from(code))))
1247}
1248
1249#[derive(Debug, Clone, PartialEq, Eq)]
1252pub struct Fixed {
1253 pub minimum: Decimal,
1254 pub resolution: Decimal,
1255 pub values: u128,
1257}
1258
1259impl Fixed {
1260 #[must_use]
1264 pub fn new(minimum: &str, resolution: &str, values: u128) -> Self {
1265 Self {
1266 minimum: Decimal::parse(minimum).expect("a linted decimal"),
1267 resolution: Decimal::parse(resolution).expect("a linted decimal"),
1268 values,
1269 }
1270 }
1271
1272 pub fn code(&self, x: &Decimal) -> Result<u64, WriteRefusal> {
1277 fixed_code(x, &self.minimum, &self.resolution, self.values)
1278 }
1279
1280 pub fn value(&self, code: u64) -> Result<Decimal, ReadRefusal> {
1285 fixed_value(code, &self.minimum, &self.resolution, self.values)
1286 }
1287}
1288
1289pub fn time_code(t: i128, epoch: Option<i64>, ms: bool) -> Result<u64, WriteRefusal> {
1298 let e = epoch.unwrap_or(DEFAULT_EPOCH);
1299 let delta = t - 1000 * i128::from(e);
1300 let (s, m) = (delta.div_euclid(1000), delta.rem_euclid(1000));
1301 let s = u32::try_from(s).map_err(|_| WriteRefusal::Range)?;
1302 let m = u64::try_from(m).unwrap_or(0);
1303 Ok(if ms {
1304 (u64::from(s) << 10) | m
1305 } else {
1306 u64::from(s)
1307 })
1308}
1309
1310pub fn time_value(code: u64, epoch: Option<i64>, ms: bool) -> Result<i128, ReadRefusal> {
1318 let (s, m) = if ms {
1319 (code >> 10, code & 0x3ff)
1320 } else {
1321 (code, 0)
1322 };
1323 if m >= 1000 {
1324 return Err(ReadRefusal::Code);
1325 }
1326 let e = epoch.unwrap_or(DEFAULT_EPOCH);
1327 Ok(1000 * i128::from(e) + 1000 * i128::from(s) + i128::from(m))
1328}
1329
1330impl Layout {
1331 fn new(items: Vec<Item>) -> Self {
1332 let mut form = Vec::new();
1333 for it in &items {
1334 match it {
1335 Item::Marker => {
1336 form.push(Value::from(MARKER));
1337 break;
1338 }
1339 Item::Field(f) => form.push(f.form()),
1340 }
1341 }
1342 let form = Value::Array(form);
1343 let sha256 = Sha256::digest(crate::schema::jcs(&form)).into();
1344 Self {
1345 items,
1346 form,
1347 sha256,
1348 }
1349 }
1350
1351 #[must_use]
1353 pub fn form(&self) -> &Value {
1354 &self.form
1355 }
1356
1357 #[must_use]
1359 pub fn sha256_hex(&self) -> String {
1360 let mut s = String::with_capacity(64);
1361 for b in self.sha256 {
1362 let _ = write!(s, "{b:02x}");
1363 }
1364 s
1365 }
1366
1367 #[must_use]
1369 pub fn tag(&self) -> u8 {
1370 self.sha256[31] & 0x0f
1371 }
1372
1373 #[must_use]
1375 pub fn slots(&self) -> Vec<Slot> {
1376 let (mut pos, mut fixed) = (0u64, true);
1377 let mut out = Vec::new();
1378 for it in &self.items {
1379 let offset = fixed.then_some(pos);
1380 match it {
1381 Item::Marker => {
1382 out.push(Slot {
1383 name: None,
1384 width: 1,
1385 optional: false,
1386 offset,
1387 });
1388 fixed = false;
1389 }
1390 Item::Field(f) => {
1391 out.push(Slot {
1392 name: Some(f.name.clone()),
1393 width: f.width,
1394 optional: f.optional,
1395 offset,
1396 });
1397 if f.optional {
1398 fixed = false;
1399 } else {
1400 pos += u64::from(f.width);
1401 }
1402 }
1403 }
1404 }
1405 out
1406 }
1407
1408 #[must_use]
1411 pub fn min_bits(&self) -> u64 {
1412 let mut n = 0;
1413 for it in &self.items {
1414 match it {
1415 Item::Marker => return n + 1,
1416 Item::Field(f) if f.optional => n += 1,
1417 Item::Field(f) => n += u64::from(f.width),
1418 }
1419 }
1420 n
1421 }
1422
1423 #[must_use]
1426 pub fn max_bits(&self) -> u64 {
1427 self.items
1428 .iter()
1429 .map(|it| match it {
1430 Item::Marker => 1,
1431 Item::Field(f) => u64::from(f.width) + u64::from(f.optional),
1432 })
1433 .sum()
1434 }
1435
1436 pub fn fields(&self) -> impl Iterator<Item = &Field> {
1438 self.items.iter().filter_map(|it| match it {
1439 Item::Field(f) => Some(f),
1440 Item::Marker => None,
1441 })
1442 }
1443
1444 pub fn write(&self, value: &Value, epoch: Option<i64>) -> Result<Record, WriteRefusal> {
1451 let Value::Object(obj) = value else {
1452 return Err(WriteRefusal::Value);
1453 };
1454 if obj
1455 .keys()
1456 .any(|k| !self.fields().any(|f| f.name == k.as_str()))
1457 {
1458 return Err(WriteRefusal::Unknown);
1459 }
1460 let mut bits = BitWriter::new();
1461 for (i, it) in self.items.iter().enumerate() {
1462 match it {
1463 Item::Marker => {
1464 let later = self.items[i + 1..].iter().any(|x| match x {
1465 Item::Field(f) => obj.contains_key(&f.name),
1466 Item::Marker => false,
1467 });
1468 bits.bit(later);
1469 if !later {
1470 break;
1471 }
1472 }
1473 Item::Field(f) => match obj.get(&f.name) {
1474 None if f.optional => bits.bit(false),
1475 None => return Err(WriteRefusal::Missing),
1476 Some(v) => {
1477 let code = f.code(v, epoch)?;
1478 if f.optional {
1479 bits.bit(true);
1480 }
1481 bits.push(code, f.width);
1482 }
1483 },
1484 }
1485 }
1486 Ok(bits.finish())
1487 }
1488
1489 pub fn read(&self, tag: u8, bytes: &[u8], epoch: Option<i64>) -> Result<Value, ReadRefusal> {
1496 let mut out = Map::new();
1497 self.walk(tag, bytes, |f, code| {
1498 out.insert(f.name.clone(), f.value(code, epoch)?);
1499 Ok(())
1500 })?;
1501 Ok(Value::Object(out))
1502 }
1503
1504 pub fn check(&self, tag: u8, bytes: &[u8]) -> Result<(), ReadRefusal> {
1510 self.walk(tag, bytes, |f, code| f.check_code(code))
1511 }
1512
1513 fn walk(
1516 &self,
1517 tag: u8,
1518 bytes: &[u8],
1519 mut each: impl FnMut(&Field, u64) -> Result<(), ReadRefusal>,
1520 ) -> Result<(), ReadRefusal> {
1521 if tag != self.tag() {
1522 return Err(ReadRefusal::Tag);
1523 }
1524 let mut r = BitReader::new(bytes);
1525 let mut set_marker = false;
1526 let mut present_after = false;
1527 let last = self.items.len().saturating_sub(1);
1528 for (i, it) in self.items.iter().enumerate() {
1529 match it {
1530 Item::Marker => {
1531 if !r.bit()? {
1532 break;
1533 }
1534 if i == last {
1535 return r.later();
1537 }
1538 set_marker = true;
1539 present_after = false;
1540 }
1541 Item::Field(f) => {
1542 if f.optional && !r.bit()? {
1543 continue;
1544 }
1545 let code = r.take(f.width)?;
1546 each(f, code)?;
1547 present_after = true;
1548 }
1549 }
1550 }
1551 if set_marker && !present_after {
1552 return Err(ReadRefusal::Extension);
1553 }
1554 r.end()
1555 }
1556}
1557
1558impl Field {
1559 pub fn code(&self, v: &Value, epoch: Option<i64>) -> Result<u64, WriteRefusal> {
1566 let reserved = |list: &[&'static str], s: &str| {
1567 reserved_code(self.width, list, s).ok_or(WriteRefusal::Value)
1568 };
1569 match &self.kind {
1570 FieldKind::Int {
1571 minimum,
1572 maximum,
1573 reserved: res,
1574 } => {
1575 if let Value::String(s) = v
1576 && RESERVED.contains(&s.as_str())
1577 {
1578 return reserved(res, s);
1579 }
1580 int_code(json_integer(v)?, *minimum, *maximum)
1581 }
1582 FieldKind::Fixed {
1583 minimum,
1584 resolution,
1585 reserved: res,
1586 values,
1587 ..
1588 } => {
1589 if let Value::String(s) = v
1590 && RESERVED.contains(&s.as_str())
1591 {
1592 return reserved(res, s);
1593 }
1594 fixed_code(&json_decimal(v)?, minimum, resolution, *values)
1595 }
1596 FieldKind::Enum { values, escape } => match v {
1597 Value::Null if *escape => Ok(self.top()),
1598 Value::String(s) => values
1599 .iter()
1600 .position(|x| x == s)
1601 .map(|i| i as u64)
1602 .ok_or(WriteRefusal::Value),
1603 _ => Err(WriteRefusal::Value),
1604 },
1605 FieldKind::Bool => v.as_bool().map(u64::from).ok_or(WriteRefusal::Value),
1606 FieldKind::Counter => {
1607 let c = json_integer(v)?;
1608 u64::try_from(c).map_err(|_| WriteRefusal::Range)
1609 }
1610 FieldKind::Time { ms } => time_code(json_integer(v)?, epoch, *ms),
1611 }
1612 }
1613
1614 #[must_use]
1618 pub fn reserved_name(&self, code: u64) -> Option<&'static str> {
1619 let list = match &self.kind {
1620 FieldKind::Int { reserved, .. } | FieldKind::Fixed { reserved, .. } => reserved,
1621 _ => return None,
1622 };
1623 list.iter()
1624 .enumerate()
1625 .find(|(i, _)| code == self.reserved_code(*i))
1626 .map(|(_, r)| *r)
1627 }
1628
1629 pub fn value(&self, code: u64, epoch: Option<i64>) -> Result<Value, ReadRefusal> {
1636 if let Some(r) = self.reserved_name(code) {
1637 return Ok(Value::from(r));
1638 }
1639 match &self.kind {
1640 FieldKind::Int {
1641 minimum, maximum, ..
1642 } => {
1643 let v = int_value(code, *minimum, *maximum)?;
1644 Ok(i64::try_from(v).map_or(Value::Null, Value::from))
1645 }
1646 FieldKind::Fixed {
1647 minimum,
1648 resolution,
1649 values,
1650 ..
1651 } => fixed_value(code, minimum, resolution, *values)
1652 .map(|x| Value::String(x.to_string())),
1653 FieldKind::Enum { values, escape } => match usize::try_from(code) {
1654 Ok(i) if i < values.len() => Ok(Value::String(values[i].clone())),
1655 _ if *escape => Ok(Value::Null),
1656 _ => Err(ReadRefusal::Code),
1657 },
1658 FieldKind::Bool => Ok(Value::Bool(code == 1)),
1659 FieldKind::Counter => Ok(Value::from(code)),
1660 FieldKind::Time { ms } => {
1661 let t = time_value(code, epoch, *ms)?;
1662 i64::try_from(t)
1663 .map(Value::from)
1664 .map_err(|_| ReadRefusal::Epoch)
1665 }
1666 }
1667 }
1668
1669 pub fn check_code(&self, code: u64) -> Result<(), ReadRefusal> {
1675 if self.reserved_name(code).is_some() {
1676 return Ok(());
1677 }
1678 let used = match &self.kind {
1679 FieldKind::Int {
1680 minimum, maximum, ..
1681 } => int_value(code, *minimum, *maximum).is_ok(),
1682 FieldKind::Fixed { values, .. } => u128::from(code) < *values,
1683 FieldKind::Enum { values, escape } => *escape || code < values.len() as u64,
1684 FieldKind::Bool | FieldKind::Counter => true,
1685 FieldKind::Time { ms } => !*ms || code & 0x3ff < 1000,
1686 };
1687 if used { Ok(()) } else { Err(ReadRefusal::Code) }
1688 }
1689}
1690
1691pub fn layout_in(doc: &Value, name: &str) -> Result<Layout, String> {
1698 let read = PackedDoc::read(doc);
1699 match read.types.get(name) {
1700 Some(Some(layout)) => Ok(layout.clone()),
1701 Some(None) => Err(format!(
1702 "packed:{name}'s declaration does not read ({})",
1703 read.findings
1704 .iter()
1705 .map(|f| f.code)
1706 .collect::<Vec<_>>()
1707 .join(", ")
1708 )),
1709 None => Err(format!("the packed document defines no types/{name}")),
1710 }
1711}
1712
1713#[cfg(test)]
1714mod tests {
1715 use serde_json::json;
1716
1717 use super::*;
1718
1719 fn codes(doc: &Value) -> Vec<&'static str> {
1720 let mut c: Vec<_> = PackedDoc::read(doc)
1721 .findings
1722 .iter()
1723 .map(|f| f.code)
1724 .collect();
1725 c.sort_unstable();
1726 c
1727 }
1728
1729 #[test]
1730 fn decimals_read_exactly_and_write_shortest() {
1731 for (s, want) in [
1732 ("0", "0"),
1733 ("-0", "0"),
1734 ("2.00", "2"),
1735 ("-40", "-40"),
1736 ("0.10", "0.1"),
1737 ("1013.2", "1013.2"),
1738 ] {
1739 assert_eq!(Decimal::parse(s).unwrap().to_string(), want, "{s}");
1740 }
1741 for bad in ["", "01", "1.", ".5", "+1", "1e3", "1,5", "--1"] {
1742 assert!(Decimal::parse(bad).is_none(), "{bad}");
1743 }
1744 assert_eq!(Decimal::parse_input("5e-1").unwrap().to_string(), "0.5");
1745 assert_eq!(Decimal::parse_input("1.5E+2").unwrap().to_string(), "150");
1746 assert_eq!(
1747 Decimal::parse_input("1e21").unwrap().to_string(),
1748 "1000000000000000000000"
1749 );
1750 assert!(Decimal::parse_input("1e999999").is_none());
1751 }
1752
1753 #[test]
1754 fn ties_go_to_the_even_code() {
1755 let half = Decimal::parse("0.5").unwrap();
1756 let r = |s: &str| {
1757 Decimal::parse_input(s)
1758 .unwrap()
1759 .div_round_even(&half)
1760 .to_string()
1761 };
1762 assert_eq!(r("0.25"), "0");
1763 assert_eq!(r("0.75"), "2");
1764 assert_eq!(r("-0.25"), "0");
1765 assert_eq!(r("-0.75"), "-2");
1766 assert_eq!(r("0.2500000000000000000000000001"), "1");
1767 }
1768
1769 #[test]
1770 fn the_report_sensor_record_is_40_bits() {
1771 let doc = json!({"types": {"Sensor": {"fields": [
1772 {"name": "temperature", "type": "fixed", "minimum": "-40", "maximum": "85", "resolution": "0.1"},
1773 {"name": "humidity", "type": "fixed", "minimum": "0", "maximum": "100", "resolution": "0.5"},
1774 {"name": "pressure", "type": "fixed", "minimum": "300", "maximum": "1100", "resolution": "0.1"},
1775 {"name": "battery", "type": "fixed", "minimum": "2.00", "maximum": "4.20", "resolution": "0.01"}
1776 ]}}});
1777 let p = PackedDoc::read(&doc);
1778 assert!(p.findings.is_empty(), "{:?}", p.findings);
1779 let l = p.types["Sensor"].clone().unwrap();
1780 assert_eq!((l.min_bits(), l.max_bits()), (40, 40));
1781 let rec = l
1782 .write(
1783 &json!({"temperature": "21.5", "humidity": "43.5", "pressure": "1013.2", "battery": "3.70"}),
1784 None,
1785 )
1786 .unwrap();
1787 assert_eq!(rec.bytes, [0x4c, 0xea, 0xfb, 0xdc, 0xaa]);
1788 assert_eq!(rec.pad(), 0);
1789 let back = l.read(l.tag(), &rec.bytes, None).unwrap();
1790 assert_eq!(back["battery"], "3.7");
1791 assert_eq!(l.read(l.tag() ^ 1, &rec.bytes, None), Err(ReadRefusal::Tag));
1792 assert_eq!(
1793 l.read(l.tag(), &rec.bytes[..4], None),
1794 Err(ReadRefusal::Length)
1795 );
1796 }
1797
1798 #[test]
1799 fn lints_follow_cascade_seven() {
1800 assert_eq!(codes(&json!([])), ["E038"]);
1801 assert_eq!(codes(&json!({"types": {}, "x": 1})), ["E038"]);
1802 assert_eq!(codes(&json!({"types": {"bad": {"fields": []}}})), ["E038"]);
1803 assert_eq!(codes(&json!({"types": {"A": {"fields": []}}})), ["E039"]);
1804 assert_eq!(
1805 codes(&json!({"types": {"A": {"fields": [{"name": "a", "type": "float"}]}}})),
1806 ["E043"]
1807 );
1808 assert_eq!(
1809 codes(
1810 &json!({"types": {"A": {"fields": [{"name": "a", "type": "int", "minimum": 1}]}}})
1811 ),
1812 ["E038"]
1813 );
1814 assert_eq!(
1815 codes(&json!({"types": {"A": {"fields": [
1816 {"name": "a", "type": "int", "minimum": 2, "maximum": 1},
1817 {"name": "b", "type": "fixed", "minimum": "0", "maximum": "1", "resolution": "0.3"},
1818 {"name": "c", "type": "fixed", "minimum": "x", "maximum": "-1", "resolution": "0"},
1819 {"name": "d", "type": "counter", "width": 65},
1820 {"name": "e", "type": "int", "minimum": 0, "maximum": 0},
1821 {"name": "a", "type": "bool"},
1822 {"name": "f", "type": "enum", "values": ["x", "x"]},
1823 "...", "...",
1824 {"name": "g", "type": "bool"}
1825 ]}}})),
1826 [
1827 "E039", "E040", "E040", "E041", "E041", "E042", "E042", "E045", "E045"
1828 ]
1829 );
1830 }
1831
1832 #[test]
1833 fn appending_behind_a_marker_keeps_the_tag() {
1834 let v1 = json!({"types": {"L": {"fields": [{"name": "up", "type": "bool"}, "..."]}}});
1835 let v2 = json!({"types": {"L": {"fields": [
1836 {"name": "up", "type": "bool"}, "...",
1837 {"name": "q", "type": "int", "minimum": 0, "maximum": 100, "optional": true}, "..."
1838 ]}}});
1839 let a = PackedDoc::read(&v1).types["L"].clone().unwrap();
1840 let b = PackedDoc::read(&v2).types["L"].clone().unwrap();
1841 assert_eq!(a.tag(), b.tag());
1842 let new = b.write(&json!({"up": true, "q": 87}), None).unwrap();
1843 assert_eq!(
1844 a.read(a.tag(), &new.bytes, None).unwrap(),
1845 json!({"up": true})
1846 );
1847 let old = a.write(&json!({"up": false}), None).unwrap();
1848 assert_eq!(
1849 b.read(b.tag(), &old.bytes, None).unwrap(),
1850 json!({"up": false})
1851 );
1852 }
1853}