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 #[must_use]
174 pub fn half(&self) -> Self {
175 Self {
176 m: &self.m * BigInt::from(5),
177 e: self.e + 1,
178 }
179 .normalized()
180 }
181
182 pub(crate) fn of_i128(v: i128) -> Self {
184 Self {
185 m: BigInt::from(v),
186 e: 0,
187 }
188 }
189
190 pub(crate) fn distance(&self, o: &Self) -> Self {
193 let d = self.sub(o);
194 Self {
195 m: d.m.abs(),
196 e: d.e,
197 }
198 }
199
200 fn div_exact(&self, o: &Self) -> Option<BigInt> {
202 let e = self.e.max(o.e);
203 let (q, r) = self.at(e).div_mod_floor(&o.at(e));
204 r.is_zero().then_some(q)
205 }
206
207 fn div_round_even(&self, o: &Self) -> BigInt {
209 let e = self.e.max(o.e);
210 let d = o.at(e);
211 let (q, r) = self.at(e).div_mod_floor(&d);
212 let twice: BigInt = &r * BigInt::from(2u8);
213 let up = match twice.cmp(&d) {
214 std::cmp::Ordering::Less => false,
215 std::cmp::Ordering::Greater => true,
216 std::cmp::Ordering::Equal => q.is_odd(),
217 };
218 if up { q + BigInt::one() } else { q }
219 }
220}
221
222impl PartialOrd for Decimal {
223 fn partial_cmp(&self, o: &Self) -> Option<std::cmp::Ordering> {
224 Some(self.cmp(o))
225 }
226}
227
228impl Ord for Decimal {
229 fn cmp(&self, o: &Self) -> std::cmp::Ordering {
230 let e = self.e.max(o.e);
231 self.at(e).cmp(&o.at(e))
232 }
233}
234
235impl std::fmt::Display for Decimal {
236 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239 let n = self.clone().normalized();
240 if n.m.is_zero() {
241 return f.write_str("0");
242 }
243 let digits = n.m.abs().to_string();
244 let e = n.e as usize;
245 let sign = if n.m.sign() == Sign::Minus { "-" } else { "" };
246 if e == 0 {
247 return write!(f, "{sign}{digits}");
248 }
249 let padded = format!("{digits:0>width$}", width = e + 1);
250 let (int, frac) = padded.split_at(padded.len() - e);
251 write!(f, "{sign}{int}.{frac}")
252 }
253}
254
255impl std::str::FromStr for Decimal {
256 type Err = WriteRefusal;
257
258 fn from_str(s: &str) -> Result<Self, WriteRefusal> {
261 Self::parse_input(s).ok_or(WriteRefusal::Value)
262 }
263}
264
265impl From<i64> for Decimal {
266 fn from(v: i64) -> Self {
267 Self {
268 m: BigInt::from(v),
269 e: 0,
270 }
271 }
272}
273
274impl Decimal {
275 #[must_use]
279 pub fn from_f64(x: f64) -> Option<Self> {
280 if !x.is_finite() {
281 return None;
282 }
283 Self::parse_input(&format!("{x}"))
284 }
285
286 #[must_use]
289 pub fn to_f64(&self) -> f64 {
290 self.to_string().parse().unwrap_or(f64::NAN)
291 }
292}
293
294fn pow10(n: u32) -> BigInt {
295 num_traits::pow(BigInt::from(10), n as usize)
296}
297
298fn bits_for(codes: &BigInt) -> u64 {
300 if codes <= &BigInt::one() {
301 0
302 } else {
303 (codes - 1u32).bits()
304 }
305}
306
307#[derive(Debug, Clone, PartialEq, Eq)]
311pub struct Finding {
312 pub code: &'static str,
313 pub at: String,
316 pub message: String,
317}
318
319#[derive(Debug, Clone, PartialEq, Eq)]
321pub enum FieldKind {
322 Int {
323 minimum: i64,
324 maximum: i64,
325 reserved: Vec<&'static str>,
326 },
327 Fixed {
328 minimum: Decimal,
329 maximum: Decimal,
330 resolution: Decimal,
331 reserved: Vec<&'static str>,
332 values: u128,
334 },
335 Enum {
336 values: Vec<String>,
337 escape: bool,
338 },
339 Bool,
340 Counter,
341 Time {
342 ms: bool,
343 },
344}
345
346impl FieldKind {
347 #[must_use]
348 pub fn as_str(&self) -> &'static str {
349 match self {
350 Self::Int { .. } => "int",
351 Self::Fixed { .. } => "fixed",
352 Self::Enum { .. } => "enum",
353 Self::Bool => "bool",
354 Self::Counter => "counter",
355 Self::Time { .. } => "time",
356 }
357 }
358}
359
360#[derive(Debug, Clone, PartialEq, Eq)]
362pub struct Field {
363 pub name: String,
364 pub kind: FieldKind,
365 pub width: u32,
367 pub optional: bool,
368}
369
370#[derive(Debug, Clone, PartialEq, Eq)]
372pub enum Item {
373 Field(Field),
374 Marker,
376}
377
378#[derive(Debug, Clone, Default)]
381pub struct PackedDoc {
382 pub types: BTreeMap<String, Option<Layout>>,
384 pub findings: Vec<Finding>,
385}
386
387fn is_type_name(s: &str) -> bool {
388 let mut b = s.bytes();
389 b.next().is_some_and(|c| c.is_ascii_uppercase()) && b.all(|c| c.is_ascii_alphanumeric())
390}
391
392fn is_field_name(s: &str) -> bool {
393 let mut b = s.bytes();
394 b.next().is_some_and(|c| c.is_ascii_lowercase())
395 && b.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_')
396}
397
398fn is_value_name(s: &str) -> bool {
399 let mut b = s.bytes();
400 b.next().is_some_and(|c| c.is_ascii_alphabetic())
401 && b.all(|c| c.is_ascii_alphanumeric() || c == b'_')
402}
403
404fn members(ty: &str) -> (&'static [&'static str], &'static [&'static str]) {
407 match ty {
408 "int" => (&["minimum", "maximum", "reserved"], &["minimum", "maximum"]),
409 "fixed" => (
410 &["minimum", "maximum", "resolution", "reserved"],
411 &["minimum", "maximum", "resolution"],
412 ),
413 "enum" => (&["values", "escape", "width"], &["values"]),
414 "counter" => (&["width"], &["width"]),
415 "time" => (&["ms"], &[]),
416 _ => (&[], &[]),
417 }
418}
419
420fn field_shape(m: &Map<String, Value>, ty: &str) -> Option<String> {
422 let (takes, needs) = members(ty);
423 for k in m.keys() {
424 if !["name", "type", "optional", "description"].contains(&k.as_str())
425 && !takes.contains(&k.as_str())
426 {
427 return Some(format!("a `{ty}` field takes no member {k:?}"));
428 }
429 }
430 for k in std::iter::once(&"name").chain(needs) {
431 if !m.contains_key(*k) {
432 return Some(format!("a `{ty}` field needs `{k}`"));
433 }
434 }
435 match m.get("name") {
436 Some(Value::String(n)) if is_field_name(n) => {}
437 Some(v) => return Some(format!("`name` {v} is not [a-z][a-z0-9_]*")),
438 None => {}
439 }
440 let is_bool = |k: &str| m.get(k).is_none_or(Value::is_boolean);
441 let is_int = |k: &str| m.get(k).is_none_or(|v| v.as_i64().is_some());
442 let is_str = |k: &str| m.get(k).is_none_or(Value::is_string);
443 if !is_bool("optional") {
444 return Some("`optional` is not a boolean".into());
445 }
446 if !is_str("description") {
447 return Some("`description` is not a string".into());
448 }
449 let list_of = |k: &str, ok: &dyn Fn(&str) -> bool| match m.get(k) {
450 None => true,
451 Some(Value::Array(a)) => a.iter().all(|v| v.as_str().is_some_and(ok)),
452 Some(_) => false,
453 };
454 let problem = match ty {
455 "int" if !is_int("minimum") || !is_int("maximum") => {
456 Some("`minimum` and `maximum` are integers")
457 }
458 "fixed" if !is_str("minimum") || !is_str("maximum") || !is_str("resolution") => {
459 Some("`minimum`, `maximum` and `resolution` are decimal strings")
460 }
461 "int" | "fixed" if !list_of("reserved", &|s| RESERVED.contains(&s)) => {
462 Some("`reserved` lists not_available, error and out_of_range")
463 }
464 "enum" if !list_of("values", &is_value_name) => {
465 Some("`values` is a list of names [A-Za-z][A-Za-z0-9_]*")
466 }
467 "enum" if !is_bool("escape") => Some("`escape` is not a boolean"),
468 "enum" | "counter" if !is_int("width") => Some("`width` is not an integer"),
469 "time" if !is_bool("ms") => Some("`ms` is not a boolean"),
470 _ => None,
471 };
472 problem.map(str::to_owned)
473}
474
475fn repeats<'a>(names: impl IntoIterator<Item = &'a str>) -> Vec<&'a str> {
477 let mut seen = BTreeSet::new();
478 names.into_iter().filter(|n| !seen.insert(*n)).collect()
479}
480
481fn strings(v: Option<&Value>) -> Vec<&str> {
482 v.and_then(Value::as_array)
483 .map(|a| a.iter().filter_map(Value::as_str).collect())
484 .unwrap_or_default()
485}
486
487fn reserved_of(m: &Map<String, Value>) -> Vec<&'static str> {
488 let listed = strings(m.get("reserved"));
489 RESERVED
490 .iter()
491 .copied()
492 .filter(|r| listed.contains(r))
493 .collect()
494}
495
496fn field_of(m: &Map<String, Value>, ty: &str) -> Result<Field, (&'static str, String)> {
499 let name = m["name"].as_str().unwrap_or_default().to_owned();
500 let optional = m.get("optional").and_then(Value::as_bool).unwrap_or(false);
501 let wide = |codes: &BigInt| -> Result<u32, (&'static str, String)> {
502 let w = bits_for(codes);
503 if (1..=64).contains(&w) {
504 Ok(u32::try_from(w).unwrap_or(64))
505 } else {
506 Err((
507 "E041",
508 format!("{codes} codes need {w} bits; a field is 1 to 64"),
509 ))
510 }
511 };
512 let (kind, width) = match ty {
513 "int" => {
514 let (lo, hi) = (
515 m["minimum"].as_i64().unwrap_or(0),
516 m["maximum"].as_i64().unwrap_or(0),
517 );
518 if lo > hi {
519 return Err(("E039", format!("`minimum` {lo} is above `maximum` {hi}")));
520 }
521 let reserved = reserved_of(m);
522 let codes = BigInt::from(hi) - BigInt::from(lo) + BigInt::from(1 + reserved.len());
523 let width = wide(&codes)?;
524 (
525 FieldKind::Int {
526 minimum: lo,
527 maximum: hi,
528 reserved,
529 },
530 width,
531 )
532 }
533 "fixed" => {
534 let read = |k: &str| {
535 let s = m[k].as_str().unwrap_or_default();
536 Decimal::parse(s).ok_or_else(|| ("E040", format!("`{k}` {s:?} is not a decimal")))
537 };
538 let (lo, hi, res) = (read("minimum")?, read("maximum")?, read("resolution")?);
539 if lo > hi {
540 return Err(("E039", format!("`minimum` {lo} is above `maximum` {hi}")));
541 }
542 if !res.is_positive() {
543 return Err(("E040", format!("`resolution` {res} is not above 0")));
544 }
545 let Some(steps) = hi.sub(&lo).div_exact(&res) else {
546 return Err((
547 "E040",
548 format!("`resolution` {res} does not divide {hi} − {lo}"),
549 ));
550 };
551 let reserved = reserved_of(m);
552 let values: BigInt = steps + BigInt::one();
553 let width = wide(&(&values + BigInt::from(reserved.len())))?;
554 (
555 FieldKind::Fixed {
556 minimum: lo,
557 maximum: hi,
558 resolution: res,
559 reserved,
560 values: values.to_u128().unwrap_or(u128::MAX),
561 },
562 width,
563 )
564 }
565 "enum" => {
566 let values: Vec<String> = strings(m.get("values"))
567 .into_iter()
568 .map(str::to_owned)
569 .collect();
570 if values.is_empty() {
571 return Err(("E039", "an enum with no value".into()));
572 }
573 let escape = m.get("escape").and_then(Value::as_bool).unwrap_or(false);
574 let need = bits_for(&BigInt::from(values.len() + usize::from(escape)));
575 let width = match m.get("width").and_then(Value::as_i64) {
576 Some(w) if !(1..=64).contains(&w) || u64::try_from(w).unwrap_or(0) < need => {
577 return Err((
578 "E041",
579 format!("`width` {w}: the enum needs {need} bits, and a field is 1 to 64"),
580 ));
581 }
582 Some(w) => u32::try_from(w).unwrap_or(64),
583 None => wide(&BigInt::from(values.len() + usize::from(escape)))?,
584 };
585 (FieldKind::Enum { values, escape }, width)
586 }
587 "bool" => (FieldKind::Bool, 1),
588 "counter" => {
589 let w = m["width"].as_i64().unwrap_or(0);
590 if !(1..=64).contains(&w) {
591 return Err(("E041", format!("a counter's `width` {w} is not 1 to 64")));
592 }
593 (FieldKind::Counter, u32::try_from(w).unwrap_or(64))
594 }
595 "time" => {
596 let ms = m.get("ms").and_then(Value::as_bool).unwrap_or(false);
597 (FieldKind::Time { ms }, if ms { 42 } else { 32 })
598 }
599 _ => unreachable!("checked by E043"),
600 };
601 Ok(Field {
602 name,
603 kind,
604 width,
605 optional,
606 })
607}
608
609impl PackedDoc {
610 #[must_use]
613 #[allow(clippy::too_many_lines)]
614 pub fn read(doc: &Value) -> Self {
615 let mut findings = Vec::new();
616 let mut find = |code: &'static str, at: String, message: String| {
617 findings.push(Finding { code, at, message });
618 };
619 let Value::Object(top) = doc else {
620 find(
621 "E038",
622 String::new(),
623 "the top level is not an object".into(),
624 );
625 return Self {
626 types: BTreeMap::new(),
627 findings,
628 };
629 };
630 let mut types: BTreeMap<String, Option<Layout>> = BTreeMap::new();
631 let problem = top
632 .keys()
633 .find(|k| *k != "types" && *k != "description")
634 .map(|k| format!("the top level takes no member {k:?}"))
635 .or_else(|| {
636 (!top.get("description").is_none_or(Value::is_string))
637 .then(|| "`description` is not a string".to_owned())
638 })
639 .or_else(|| match top.get("types") {
640 Some(Value::Object(_)) => None,
641 Some(_) => Some("`types` is not an object".into()),
642 None => Some("there is no `types`".into()),
643 });
644 if let Some(p) = problem {
645 find("E038", String::new(), p);
646 }
647 let Some(Value::Object(defs)) = top.get("types") else {
648 return Self { types, findings };
649 };
650 for (name, record) in defs {
651 let at = format!("types.{name}");
652 if !is_type_name(name) {
653 find(
654 "E038",
655 at,
656 format!("{name:?} is not a type name [A-Z][A-Za-z0-9]*"),
657 );
658 continue;
659 }
660 let mut clean = true;
661 let Value::Object(rec) = record else {
662 find("E038", at, "a record is an object".into());
663 types.insert(name.clone(), None);
664 continue;
665 };
666 let problem = rec
667 .keys()
668 .find(|k| *k != "fields" && *k != "description")
669 .map(|k| format!("a record takes no member {k:?}"))
670 .or_else(|| {
671 (!rec.get("description").is_none_or(Value::is_string))
672 .then(|| "`description` is not a string".to_owned())
673 })
674 .or_else(|| match rec.get("fields") {
675 Some(Value::Array(_)) => None,
676 Some(_) => Some("`fields` is not a list".into()),
677 None => Some("a record needs `fields`".into()),
678 });
679 if let Some(p) = problem {
680 find("E038", at.clone(), p);
681 clean = false;
682 }
683 let Some(Value::Array(list)) = rec.get("fields") else {
684 types.insert(name.clone(), None);
685 continue;
686 };
687 let mut items: Vec<Option<Item>> = Vec::new();
690 let mut sound: Vec<(usize, &str, bool)> = Vec::new();
691 let mut objects = 0;
692 for (i, item) in list.iter().enumerate() {
693 let fat = format!("{at}.fields[{i}]");
694 if item.as_str() == Some(MARKER) {
695 items.push(Some(Item::Marker));
696 continue;
697 }
698 let Value::Object(f) = item else {
699 find(
700 "E038",
701 fat,
702 "an item is a field object or the marker \"...\"".into(),
703 );
704 items.push(None);
705 clean = false;
706 continue;
707 };
708 objects += 1;
709 let ty = match f.get("type") {
710 Some(Value::String(t)) if FIELD_TYPES.contains(&t.as_str()) => t.as_str(),
711 Some(Value::String(t)) => {
712 find(
713 "E043",
714 fat,
715 format!("`type` {t:?} names no field type of core §7.6"),
716 );
717 items.push(None);
718 clean = false;
719 continue;
720 }
721 _ => {
722 find("E038", fat, "a field needs `type`, a string".into());
723 items.push(None);
724 clean = false;
725 continue;
726 }
727 };
728 if let Some(p) = field_shape(f, ty) {
729 find("E038", fat, p);
730 items.push(None);
731 clean = false;
732 continue;
733 }
734 let name = f["name"].as_str().unwrap_or_default();
735 let optional = f.get("optional").and_then(Value::as_bool).unwrap_or(false);
736 sound.push((i, name, optional));
737 for key in ["values", "reserved"] {
738 for r in repeats(strings(f.get(key))) {
739 find("E042", fat.clone(), format!("{r:?} is repeated in `{key}`"));
740 clean = false;
741 }
742 }
743 match field_of(f, ty) {
744 Ok(field) => items.push(Some(Item::Field(field))),
745 Err((code, message)) => {
746 find(code, fat, message);
747 items.push(None);
748 clean = false;
749 }
750 }
751 }
752 for r in repeats(sound.iter().map(|(_, n, _)| *n)) {
753 find(
754 "E042",
755 at.clone(),
756 format!("the field name {r:?} is repeated"),
757 );
758 clean = false;
759 }
760 let first_marker = list.iter().position(|v| v.as_str() == Some(MARKER));
761 for (i, item) in list.iter().enumerate() {
762 if item.as_str() == Some(MARKER) && i > 0 && list[i - 1].as_str() == Some(MARKER) {
763 find(
764 "E045",
765 format!("{at}.fields[{i}]"),
766 "a marker right after another".into(),
767 );
768 clean = false;
769 }
770 }
771 if let Some(m0) = first_marker {
772 for (i, n, optional) in &sound {
773 if *i > m0 && !optional {
774 find(
775 "E045",
776 format!("{at}.fields[{i}]"),
777 format!("{n:?} is after a marker, and is not optional"),
778 );
779 clean = false;
780 }
781 }
782 }
783 if objects == 0 {
784 find("E039", at.clone(), "a record with no field".into());
785 clean = false;
786 }
787 let layout = if clean {
788 items
789 .into_iter()
790 .collect::<Option<Vec<Item>>>()
791 .map(Layout::new)
792 } else {
793 None
794 };
795 types.insert(name.clone(), layout);
796 }
797 Self { types, findings }
798 }
799}
800
801#[derive(Debug, Clone, PartialEq, Eq)]
805pub struct Layout {
806 pub items: Vec<Item>,
807 form: Value,
808 sha256: [u8; 32],
809}
810
811#[derive(Debug, Clone, PartialEq, Eq)]
813pub struct Slot {
814 pub name: Option<String>,
816 pub width: u32,
817 pub optional: bool,
818 pub offset: Option<u64>,
821}
822
823impl Field {
824 fn form(&self) -> Value {
825 let mut f = Map::new();
826 f.insert("type".into(), self.kind.as_str().into());
827 f.insert("width".into(), self.width.into());
828 f.insert("optional".into(), self.optional.into());
829 match &self.kind {
830 FieldKind::Int {
831 minimum,
832 maximum,
833 reserved,
834 } => {
835 f.insert("minimum".into(), (*minimum).into());
836 f.insert("maximum".into(), (*maximum).into());
837 f.insert("reserved".into(), reserved.clone().into());
838 }
839 FieldKind::Fixed {
840 minimum,
841 maximum,
842 resolution,
843 reserved,
844 ..
845 } => {
846 f.insert("minimum".into(), minimum.to_string().into());
847 f.insert("maximum".into(), maximum.to_string().into());
848 f.insert("resolution".into(), resolution.to_string().into());
849 f.insert("reserved".into(), reserved.clone().into());
850 }
851 FieldKind::Enum { values, escape } => {
852 f.insert("escape".into(), (*escape).into());
853 if !escape {
854 f.insert("values".into(), values.len().into());
855 }
856 }
857 FieldKind::Time { ms } => {
858 f.insert("ms".into(), (*ms).into());
859 }
860 FieldKind::Bool | FieldKind::Counter => {}
861 }
862 Value::Object(f)
863 }
864
865 fn top(&self) -> u64 {
866 top_code(self.width)
867 }
868
869 fn reserved_code(&self, i: usize) -> u64 {
870 self.top() - i as u64
871 }
872}
873
874#[must_use]
877pub const fn top_code(width: u32) -> u64 {
878 if width >= 64 {
879 u64::MAX
880 } else {
881 (1u64 << width) - 1
882 }
883}
884
885#[must_use]
889pub fn reserved_code(width: u32, declared: &[&str], name: &str) -> Option<u64> {
890 RESERVED
891 .iter()
892 .filter(|r| declared.contains(r))
893 .position(|r| *r == name)
894 .map(|i| top_code(width) - i as u64)
895}
896
897pub const DEFAULT_EPOCH: i64 = 0;
904
905#[derive(Debug, Clone, Copy, PartialEq, Eq)]
907pub enum WriteRefusal {
908 Missing,
910 Unknown,
912 Value,
915 Range,
917}
918
919impl WriteRefusal {
920 #[must_use]
921 pub fn token(self) -> &'static str {
922 match self {
923 Self::Missing => "missing",
924 Self::Unknown => "unknown",
925 Self::Value => "value",
926 Self::Range => "range",
927 }
928 }
929
930 #[must_use]
932 pub fn reason(self) -> &'static str {
933 match self {
934 Self::Missing => "missing: a field that is not optional is not given",
935 Self::Unknown => "unknown: a member the type does not have",
936 Self::Value => "value: the wrong JSON type, a name not declared, or no decimal",
937 Self::Range => "range: a value that has no code",
938 }
939 }
940}
941
942impl std::fmt::Display for WriteRefusal {
943 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
944 f.write_str(self.reason())
945 }
946}
947
948impl std::error::Error for WriteRefusal {}
949
950#[derive(Debug, Clone, Copy, PartialEq, Eq)]
952pub enum ReadRefusal {
953 Tag,
955 Length,
958 Code,
960 Extension,
962 Pad,
964 Epoch,
970}
971
972impl ReadRefusal {
973 #[must_use]
974 pub fn token(self) -> &'static str {
975 match self {
976 Self::Tag => "tag",
977 Self::Length => "length",
978 Self::Code => "code",
979 Self::Extension => "extension",
980 Self::Pad => "pad",
981 Self::Epoch => "epoch",
982 }
983 }
984
985 #[must_use]
987 pub fn reason(self) -> &'static str {
988 match self {
989 Self::Tag => "tag: the envelope's tag is not the type's",
990 Self::Length => "length: the record is not as long as the layout reads it",
991 Self::Code => "code: a field's code is unused",
992 Self::Extension => "extension: a marker read as 1, and no field present after it",
993 Self::Pad => "pad: a bit of the pad is 1",
994 Self::Epoch => "epoch: the deployment epoch puts the instant past 64-bit milliseconds",
995 }
996 }
997}
998
999impl std::fmt::Display for ReadRefusal {
1000 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1001 f.write_str(self.reason())
1002 }
1003}
1004
1005impl std::error::Error for ReadRefusal {}
1006
1007#[derive(Debug, Clone, PartialEq, Eq)]
1010pub struct Record {
1011 pub bytes: Vec<u8>,
1012 pub bits: u64,
1013}
1014
1015impl Record {
1016 #[must_use]
1018 pub fn pad(&self) -> u64 {
1019 self.bytes.len() as u64 * 8 - self.bits
1020 }
1021
1022 #[must_use]
1024 pub fn bit_string(&self) -> String {
1025 (0..self.bits)
1026 .map(|i| {
1027 let b = (self.bytes[(i / 8) as usize] >> (7 - i % 8)) & 1;
1028 if b == 1 { '1' } else { '0' }
1029 })
1030 .collect()
1031 }
1032}
1033
1034#[derive(Debug, Clone, Default)]
1037pub struct BitWriter {
1038 bytes: Vec<u8>,
1039 len: u64,
1040}
1041
1042impl BitWriter {
1043 #[must_use]
1044 pub fn new() -> Self {
1045 Self::default()
1046 }
1047
1048 pub fn push(&mut self, v: u64, width: u32) {
1051 for i in (0..width).rev() {
1052 if self.len.is_multiple_of(8) {
1053 self.bytes.push(0);
1054 }
1055 if (v >> i) & 1 == 1 {
1056 let last = self.bytes.len() - 1;
1057 self.bytes[last] |= 0x80 >> (self.len % 8);
1058 }
1059 self.len += 1;
1060 }
1061 }
1062
1063 pub fn bit(&mut self, set: bool) {
1065 self.push(u64::from(set), 1);
1066 }
1067
1068 #[must_use]
1070 pub fn finish(self) -> Record {
1071 Record {
1072 bytes: self.bytes,
1073 bits: self.len,
1074 }
1075 }
1076}
1077
1078#[derive(Debug, Clone)]
1081pub struct BitReader<'a> {
1082 bytes: &'a [u8],
1083 pos: u64,
1084}
1085
1086impl<'a> BitReader<'a> {
1087 #[must_use]
1088 pub fn new(bytes: &'a [u8]) -> Self {
1089 Self { bytes, pos: 0 }
1090 }
1091
1092 fn total(&self) -> u64 {
1093 self.bytes.len() as u64 * 8
1094 }
1095
1096 pub fn take(&mut self, width: u32) -> Result<u64, ReadRefusal> {
1102 if self.pos + u64::from(width) > self.total() {
1103 return Err(ReadRefusal::Length);
1104 }
1105 let mut v = 0u64;
1106 for _ in 0..width {
1107 let b = (self.bytes[(self.pos / 8) as usize] >> (7 - self.pos % 8)) & 1;
1108 v = (v << 1) | u64::from(b);
1109 self.pos += 1;
1110 }
1111 Ok(v)
1112 }
1113
1114 pub fn bit(&mut self) -> Result<bool, ReadRefusal> {
1119 self.take(1).map(|b| b == 1)
1120 }
1121
1122 pub fn later(&self) -> Result<(), ReadRefusal> {
1128 if self.total() <= self.pos {
1129 Err(ReadRefusal::Length)
1130 } else {
1131 Ok(())
1132 }
1133 }
1134
1135 pub fn end(mut self) -> Result<(), ReadRefusal> {
1141 if self.bytes.len() as u64 != self.pos.div_ceil(8) {
1142 return Err(ReadRefusal::Length);
1143 }
1144 while self.pos < self.total() {
1145 if self.take(1)? == 1 {
1146 return Err(ReadRefusal::Pad);
1147 }
1148 }
1149 Ok(())
1150 }
1151}
1152
1153pub fn json_decimal(v: &Value) -> Result<Decimal, WriteRefusal> {
1163 match v {
1164 Value::String(s) => Decimal::parse_input(s).ok_or(WriteRefusal::Value),
1165 Value::Number(n) => Decimal::parse_input(&n.to_string()).ok_or(WriteRefusal::Value),
1168 _ => Err(WriteRefusal::Value),
1169 }
1170}
1171
1172pub fn json_integer(v: &Value) -> Result<i128, WriteRefusal> {
1182 match v {
1183 Value::Number(n) => {
1184 if let Some(i) = n.as_i64() {
1185 Ok(i128::from(i))
1186 } else if let Some(u) = n.as_u64() {
1187 Ok(i128::from(u))
1188 } else {
1189 if n.as_f64().unwrap_or(0.0).abs() >= 2f64.powi(63) {
1191 Err(WriteRefusal::Range)
1192 } else {
1193 Err(WriteRefusal::Value)
1194 }
1195 }
1196 }
1197 _ => Err(WriteRefusal::Value),
1198 }
1199}
1200
1201pub fn int_code(x: i128, minimum: i64, maximum: i64) -> Result<u64, WriteRefusal> {
1207 if x < i128::from(minimum) || x > i128::from(maximum) {
1208 return Err(WriteRefusal::Range);
1209 }
1210 u64::try_from(x - i128::from(minimum)).map_err(|_| WriteRefusal::Range)
1211}
1212
1213pub fn int_value(code: u64, minimum: i64, maximum: i64) -> Result<i128, ReadRefusal> {
1219 let span = i128::from(maximum) - i128::from(minimum);
1220 if i128::from(code) > span {
1221 return Err(ReadRefusal::Code);
1222 }
1223 Ok(i128::from(minimum) + i128::from(code))
1224}
1225
1226pub fn fixed_code(
1233 x: &Decimal,
1234 minimum: &Decimal,
1235 resolution: &Decimal,
1236 values: u128,
1237) -> Result<u64, WriteRefusal> {
1238 match x.sub(minimum).div_round_even(resolution).to_u128() {
1239 Some(c) if c < values => u64::try_from(c).map_err(|_| WriteRefusal::Range),
1240 _ => Err(WriteRefusal::Range),
1241 }
1242}
1243
1244pub fn fixed_value(
1250 code: u64,
1251 minimum: &Decimal,
1252 resolution: &Decimal,
1253 values: u128,
1254) -> Result<Decimal, ReadRefusal> {
1255 if u128::from(code) >= values {
1256 return Err(ReadRefusal::Code);
1257 }
1258 Ok(minimum.add(&resolution.mul_int(&BigInt::from(code))))
1259}
1260
1261#[derive(Debug, Clone, PartialEq, Eq)]
1264pub struct Fixed {
1265 pub minimum: Decimal,
1266 pub resolution: Decimal,
1267 pub values: u128,
1269}
1270
1271impl Fixed {
1272 #[must_use]
1276 pub fn new(minimum: &str, resolution: &str, values: u128) -> Self {
1277 Self {
1278 minimum: Decimal::parse(minimum).expect("a linted decimal"),
1279 resolution: Decimal::parse(resolution).expect("a linted decimal"),
1280 values,
1281 }
1282 }
1283
1284 pub fn code(&self, x: &Decimal) -> Result<u64, WriteRefusal> {
1289 fixed_code(x, &self.minimum, &self.resolution, self.values)
1290 }
1291
1292 pub fn value(&self, code: u64) -> Result<Decimal, ReadRefusal> {
1297 fixed_value(code, &self.minimum, &self.resolution, self.values)
1298 }
1299}
1300
1301pub fn time_code(t: i128, epoch: Option<i64>, ms: bool) -> Result<u64, WriteRefusal> {
1310 let e = epoch.unwrap_or(DEFAULT_EPOCH);
1311 let delta = t - 1000 * i128::from(e);
1312 let (s, m) = (delta.div_euclid(1000), delta.rem_euclid(1000));
1313 let s = u32::try_from(s).map_err(|_| WriteRefusal::Range)?;
1314 let m = u64::try_from(m).unwrap_or(0);
1315 Ok(if ms {
1316 (u64::from(s) << 10) | m
1317 } else {
1318 u64::from(s)
1319 })
1320}
1321
1322pub fn time_value(code: u64, epoch: Option<i64>, ms: bool) -> Result<i128, ReadRefusal> {
1330 let (s, m) = if ms {
1331 (code >> 10, code & 0x3ff)
1332 } else {
1333 (code, 0)
1334 };
1335 if m >= 1000 {
1336 return Err(ReadRefusal::Code);
1337 }
1338 let e = epoch.unwrap_or(DEFAULT_EPOCH);
1339 Ok(1000 * i128::from(e) + 1000 * i128::from(s) + i128::from(m))
1340}
1341
1342impl Layout {
1343 fn new(items: Vec<Item>) -> Self {
1344 let mut form = Vec::new();
1345 for it in &items {
1346 match it {
1347 Item::Marker => {
1348 form.push(Value::from(MARKER));
1349 break;
1350 }
1351 Item::Field(f) => form.push(f.form()),
1352 }
1353 }
1354 let form = Value::Array(form);
1355 let sha256 = Sha256::digest(crate::schema::jcs(&form)).into();
1356 Self {
1357 items,
1358 form,
1359 sha256,
1360 }
1361 }
1362
1363 #[must_use]
1365 pub fn form(&self) -> &Value {
1366 &self.form
1367 }
1368
1369 #[must_use]
1371 pub fn sha256_hex(&self) -> String {
1372 let mut s = String::with_capacity(64);
1373 for b in self.sha256 {
1374 let _ = write!(s, "{b:02x}");
1375 }
1376 s
1377 }
1378
1379 #[must_use]
1381 pub fn tag(&self) -> u8 {
1382 self.sha256[31] & 0x0f
1383 }
1384
1385 #[must_use]
1387 pub fn slots(&self) -> Vec<Slot> {
1388 let (mut pos, mut fixed) = (0u64, true);
1389 let mut out = Vec::new();
1390 for it in &self.items {
1391 let offset = fixed.then_some(pos);
1392 match it {
1393 Item::Marker => {
1394 out.push(Slot {
1395 name: None,
1396 width: 1,
1397 optional: false,
1398 offset,
1399 });
1400 fixed = false;
1401 }
1402 Item::Field(f) => {
1403 out.push(Slot {
1404 name: Some(f.name.clone()),
1405 width: f.width,
1406 optional: f.optional,
1407 offset,
1408 });
1409 if f.optional {
1410 fixed = false;
1411 } else {
1412 pos += u64::from(f.width);
1413 }
1414 }
1415 }
1416 }
1417 out
1418 }
1419
1420 #[must_use]
1423 pub fn min_bits(&self) -> u64 {
1424 let mut n = 0;
1425 for it in &self.items {
1426 match it {
1427 Item::Marker => return n + 1,
1428 Item::Field(f) if f.optional => n += 1,
1429 Item::Field(f) => n += u64::from(f.width),
1430 }
1431 }
1432 n
1433 }
1434
1435 #[must_use]
1438 pub fn max_bits(&self) -> u64 {
1439 self.items
1440 .iter()
1441 .map(|it| match it {
1442 Item::Marker => 1,
1443 Item::Field(f) => u64::from(f.width) + u64::from(f.optional),
1444 })
1445 .sum()
1446 }
1447
1448 pub fn fields(&self) -> impl Iterator<Item = &Field> {
1450 self.items.iter().filter_map(|it| match it {
1451 Item::Field(f) => Some(f),
1452 Item::Marker => None,
1453 })
1454 }
1455
1456 pub fn write(&self, value: &Value, epoch: Option<i64>) -> Result<Record, WriteRefusal> {
1463 let Value::Object(obj) = value else {
1464 return Err(WriteRefusal::Value);
1465 };
1466 if obj
1467 .keys()
1468 .any(|k| !self.fields().any(|f| f.name == k.as_str()))
1469 {
1470 return Err(WriteRefusal::Unknown);
1471 }
1472 let mut bits = BitWriter::new();
1473 for (i, it) in self.items.iter().enumerate() {
1474 match it {
1475 Item::Marker => {
1476 let later = self.items[i + 1..].iter().any(|x| match x {
1477 Item::Field(f) => obj.contains_key(&f.name),
1478 Item::Marker => false,
1479 });
1480 bits.bit(later);
1481 if !later {
1482 break;
1483 }
1484 }
1485 Item::Field(f) => match obj.get(&f.name) {
1486 None if f.optional => bits.bit(false),
1487 None => return Err(WriteRefusal::Missing),
1488 Some(v) => {
1489 let code = f.code(v, epoch)?;
1490 if f.optional {
1491 bits.bit(true);
1492 }
1493 bits.push(code, f.width);
1494 }
1495 },
1496 }
1497 }
1498 Ok(bits.finish())
1499 }
1500
1501 pub fn read(&self, tag: u8, bytes: &[u8], epoch: Option<i64>) -> Result<Value, ReadRefusal> {
1508 let mut out = Map::new();
1509 self.walk(tag, bytes, |f, code| {
1510 out.insert(f.name.clone(), f.value(code, epoch)?);
1511 Ok(())
1512 })?;
1513 Ok(Value::Object(out))
1514 }
1515
1516 pub fn check(&self, tag: u8, bytes: &[u8]) -> Result<(), ReadRefusal> {
1522 self.walk(tag, bytes, |f, code| f.check_code(code))
1523 }
1524
1525 fn walk(
1528 &self,
1529 tag: u8,
1530 bytes: &[u8],
1531 mut each: impl FnMut(&Field, u64) -> Result<(), ReadRefusal>,
1532 ) -> Result<(), ReadRefusal> {
1533 if tag != self.tag() {
1534 return Err(ReadRefusal::Tag);
1535 }
1536 let mut r = BitReader::new(bytes);
1537 let mut set_marker = false;
1538 let mut present_after = false;
1539 let last = self.items.len().saturating_sub(1);
1540 for (i, it) in self.items.iter().enumerate() {
1541 match it {
1542 Item::Marker => {
1543 if !r.bit()? {
1544 break;
1545 }
1546 if i == last {
1547 return r.later();
1549 }
1550 set_marker = true;
1551 present_after = false;
1552 }
1553 Item::Field(f) => {
1554 if f.optional && !r.bit()? {
1555 continue;
1556 }
1557 let code = r.take(f.width)?;
1558 each(f, code)?;
1559 present_after = true;
1560 }
1561 }
1562 }
1563 if set_marker && !present_after {
1564 return Err(ReadRefusal::Extension);
1565 }
1566 r.end()
1567 }
1568}
1569
1570impl Field {
1571 pub fn code(&self, v: &Value, epoch: Option<i64>) -> Result<u64, WriteRefusal> {
1578 let reserved = |list: &[&'static str], s: &str| {
1579 reserved_code(self.width, list, s).ok_or(WriteRefusal::Value)
1580 };
1581 match &self.kind {
1582 FieldKind::Int {
1583 minimum,
1584 maximum,
1585 reserved: res,
1586 } => {
1587 if let Value::String(s) = v
1588 && RESERVED.contains(&s.as_str())
1589 {
1590 return reserved(res, s);
1591 }
1592 int_code(json_integer(v)?, *minimum, *maximum)
1593 }
1594 FieldKind::Fixed {
1595 minimum,
1596 resolution,
1597 reserved: res,
1598 values,
1599 ..
1600 } => {
1601 if let Value::String(s) = v
1602 && RESERVED.contains(&s.as_str())
1603 {
1604 return reserved(res, s);
1605 }
1606 fixed_code(&json_decimal(v)?, minimum, resolution, *values)
1607 }
1608 FieldKind::Enum { values, escape } => match v {
1609 Value::Null if *escape => Ok(self.top()),
1610 Value::String(s) => values
1611 .iter()
1612 .position(|x| x == s)
1613 .map(|i| i as u64)
1614 .ok_or(WriteRefusal::Value),
1615 _ => Err(WriteRefusal::Value),
1616 },
1617 FieldKind::Bool => v.as_bool().map(u64::from).ok_or(WriteRefusal::Value),
1618 FieldKind::Counter => {
1619 let c = json_integer(v)?;
1620 u64::try_from(c).map_err(|_| WriteRefusal::Range)
1621 }
1622 FieldKind::Time { ms } => time_code(json_integer(v)?, epoch, *ms),
1623 }
1624 }
1625
1626 #[must_use]
1630 pub fn reserved_name(&self, code: u64) -> Option<&'static str> {
1631 let list = match &self.kind {
1632 FieldKind::Int { reserved, .. } | FieldKind::Fixed { reserved, .. } => reserved,
1633 _ => return None,
1634 };
1635 list.iter()
1636 .enumerate()
1637 .find(|(i, _)| code == self.reserved_code(*i))
1638 .map(|(_, r)| *r)
1639 }
1640
1641 pub fn value(&self, code: u64, epoch: Option<i64>) -> Result<Value, ReadRefusal> {
1648 if let Some(r) = self.reserved_name(code) {
1649 return Ok(Value::from(r));
1650 }
1651 match &self.kind {
1652 FieldKind::Int {
1653 minimum, maximum, ..
1654 } => {
1655 let v = int_value(code, *minimum, *maximum)?;
1656 Ok(i64::try_from(v).map_or(Value::Null, Value::from))
1657 }
1658 FieldKind::Fixed {
1659 minimum,
1660 resolution,
1661 values,
1662 ..
1663 } => fixed_value(code, minimum, resolution, *values)
1664 .map(|x| Value::String(x.to_string())),
1665 FieldKind::Enum { values, escape } => match usize::try_from(code) {
1666 Ok(i) if i < values.len() => Ok(Value::String(values[i].clone())),
1667 _ if *escape => Ok(Value::Null),
1668 _ => Err(ReadRefusal::Code),
1669 },
1670 FieldKind::Bool => Ok(Value::Bool(code == 1)),
1671 FieldKind::Counter => Ok(Value::from(code)),
1672 FieldKind::Time { ms } => {
1673 let t = time_value(code, epoch, *ms)?;
1674 i64::try_from(t)
1675 .map(Value::from)
1676 .map_err(|_| ReadRefusal::Epoch)
1677 }
1678 }
1679 }
1680
1681 pub fn check_code(&self, code: u64) -> Result<(), ReadRefusal> {
1687 if self.reserved_name(code).is_some() {
1688 return Ok(());
1689 }
1690 let used = match &self.kind {
1691 FieldKind::Int {
1692 minimum, maximum, ..
1693 } => int_value(code, *minimum, *maximum).is_ok(),
1694 FieldKind::Fixed { values, .. } => u128::from(code) < *values,
1695 FieldKind::Enum { values, escape } => *escape || code < values.len() as u64,
1696 FieldKind::Bool | FieldKind::Counter => true,
1697 FieldKind::Time { ms } => !*ms || code & 0x3ff < 1000,
1698 };
1699 if used { Ok(()) } else { Err(ReadRefusal::Code) }
1700 }
1701}
1702
1703pub fn layout_in(doc: &Value, name: &str) -> Result<Layout, String> {
1710 let read = PackedDoc::read(doc);
1711 match read.types.get(name) {
1712 Some(Some(layout)) => Ok(layout.clone()),
1713 Some(None) => Err(format!(
1714 "packed:{name}'s declaration does not read ({})",
1715 read.findings
1716 .iter()
1717 .map(|f| f.code)
1718 .collect::<Vec<_>>()
1719 .join(", ")
1720 )),
1721 None => Err(format!("the packed document defines no types/{name}")),
1722 }
1723}
1724
1725#[cfg(test)]
1726mod tests {
1727 use serde_json::json;
1728
1729 use super::*;
1730
1731 #[test]
1732 fn half_a_resolution_is_exact() {
1733 for (r, half) in [
1734 ("100", "50"),
1735 ("0.25", "0.125"),
1736 ("1", "0.5"),
1737 ("0.001", "0.0005"),
1738 ] {
1739 assert_eq!(Decimal::parse(r).unwrap().half().to_string(), half);
1740 }
1741 }
1742
1743 fn codes(doc: &Value) -> Vec<&'static str> {
1744 let mut c: Vec<_> = PackedDoc::read(doc)
1745 .findings
1746 .iter()
1747 .map(|f| f.code)
1748 .collect();
1749 c.sort_unstable();
1750 c
1751 }
1752
1753 #[test]
1754 fn decimals_read_exactly_and_write_shortest() {
1755 for (s, want) in [
1756 ("0", "0"),
1757 ("-0", "0"),
1758 ("2.00", "2"),
1759 ("-40", "-40"),
1760 ("0.10", "0.1"),
1761 ("1013.2", "1013.2"),
1762 ] {
1763 assert_eq!(Decimal::parse(s).unwrap().to_string(), want, "{s}");
1764 }
1765 for bad in ["", "01", "1.", ".5", "+1", "1e3", "1,5", "--1"] {
1766 assert!(Decimal::parse(bad).is_none(), "{bad}");
1767 }
1768 assert_eq!(Decimal::parse_input("5e-1").unwrap().to_string(), "0.5");
1769 assert_eq!(Decimal::parse_input("1.5E+2").unwrap().to_string(), "150");
1770 assert_eq!(
1771 Decimal::parse_input("1e21").unwrap().to_string(),
1772 "1000000000000000000000"
1773 );
1774 assert!(Decimal::parse_input("1e999999").is_none());
1775 }
1776
1777 #[test]
1778 fn ties_go_to_the_even_code() {
1779 let half = Decimal::parse("0.5").unwrap();
1780 let r = |s: &str| {
1781 Decimal::parse_input(s)
1782 .unwrap()
1783 .div_round_even(&half)
1784 .to_string()
1785 };
1786 assert_eq!(r("0.25"), "0");
1787 assert_eq!(r("0.75"), "2");
1788 assert_eq!(r("-0.25"), "0");
1789 assert_eq!(r("-0.75"), "-2");
1790 assert_eq!(r("0.2500000000000000000000000001"), "1");
1791 }
1792
1793 #[test]
1794 fn the_report_sensor_record_is_40_bits() {
1795 let doc = json!({"types": {"Sensor": {"fields": [
1796 {"name": "temperature", "type": "fixed", "minimum": "-40", "maximum": "85", "resolution": "0.1"},
1797 {"name": "humidity", "type": "fixed", "minimum": "0", "maximum": "100", "resolution": "0.5"},
1798 {"name": "pressure", "type": "fixed", "minimum": "300", "maximum": "1100", "resolution": "0.1"},
1799 {"name": "battery", "type": "fixed", "minimum": "2.00", "maximum": "4.20", "resolution": "0.01"}
1800 ]}}});
1801 let p = PackedDoc::read(&doc);
1802 assert!(p.findings.is_empty(), "{:?}", p.findings);
1803 let l = p.types["Sensor"].clone().unwrap();
1804 assert_eq!((l.min_bits(), l.max_bits()), (40, 40));
1805 let rec = l
1806 .write(
1807 &json!({"temperature": "21.5", "humidity": "43.5", "pressure": "1013.2", "battery": "3.70"}),
1808 None,
1809 )
1810 .unwrap();
1811 assert_eq!(rec.bytes, [0x4c, 0xea, 0xfb, 0xdc, 0xaa]);
1812 assert_eq!(rec.pad(), 0);
1813 let back = l.read(l.tag(), &rec.bytes, None).unwrap();
1814 assert_eq!(back["battery"], "3.7");
1815 assert_eq!(l.read(l.tag() ^ 1, &rec.bytes, None), Err(ReadRefusal::Tag));
1816 assert_eq!(
1817 l.read(l.tag(), &rec.bytes[..4], None),
1818 Err(ReadRefusal::Length)
1819 );
1820 }
1821
1822 #[test]
1823 fn lints_follow_cascade_seven() {
1824 assert_eq!(codes(&json!([])), ["E038"]);
1825 assert_eq!(codes(&json!({"types": {}, "x": 1})), ["E038"]);
1826 assert_eq!(codes(&json!({"types": {"bad": {"fields": []}}})), ["E038"]);
1827 assert_eq!(codes(&json!({"types": {"A": {"fields": []}}})), ["E039"]);
1828 assert_eq!(
1829 codes(&json!({"types": {"A": {"fields": [{"name": "a", "type": "float"}]}}})),
1830 ["E043"]
1831 );
1832 assert_eq!(
1833 codes(
1834 &json!({"types": {"A": {"fields": [{"name": "a", "type": "int", "minimum": 1}]}}})
1835 ),
1836 ["E038"]
1837 );
1838 assert_eq!(
1839 codes(&json!({"types": {"A": {"fields": [
1840 {"name": "a", "type": "int", "minimum": 2, "maximum": 1},
1841 {"name": "b", "type": "fixed", "minimum": "0", "maximum": "1", "resolution": "0.3"},
1842 {"name": "c", "type": "fixed", "minimum": "x", "maximum": "-1", "resolution": "0"},
1843 {"name": "d", "type": "counter", "width": 65},
1844 {"name": "e", "type": "int", "minimum": 0, "maximum": 0},
1845 {"name": "a", "type": "bool"},
1846 {"name": "f", "type": "enum", "values": ["x", "x"]},
1847 "...", "...",
1848 {"name": "g", "type": "bool"}
1849 ]}}})),
1850 [
1851 "E039", "E040", "E040", "E041", "E041", "E042", "E042", "E045", "E045"
1852 ]
1853 );
1854 }
1855
1856 #[test]
1857 fn appending_behind_a_marker_keeps_the_tag() {
1858 let v1 = json!({"types": {"L": {"fields": [{"name": "up", "type": "bool"}, "..."]}}});
1859 let v2 = json!({"types": {"L": {"fields": [
1860 {"name": "up", "type": "bool"}, "...",
1861 {"name": "q", "type": "int", "minimum": 0, "maximum": 100, "optional": true}, "..."
1862 ]}}});
1863 let a = PackedDoc::read(&v1).types["L"].clone().unwrap();
1864 let b = PackedDoc::read(&v2).types["L"].clone().unwrap();
1865 assert_eq!(a.tag(), b.tag());
1866 let new = b.write(&json!({"up": true, "q": 87}), None).unwrap();
1867 assert_eq!(
1868 a.read(a.tag(), &new.bytes, None).unwrap(),
1869 json!({"up": true})
1870 );
1871 let old = a.write(&json!({"up": false}), None).unwrap();
1872 assert_eq!(
1873 b.read(b.tag(), &old.bytes, None).unwrap(),
1874 json!({"up": false})
1875 );
1876 }
1877}