1use std::collections::BTreeMap;
13
14use crate::RuntimeValue;
15use crate::ir::{Storage, TypeDescriptor};
16
17pub const MAX_SAFE_INTEGER: u128 = (1 << 53) - 1;
19
20#[derive(Debug, Clone, PartialEq)]
22pub enum Presented {
23 Undefined,
24 Null,
25 Bool(bool),
26 Number(f64),
28 BigInt {
29 negative: bool,
30 magnitude: u128,
31 },
32 Bytes(Vec<u8>),
33 String(String),
34 Array(Vec<Presented>),
35 Object(Vec<(String, Presented)>),
37}
38
39impl Presented {
40 #[must_use]
42 pub fn big(n: u128) -> Self {
43 Self::BigInt {
44 negative: false,
45 magnitude: n,
46 }
47 }
48
49 #[must_use]
51 pub fn signed_big(n: i128) -> Self {
52 Self::BigInt {
53 negative: n < 0,
54 magnitude: n.unsigned_abs(),
55 }
56 }
57
58 #[must_use]
61 pub fn whole(n: u128) -> Self {
62 if n <= MAX_SAFE_INTEGER {
63 Self::Number(exact_f64(n))
64 } else {
65 Self::big(n)
66 }
67 }
68
69 #[must_use]
71 pub fn object<K: Into<String>>(fields: impl IntoIterator<Item = (K, Presented)>) -> Self {
72 Self::Object(fields.into_iter().map(|(k, v)| (k.into(), v)).collect())
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
78#[error("{0}")]
79pub struct ShapeError(String);
80
81#[must_use]
83pub fn plain(value: &RuntimeValue) -> Presented {
84 match value {
85 RuntimeValue::Null => Presented::Null,
86 RuntimeValue::Bool(b) => Presented::Bool(*b),
87 RuntimeValue::Int(i) => signed_whole(*i),
88 RuntimeValue::Bytes(b) => Presented::Bytes(b.clone()),
89 RuntimeValue::String(s) => Presented::String(s.clone()),
90 RuntimeValue::Array(items) => Presented::Array(items.iter().map(plain).collect()),
91 RuntimeValue::Object(fields) => {
92 Presented::Object(fields.iter().map(|(k, v)| (k.clone(), plain(v))).collect())
93 }
94 }
95}
96
97pub fn typed(value: &RuntimeValue, descriptor: &TypeDescriptor) -> Result<Presented, ShapeError> {
103 match (descriptor, value) {
104 (TypeDescriptor::Uint { maxval, .. }, _) => {
105 let fits = maxval.as_u128().is_some_and(|max| max <= MAX_SAFE_INTEGER);
106 unsigned(value, !fits)
107 }
108 (TypeDescriptor::Counter, _) => unsigned(value, true),
109 (TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of }, _) => typed(value, of),
110 (TypeDescriptor::Tuple { types }, RuntimeValue::Null) if types.is_empty() => {
111 Ok(Presented::Undefined)
112 }
113 (TypeDescriptor::Tuple { types }, RuntimeValue::Array(items))
114 if types.is_empty() && items.is_empty() =>
115 {
116 Ok(Presented::Undefined)
117 }
118 (TypeDescriptor::Tuple { types }, RuntimeValue::Array(items))
119 if types.len() == items.len() =>
120 {
121 items
122 .iter()
123 .zip(types)
124 .map(|(item, ty)| typed(item, ty))
125 .collect::<Result<_, _>>()
126 .map(Presented::Array)
127 }
128 (
129 TypeDescriptor::Vector { elt_type: of, .. }
130 | TypeDescriptor::List { of }
131 | TypeDescriptor::Set { of },
132 RuntimeValue::Array(items),
133 ) => typed_items(items, of),
134 (TypeDescriptor::Struct { elements, .. }, RuntimeValue::Object(fields)) => elements
135 .iter()
136 .map(|element| {
137 let field = fields.get(&element.name).unwrap_or(&RuntimeValue::Null);
138 Ok((element.name.clone(), typed(field, &element.field_type)?))
139 })
140 .collect::<Result<_, _>>()
141 .map(Presented::Object),
142 (TypeDescriptor::Map { value: of, .. }, RuntimeValue::Object(entries)) => {
143 typed_record(entries, of)
144 }
145 (
146 TypeDescriptor::Tuple { .. }
147 | TypeDescriptor::Vector { .. }
148 | TypeDescriptor::List { .. }
149 | TypeDescriptor::Set { .. }
150 | TypeDescriptor::Struct { .. }
151 | TypeDescriptor::Map { .. },
152 _,
153 ) => Err(ShapeError(format!(
154 "{value} does not have the shape of its declared type {descriptor:?}"
155 ))),
156 _ => Ok(plain(value)),
157 }
158}
159
160pub fn stored(value: &RuntimeValue, storage: &Storage) -> Result<Presented, ShapeError> {
168 match (storage, value) {
169 (Storage::Counter, _) => unsigned(value, true),
170 (Storage::Cell { of }, _) => typed(value, of),
171 (Storage::Map { value: of, .. }, RuntimeValue::Object(entries)) => {
172 typed_record(entries, of)
173 }
174 (Storage::Set { of } | Storage::List { of }, RuntimeValue::Array(items)) => {
175 typed_items(items, of)
176 }
177 (Storage::MerkleTree { .. } | Storage::HistoricMerkleTree { .. }, _) => Ok(plain(value)),
178 (Storage::Map { .. } | Storage::Set { .. } | Storage::List { .. }, _) => Err(ShapeError(
179 format!("a ledger collection decoded to {value}, which is not its declared shape"),
180 )),
181 }
182}
183
184fn typed_items(items: &[RuntimeValue], of: &TypeDescriptor) -> Result<Presented, ShapeError> {
185 items
186 .iter()
187 .map(|item| typed(item, of))
188 .collect::<Result<_, _>>()
189 .map(Presented::Array)
190}
191
192fn typed_record(
195 entries: &BTreeMap<String, RuntimeValue>,
196 of: &TypeDescriptor,
197) -> Result<Presented, ShapeError> {
198 entries
199 .iter()
200 .map(|(key, entry)| {
201 let shown = match entry {
202 RuntimeValue::Null => Presented::Null,
203 other => typed(other, of)?,
204 };
205 Ok((key.clone(), shown))
206 })
207 .collect::<Result<_, _>>()
208 .map(Presented::Object)
209}
210
211fn unsigned(value: &RuntimeValue, big: bool) -> Result<Presented, ShapeError> {
214 let n: u128 = match value {
215 RuntimeValue::Int(i) => u128::try_from(*i).ok(),
216 RuntimeValue::String(s) => s.parse().ok(),
217 _ => None,
218 }
219 .ok_or_else(|| ShapeError(format!("{value} is not an unsigned integer")))?;
220 Ok(if big {
221 Presented::big(n)
222 } else {
223 Presented::whole(n)
224 })
225}
226
227fn signed_whole(n: i128) -> Presented {
228 if n.unsigned_abs() <= MAX_SAFE_INTEGER {
229 let magnitude = exact_f64(n.unsigned_abs());
230 Presented::Number(if n < 0 { -magnitude } else { magnitude })
231 } else {
232 Presented::signed_big(n)
233 }
234}
235
236fn exact_f64(n: u128) -> f64 {
238 let high = u32::try_from(n >> 32).unwrap_or(0);
239 let low = u32::try_from(n & 0xffff_ffff).unwrap_or(0);
240 f64::from(high) * 4_294_967_296.0 + f64::from(low)
241}
242
243pub fn to_presented<T: serde::Serialize + ?Sized>(value: &T) -> Result<Presented, ShapeError> {
252 value.serialize(Shower)
253}
254
255impl serde::ser::Error for ShapeError {
256 fn custom<T: std::fmt::Display>(msg: T) -> Self {
257 Self(msg.to_string())
258 }
259}
260
261struct Shower;
263
264struct Collect {
266 items: Vec<Presented>,
267 fields: Vec<(String, Presented)>,
268 key: Option<String>,
269 variant: Option<&'static str>,
271}
272
273impl Collect {
274 fn new(variant: Option<&'static str>) -> Self {
275 Self {
276 items: Vec::new(),
277 fields: Vec::new(),
278 key: None,
279 variant,
280 }
281 }
282
283 fn wrap(&self, inner: Presented) -> Presented {
284 match self.variant {
285 Some(variant) => Presented::Object(vec![(variant.to_owned(), inner)]),
286 None => inner,
287 }
288 }
289}
290
291fn signed64(n: i64) -> Presented {
292 signed_whole(i128::from(n))
293}
294
295impl serde::Serializer for Shower {
296 type Ok = Presented;
297 type Error = ShapeError;
298 type SerializeSeq = Collect;
299 type SerializeTuple = Collect;
300 type SerializeTupleStruct = Collect;
301 type SerializeTupleVariant = Collect;
302 type SerializeMap = Collect;
303 type SerializeStruct = Collect;
304 type SerializeStructVariant = Collect;
305
306 fn serialize_bool(self, v: bool) -> Result<Presented, ShapeError> {
307 Ok(Presented::Bool(v))
308 }
309 fn serialize_i8(self, v: i8) -> Result<Presented, ShapeError> {
310 Ok(signed64(i64::from(v)))
311 }
312 fn serialize_i16(self, v: i16) -> Result<Presented, ShapeError> {
313 Ok(signed64(i64::from(v)))
314 }
315 fn serialize_i32(self, v: i32) -> Result<Presented, ShapeError> {
316 Ok(signed64(i64::from(v)))
317 }
318 fn serialize_i64(self, v: i64) -> Result<Presented, ShapeError> {
319 Ok(signed64(v))
320 }
321 fn serialize_i128(self, v: i128) -> Result<Presented, ShapeError> {
322 Ok(Presented::signed_big(v))
323 }
324 fn serialize_u8(self, v: u8) -> Result<Presented, ShapeError> {
325 Ok(Presented::whole(u128::from(v)))
326 }
327 fn serialize_u16(self, v: u16) -> Result<Presented, ShapeError> {
328 Ok(Presented::whole(u128::from(v)))
329 }
330 fn serialize_u32(self, v: u32) -> Result<Presented, ShapeError> {
331 Ok(Presented::whole(u128::from(v)))
332 }
333 fn serialize_u64(self, v: u64) -> Result<Presented, ShapeError> {
334 Ok(Presented::whole(u128::from(v)))
335 }
336 fn serialize_u128(self, v: u128) -> Result<Presented, ShapeError> {
337 Ok(Presented::big(v))
338 }
339 fn serialize_f32(self, v: f32) -> Result<Presented, ShapeError> {
340 Ok(Presented::Number(f64::from(v)))
341 }
342 fn serialize_f64(self, v: f64) -> Result<Presented, ShapeError> {
343 Ok(Presented::Number(v))
344 }
345 fn serialize_char(self, v: char) -> Result<Presented, ShapeError> {
346 Ok(Presented::String(v.to_string()))
347 }
348 fn serialize_str(self, v: &str) -> Result<Presented, ShapeError> {
349 Ok(Presented::String(v.to_owned()))
350 }
351 fn serialize_bytes(self, v: &[u8]) -> Result<Presented, ShapeError> {
352 Ok(Presented::Bytes(v.to_vec()))
353 }
354 fn serialize_none(self) -> Result<Presented, ShapeError> {
355 Ok(Presented::Null)
356 }
357 fn serialize_some<T: serde::Serialize + ?Sized>(
358 self,
359 value: &T,
360 ) -> Result<Presented, ShapeError> {
361 value.serialize(self)
362 }
363 fn serialize_unit(self) -> Result<Presented, ShapeError> {
364 Ok(Presented::Undefined)
365 }
366 fn serialize_unit_struct(self, _name: &'static str) -> Result<Presented, ShapeError> {
367 Ok(Presented::Null)
368 }
369 fn serialize_unit_variant(
370 self,
371 _name: &'static str,
372 _index: u32,
373 variant: &'static str,
374 ) -> Result<Presented, ShapeError> {
375 Ok(Presented::String(variant.to_owned()))
376 }
377 fn serialize_newtype_struct<T: serde::Serialize + ?Sized>(
378 self,
379 _name: &'static str,
380 value: &T,
381 ) -> Result<Presented, ShapeError> {
382 value.serialize(self)
383 }
384 fn serialize_newtype_variant<T: serde::Serialize + ?Sized>(
385 self,
386 _name: &'static str,
387 _index: u32,
388 variant: &'static str,
389 value: &T,
390 ) -> Result<Presented, ShapeError> {
391 Ok(Presented::Object(vec![(
392 variant.to_owned(),
393 value.serialize(self)?,
394 )]))
395 }
396 fn serialize_seq(self, _len: Option<usize>) -> Result<Collect, ShapeError> {
397 Ok(Collect::new(None))
398 }
399 fn serialize_tuple(self, _len: usize) -> Result<Collect, ShapeError> {
400 Ok(Collect::new(None))
401 }
402 fn serialize_tuple_struct(
403 self,
404 _name: &'static str,
405 _len: usize,
406 ) -> Result<Collect, ShapeError> {
407 Ok(Collect::new(None))
408 }
409 fn serialize_tuple_variant(
410 self,
411 _name: &'static str,
412 _index: u32,
413 variant: &'static str,
414 _len: usize,
415 ) -> Result<Collect, ShapeError> {
416 Ok(Collect::new(Some(variant)))
417 }
418 fn serialize_map(self, _len: Option<usize>) -> Result<Collect, ShapeError> {
419 Ok(Collect::new(None))
420 }
421 fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Collect, ShapeError> {
422 Ok(Collect::new(None))
423 }
424 fn serialize_struct_variant(
425 self,
426 _name: &'static str,
427 _index: u32,
428 variant: &'static str,
429 _len: usize,
430 ) -> Result<Collect, ShapeError> {
431 Ok(Collect::new(Some(variant)))
432 }
433}
434
435impl serde::ser::SerializeSeq for Collect {
436 type Ok = Presented;
437 type Error = ShapeError;
438 fn serialize_element<T: serde::Serialize + ?Sized>(
439 &mut self,
440 value: &T,
441 ) -> Result<(), ShapeError> {
442 self.items.push(value.serialize(Shower)?);
443 Ok(())
444 }
445 fn end(self) -> Result<Presented, ShapeError> {
446 Ok(Presented::Array(self.items))
447 }
448}
449
450impl serde::ser::SerializeTuple for Collect {
451 type Ok = Presented;
452 type Error = ShapeError;
453 fn serialize_element<T: serde::Serialize + ?Sized>(
454 &mut self,
455 value: &T,
456 ) -> Result<(), ShapeError> {
457 serde::ser::SerializeSeq::serialize_element(self, value)
458 }
459 fn end(self) -> Result<Presented, ShapeError> {
460 serde::ser::SerializeSeq::end(self)
461 }
462}
463
464impl serde::ser::SerializeTupleStruct for Collect {
465 type Ok = Presented;
466 type Error = ShapeError;
467 fn serialize_field<T: serde::Serialize + ?Sized>(
468 &mut self,
469 value: &T,
470 ) -> Result<(), ShapeError> {
471 serde::ser::SerializeSeq::serialize_element(self, value)
472 }
473 fn end(self) -> Result<Presented, ShapeError> {
474 serde::ser::SerializeSeq::end(self)
475 }
476}
477
478impl serde::ser::SerializeTupleVariant for Collect {
479 type Ok = Presented;
480 type Error = ShapeError;
481 fn serialize_field<T: serde::Serialize + ?Sized>(
482 &mut self,
483 value: &T,
484 ) -> Result<(), ShapeError> {
485 self.items.push(value.serialize(Shower)?);
486 Ok(())
487 }
488 fn end(self) -> Result<Presented, ShapeError> {
489 let inner = Presented::Array(self.items.clone());
490 Ok(self.wrap(inner))
491 }
492}
493
494impl serde::ser::SerializeMap for Collect {
495 type Ok = Presented;
496 type Error = ShapeError;
497 fn serialize_key<T: serde::Serialize + ?Sized>(&mut self, key: &T) -> Result<(), ShapeError> {
498 self.key = Some(match key.serialize(Shower)? {
499 Presented::String(s) => s,
500 Presented::Number(n) => format!("{n}"),
501 Presented::BigInt {
502 negative,
503 magnitude,
504 } => format!("{}{magnitude}", if negative { "-" } else { "" }),
505 other => {
506 return Err(ShapeError(format!(
507 "a map key is a string or an integer, not {other:?}"
508 )));
509 }
510 });
511 Ok(())
512 }
513 fn serialize_value<T: serde::Serialize + ?Sized>(
514 &mut self,
515 value: &T,
516 ) -> Result<(), ShapeError> {
517 let key = self
518 .key
519 .take()
520 .ok_or_else(|| ShapeError("a map value without its key".to_owned()))?;
521 self.fields.push((key, value.serialize(Shower)?));
522 Ok(())
523 }
524 fn end(self) -> Result<Presented, ShapeError> {
525 Ok(Presented::Object(self.fields))
526 }
527}
528
529impl serde::ser::SerializeStruct for Collect {
530 type Ok = Presented;
531 type Error = ShapeError;
532 fn serialize_field<T: serde::Serialize + ?Sized>(
533 &mut self,
534 key: &'static str,
535 value: &T,
536 ) -> Result<(), ShapeError> {
537 self.fields.push((key.to_owned(), value.serialize(Shower)?));
538 Ok(())
539 }
540 fn end(self) -> Result<Presented, ShapeError> {
541 Ok(Presented::Object(self.fields))
542 }
543}
544
545impl serde::ser::SerializeStructVariant for Collect {
546 type Ok = Presented;
547 type Error = ShapeError;
548 fn serialize_field<T: serde::Serialize + ?Sized>(
549 &mut self,
550 key: &'static str,
551 value: &T,
552 ) -> Result<(), ShapeError> {
553 self.fields.push((key.to_owned(), value.serialize(Shower)?));
554 Ok(())
555 }
556 fn end(self) -> Result<Presented, ShapeError> {
557 let inner = Presented::Object(self.fields.clone());
558 Ok(self.wrap(inner))
559 }
560}
561
562#[cfg(test)]
563mod tests {
564 use super::*;
565 use crate::ir::IntLit;
566
567 fn uint(max: u128) -> TypeDescriptor {
568 TypeDescriptor::Uint {
569 maxval: IntLit::from_u128(max),
570 alignment_bytes: None,
571 }
572 }
573
574 #[test]
575 fn a_uint_takes_its_type_from_its_bound_not_its_value() {
576 assert_eq!(
577 typed(&RuntimeValue::Int(5), &uint(255)),
578 Ok(Presented::Number(5.0))
579 );
580 assert_eq!(
581 typed(&RuntimeValue::Int(5), &uint(u128::from(u64::MAX))),
582 Ok(Presented::big(5))
583 );
584 assert_eq!(
585 typed(&RuntimeValue::Int(5), &TypeDescriptor::Counter),
586 Ok(Presented::big(5))
587 );
588 let wide = RuntimeValue::String(u128::MAX.to_string());
589 assert_eq!(
590 typed(&wide, &uint(u128::MAX)),
591 Ok(Presented::big(u128::MAX))
592 );
593 }
594
595 #[test]
596 fn an_empty_tuple_is_undefined_and_a_mismatch_is_named() {
597 let unit = TypeDescriptor::Tuple { types: Vec::new() };
598 assert_eq!(typed(&RuntimeValue::Null, &unit), Ok(Presented::Undefined));
599 assert_eq!(
600 typed(&RuntimeValue::Array(Vec::new()), &unit),
601 Ok(Presented::Undefined)
602 );
603 let pair = TypeDescriptor::Tuple {
604 types: vec![TypeDescriptor::Boolean, TypeDescriptor::Boolean],
605 };
606 assert!(typed(&RuntimeValue::Bool(true), &pair).is_err());
607 }
608
609 #[test]
610 fn plain_integers_go_by_magnitude() {
611 assert_eq!(plain(&RuntimeValue::Int(-3)), Presented::Number(-3.0));
612 let past = i128::try_from(MAX_SAFE_INTEGER).unwrap() + 1;
613 assert_eq!(
614 plain(&RuntimeValue::Int(-past)),
615 Presented::signed_big(-past)
616 );
617 }
618
619 #[test]
620 fn a_counter_ledger_field_is_big_and_a_set_entry_stays_null() {
621 assert_eq!(
622 stored(&RuntimeValue::Int(2), &Storage::Counter),
623 Ok(Presented::big(2))
624 );
625 let map = Storage::Map {
626 key: TypeDescriptor::Boolean,
627 value: uint(255),
628 };
629 let entries = RuntimeValue::Object(
630 [
631 ("a".to_owned(), RuntimeValue::Int(1)),
632 ("b".to_owned(), RuntimeValue::Null),
633 ]
634 .into_iter()
635 .collect(),
636 );
637 assert_eq!(
638 stored(&entries, &map),
639 Ok(Presented::object([
640 ("a", Presented::Number(1.0)),
641 ("b", Presented::Null)
642 ]))
643 );
644 }
645
646 #[test]
647 fn a_result_struct_shows_its_fields_in_order_with_amounts_big() {
648 #[derive(serde::Serialize)]
649 #[serde(rename_all = "camelCase")]
650 struct Balance {
651 address: String,
652 night_available: u128,
653 height: u64,
654 memo: Option<String>,
655 raw: serde_bytes_like::Bytes,
656 }
657 mod serde_bytes_like {
658 pub struct Bytes(pub Vec<u8>);
659 impl serde::Serialize for Bytes {
660 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
661 s.serialize_bytes(&self.0)
662 }
663 }
664 }
665 let shown = to_presented(&Balance {
666 address: "addr".to_owned(),
667 night_available: 5,
668 height: 7,
669 memo: None,
670 raw: serde_bytes_like::Bytes(vec![1, 2]),
671 })
672 .unwrap();
673 assert_eq!(
674 shown,
675 Presented::object([
676 ("address", Presented::String("addr".to_owned())),
677 ("nightAvailable", Presented::big(5)),
678 ("height", Presented::Number(7.0)),
679 ("memo", Presented::Null),
680 ("raw", Presented::Bytes(vec![1, 2])),
681 ])
682 );
683 }
684}