use std::collections::BTreeMap;
use crate::RuntimeValue;
use crate::ir::{Storage, TypeDescriptor};
pub const MAX_SAFE_INTEGER: u128 = (1 << 53) - 1;
#[derive(Debug, Clone, PartialEq)]
pub enum Presented {
Undefined,
Null,
Bool(bool),
Number(f64),
BigInt {
negative: bool,
magnitude: u128,
},
Bytes(Vec<u8>),
String(String),
Array(Vec<Presented>),
Object(Vec<(String, Presented)>),
}
impl Presented {
#[must_use]
pub fn big(n: u128) -> Self {
Self::BigInt {
negative: false,
magnitude: n,
}
}
#[must_use]
pub fn signed_big(n: i128) -> Self {
Self::BigInt {
negative: n < 0,
magnitude: n.unsigned_abs(),
}
}
#[must_use]
pub fn whole(n: u128) -> Self {
if n <= MAX_SAFE_INTEGER {
Self::Number(exact_f64(n))
} else {
Self::big(n)
}
}
#[must_use]
pub fn object<K: Into<String>>(fields: impl IntoIterator<Item = (K, Presented)>) -> Self {
Self::Object(fields.into_iter().map(|(k, v)| (k.into(), v)).collect())
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub struct ShapeError(String);
#[must_use]
pub fn plain(value: &RuntimeValue) -> Presented {
match value {
RuntimeValue::Null => Presented::Null,
RuntimeValue::Bool(b) => Presented::Bool(*b),
RuntimeValue::Int(i) => signed_whole(*i),
RuntimeValue::Bytes(b) => Presented::Bytes(b.clone()),
RuntimeValue::String(s) => Presented::String(s.clone()),
RuntimeValue::Array(items) => Presented::Array(items.iter().map(plain).collect()),
RuntimeValue::Object(fields) => {
Presented::Object(fields.iter().map(|(k, v)| (k.clone(), plain(v))).collect())
}
}
}
pub fn typed(value: &RuntimeValue, descriptor: &TypeDescriptor) -> Result<Presented, ShapeError> {
match (descriptor, value) {
(TypeDescriptor::Uint { maxval, .. }, _) => {
let fits = maxval.as_u128().is_some_and(|max| max <= MAX_SAFE_INTEGER);
unsigned(value, !fits)
}
(TypeDescriptor::Counter, _) => unsigned(value, true),
(TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of }, _) => typed(value, of),
(TypeDescriptor::Tuple { types }, RuntimeValue::Null) if types.is_empty() => {
Ok(Presented::Undefined)
}
(TypeDescriptor::Tuple { types }, RuntimeValue::Array(items))
if types.is_empty() && items.is_empty() =>
{
Ok(Presented::Undefined)
}
(TypeDescriptor::Tuple { types }, RuntimeValue::Array(items))
if types.len() == items.len() =>
{
items
.iter()
.zip(types)
.map(|(item, ty)| typed(item, ty))
.collect::<Result<_, _>>()
.map(Presented::Array)
}
(
TypeDescriptor::Vector { elt_type: of, .. }
| TypeDescriptor::List { of }
| TypeDescriptor::Set { of },
RuntimeValue::Array(items),
) => typed_items(items, of),
(TypeDescriptor::Struct { elements, .. }, RuntimeValue::Object(fields)) => elements
.iter()
.map(|element| {
let field = fields.get(&element.name).unwrap_or(&RuntimeValue::Null);
Ok((element.name.clone(), typed(field, &element.field_type)?))
})
.collect::<Result<_, _>>()
.map(Presented::Object),
(TypeDescriptor::Map { value: of, .. }, RuntimeValue::Object(entries)) => {
typed_record(entries, of)
}
(
TypeDescriptor::Tuple { .. }
| TypeDescriptor::Vector { .. }
| TypeDescriptor::List { .. }
| TypeDescriptor::Set { .. }
| TypeDescriptor::Struct { .. }
| TypeDescriptor::Map { .. },
_,
) => Err(ShapeError(format!(
"{value} does not have the shape of its declared type {descriptor:?}"
))),
_ => Ok(plain(value)),
}
}
pub fn stored(value: &RuntimeValue, storage: &Storage) -> Result<Presented, ShapeError> {
match (storage, value) {
(Storage::Counter, _) => unsigned(value, true),
(Storage::Cell { of }, _) => typed(value, of),
(Storage::Map { value: of, .. }, RuntimeValue::Object(entries)) => {
typed_record(entries, of)
}
(Storage::Set { of } | Storage::List { of }, RuntimeValue::Array(items)) => {
typed_items(items, of)
}
(Storage::MerkleTree { .. } | Storage::HistoricMerkleTree { .. }, _) => Ok(plain(value)),
(Storage::Map { .. } | Storage::Set { .. } | Storage::List { .. }, _) => Err(ShapeError(
format!("a ledger collection decoded to {value}, which is not its declared shape"),
)),
}
}
fn typed_items(items: &[RuntimeValue], of: &TypeDescriptor) -> Result<Presented, ShapeError> {
items
.iter()
.map(|item| typed(item, of))
.collect::<Result<_, _>>()
.map(Presented::Array)
}
fn typed_record(
entries: &BTreeMap<String, RuntimeValue>,
of: &TypeDescriptor,
) -> Result<Presented, ShapeError> {
entries
.iter()
.map(|(key, entry)| {
let shown = match entry {
RuntimeValue::Null => Presented::Null,
other => typed(other, of)?,
};
Ok((key.clone(), shown))
})
.collect::<Result<_, _>>()
.map(Presented::Object)
}
fn unsigned(value: &RuntimeValue, big: bool) -> Result<Presented, ShapeError> {
let n: u128 = match value {
RuntimeValue::Int(i) => u128::try_from(*i).ok(),
RuntimeValue::String(s) => s.parse().ok(),
_ => None,
}
.ok_or_else(|| ShapeError(format!("{value} is not an unsigned integer")))?;
Ok(if big {
Presented::big(n)
} else {
Presented::whole(n)
})
}
fn signed_whole(n: i128) -> Presented {
if n.unsigned_abs() <= MAX_SAFE_INTEGER {
let magnitude = exact_f64(n.unsigned_abs());
Presented::Number(if n < 0 { -magnitude } else { magnitude })
} else {
Presented::signed_big(n)
}
}
fn exact_f64(n: u128) -> f64 {
let high = u32::try_from(n >> 32).unwrap_or(0);
let low = u32::try_from(n & 0xffff_ffff).unwrap_or(0);
f64::from(high) * 4_294_967_296.0 + f64::from(low)
}
pub fn to_presented<T: serde::Serialize + ?Sized>(value: &T) -> Result<Presented, ShapeError> {
value.serialize(Shower)
}
impl serde::ser::Error for ShapeError {
fn custom<T: std::fmt::Display>(msg: T) -> Self {
Self(msg.to_string())
}
}
struct Shower;
struct Collect {
items: Vec<Presented>,
fields: Vec<(String, Presented)>,
key: Option<String>,
variant: Option<&'static str>,
}
impl Collect {
fn new(variant: Option<&'static str>) -> Self {
Self {
items: Vec::new(),
fields: Vec::new(),
key: None,
variant,
}
}
fn wrap(&self, inner: Presented) -> Presented {
match self.variant {
Some(variant) => Presented::Object(vec![(variant.to_owned(), inner)]),
None => inner,
}
}
}
fn signed64(n: i64) -> Presented {
signed_whole(i128::from(n))
}
impl serde::Serializer for Shower {
type Ok = Presented;
type Error = ShapeError;
type SerializeSeq = Collect;
type SerializeTuple = Collect;
type SerializeTupleStruct = Collect;
type SerializeTupleVariant = Collect;
type SerializeMap = Collect;
type SerializeStruct = Collect;
type SerializeStructVariant = Collect;
fn serialize_bool(self, v: bool) -> Result<Presented, ShapeError> {
Ok(Presented::Bool(v))
}
fn serialize_i8(self, v: i8) -> Result<Presented, ShapeError> {
Ok(signed64(i64::from(v)))
}
fn serialize_i16(self, v: i16) -> Result<Presented, ShapeError> {
Ok(signed64(i64::from(v)))
}
fn serialize_i32(self, v: i32) -> Result<Presented, ShapeError> {
Ok(signed64(i64::from(v)))
}
fn serialize_i64(self, v: i64) -> Result<Presented, ShapeError> {
Ok(signed64(v))
}
fn serialize_i128(self, v: i128) -> Result<Presented, ShapeError> {
Ok(Presented::signed_big(v))
}
fn serialize_u8(self, v: u8) -> Result<Presented, ShapeError> {
Ok(Presented::whole(u128::from(v)))
}
fn serialize_u16(self, v: u16) -> Result<Presented, ShapeError> {
Ok(Presented::whole(u128::from(v)))
}
fn serialize_u32(self, v: u32) -> Result<Presented, ShapeError> {
Ok(Presented::whole(u128::from(v)))
}
fn serialize_u64(self, v: u64) -> Result<Presented, ShapeError> {
Ok(Presented::whole(u128::from(v)))
}
fn serialize_u128(self, v: u128) -> Result<Presented, ShapeError> {
Ok(Presented::big(v))
}
fn serialize_f32(self, v: f32) -> Result<Presented, ShapeError> {
Ok(Presented::Number(f64::from(v)))
}
fn serialize_f64(self, v: f64) -> Result<Presented, ShapeError> {
Ok(Presented::Number(v))
}
fn serialize_char(self, v: char) -> Result<Presented, ShapeError> {
Ok(Presented::String(v.to_string()))
}
fn serialize_str(self, v: &str) -> Result<Presented, ShapeError> {
Ok(Presented::String(v.to_owned()))
}
fn serialize_bytes(self, v: &[u8]) -> Result<Presented, ShapeError> {
Ok(Presented::Bytes(v.to_vec()))
}
fn serialize_none(self) -> Result<Presented, ShapeError> {
Ok(Presented::Null)
}
fn serialize_some<T: serde::Serialize + ?Sized>(
self,
value: &T,
) -> Result<Presented, ShapeError> {
value.serialize(self)
}
fn serialize_unit(self) -> Result<Presented, ShapeError> {
Ok(Presented::Undefined)
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<Presented, ShapeError> {
Ok(Presented::Null)
}
fn serialize_unit_variant(
self,
_name: &'static str,
_index: u32,
variant: &'static str,
) -> Result<Presented, ShapeError> {
Ok(Presented::String(variant.to_owned()))
}
fn serialize_newtype_struct<T: serde::Serialize + ?Sized>(
self,
_name: &'static str,
value: &T,
) -> Result<Presented, ShapeError> {
value.serialize(self)
}
fn serialize_newtype_variant<T: serde::Serialize + ?Sized>(
self,
_name: &'static str,
_index: u32,
variant: &'static str,
value: &T,
) -> Result<Presented, ShapeError> {
Ok(Presented::Object(vec![(
variant.to_owned(),
value.serialize(self)?,
)]))
}
fn serialize_seq(self, _len: Option<usize>) -> Result<Collect, ShapeError> {
Ok(Collect::new(None))
}
fn serialize_tuple(self, _len: usize) -> Result<Collect, ShapeError> {
Ok(Collect::new(None))
}
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Collect, ShapeError> {
Ok(Collect::new(None))
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Collect, ShapeError> {
Ok(Collect::new(Some(variant)))
}
fn serialize_map(self, _len: Option<usize>) -> Result<Collect, ShapeError> {
Ok(Collect::new(None))
}
fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Collect, ShapeError> {
Ok(Collect::new(None))
}
fn serialize_struct_variant(
self,
_name: &'static str,
_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Collect, ShapeError> {
Ok(Collect::new(Some(variant)))
}
}
impl serde::ser::SerializeSeq for Collect {
type Ok = Presented;
type Error = ShapeError;
fn serialize_element<T: serde::Serialize + ?Sized>(
&mut self,
value: &T,
) -> Result<(), ShapeError> {
self.items.push(value.serialize(Shower)?);
Ok(())
}
fn end(self) -> Result<Presented, ShapeError> {
Ok(Presented::Array(self.items))
}
}
impl serde::ser::SerializeTuple for Collect {
type Ok = Presented;
type Error = ShapeError;
fn serialize_element<T: serde::Serialize + ?Sized>(
&mut self,
value: &T,
) -> Result<(), ShapeError> {
serde::ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Presented, ShapeError> {
serde::ser::SerializeSeq::end(self)
}
}
impl serde::ser::SerializeTupleStruct for Collect {
type Ok = Presented;
type Error = ShapeError;
fn serialize_field<T: serde::Serialize + ?Sized>(
&mut self,
value: &T,
) -> Result<(), ShapeError> {
serde::ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Presented, ShapeError> {
serde::ser::SerializeSeq::end(self)
}
}
impl serde::ser::SerializeTupleVariant for Collect {
type Ok = Presented;
type Error = ShapeError;
fn serialize_field<T: serde::Serialize + ?Sized>(
&mut self,
value: &T,
) -> Result<(), ShapeError> {
self.items.push(value.serialize(Shower)?);
Ok(())
}
fn end(self) -> Result<Presented, ShapeError> {
let inner = Presented::Array(self.items.clone());
Ok(self.wrap(inner))
}
}
impl serde::ser::SerializeMap for Collect {
type Ok = Presented;
type Error = ShapeError;
fn serialize_key<T: serde::Serialize + ?Sized>(&mut self, key: &T) -> Result<(), ShapeError> {
self.key = Some(match key.serialize(Shower)? {
Presented::String(s) => s,
Presented::Number(n) => format!("{n}"),
Presented::BigInt {
negative,
magnitude,
} => format!("{}{magnitude}", if negative { "-" } else { "" }),
other => {
return Err(ShapeError(format!(
"a map key is a string or an integer, not {other:?}"
)));
}
});
Ok(())
}
fn serialize_value<T: serde::Serialize + ?Sized>(
&mut self,
value: &T,
) -> Result<(), ShapeError> {
let key = self
.key
.take()
.ok_or_else(|| ShapeError("a map value without its key".to_owned()))?;
self.fields.push((key, value.serialize(Shower)?));
Ok(())
}
fn end(self) -> Result<Presented, ShapeError> {
Ok(Presented::Object(self.fields))
}
}
impl serde::ser::SerializeStruct for Collect {
type Ok = Presented;
type Error = ShapeError;
fn serialize_field<T: serde::Serialize + ?Sized>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), ShapeError> {
self.fields.push((key.to_owned(), value.serialize(Shower)?));
Ok(())
}
fn end(self) -> Result<Presented, ShapeError> {
Ok(Presented::Object(self.fields))
}
}
impl serde::ser::SerializeStructVariant for Collect {
type Ok = Presented;
type Error = ShapeError;
fn serialize_field<T: serde::Serialize + ?Sized>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), ShapeError> {
self.fields.push((key.to_owned(), value.serialize(Shower)?));
Ok(())
}
fn end(self) -> Result<Presented, ShapeError> {
let inner = Presented::Object(self.fields.clone());
Ok(self.wrap(inner))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ir::IntLit;
fn uint(max: u128) -> TypeDescriptor {
TypeDescriptor::Uint {
maxval: IntLit::from_u128(max),
alignment_bytes: None,
}
}
#[test]
fn a_uint_takes_its_type_from_its_bound_not_its_value() {
assert_eq!(
typed(&RuntimeValue::Int(5), &uint(255)),
Ok(Presented::Number(5.0))
);
assert_eq!(
typed(&RuntimeValue::Int(5), &uint(u128::from(u64::MAX))),
Ok(Presented::big(5))
);
assert_eq!(
typed(&RuntimeValue::Int(5), &TypeDescriptor::Counter),
Ok(Presented::big(5))
);
let wide = RuntimeValue::String(u128::MAX.to_string());
assert_eq!(
typed(&wide, &uint(u128::MAX)),
Ok(Presented::big(u128::MAX))
);
}
#[test]
fn an_empty_tuple_is_undefined_and_a_mismatch_is_named() {
let unit = TypeDescriptor::Tuple { types: Vec::new() };
assert_eq!(typed(&RuntimeValue::Null, &unit), Ok(Presented::Undefined));
assert_eq!(
typed(&RuntimeValue::Array(Vec::new()), &unit),
Ok(Presented::Undefined)
);
let pair = TypeDescriptor::Tuple {
types: vec![TypeDescriptor::Boolean, TypeDescriptor::Boolean],
};
assert!(typed(&RuntimeValue::Bool(true), &pair).is_err());
}
#[test]
fn plain_integers_go_by_magnitude() {
assert_eq!(plain(&RuntimeValue::Int(-3)), Presented::Number(-3.0));
let past = i128::try_from(MAX_SAFE_INTEGER).unwrap() + 1;
assert_eq!(
plain(&RuntimeValue::Int(-past)),
Presented::signed_big(-past)
);
}
#[test]
fn a_counter_ledger_field_is_big_and_a_set_entry_stays_null() {
assert_eq!(
stored(&RuntimeValue::Int(2), &Storage::Counter),
Ok(Presented::big(2))
);
let map = Storage::Map {
key: TypeDescriptor::Boolean,
value: uint(255),
};
let entries = RuntimeValue::Object(
[
("a".to_owned(), RuntimeValue::Int(1)),
("b".to_owned(), RuntimeValue::Null),
]
.into_iter()
.collect(),
);
assert_eq!(
stored(&entries, &map),
Ok(Presented::object([
("a", Presented::Number(1.0)),
("b", Presented::Null)
]))
);
}
#[test]
fn a_result_struct_shows_its_fields_in_order_with_amounts_big() {
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct Balance {
address: String,
night_available: u128,
height: u64,
memo: Option<String>,
raw: serde_bytes_like::Bytes,
}
mod serde_bytes_like {
pub struct Bytes(pub Vec<u8>);
impl serde::Serialize for Bytes {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_bytes(&self.0)
}
}
}
let shown = to_presented(&Balance {
address: "addr".to_owned(),
night_available: 5,
height: 7,
memo: None,
raw: serde_bytes_like::Bytes(vec![1, 2]),
})
.unwrap();
assert_eq!(
shown,
Presented::object([
("address", Presented::String("addr".to_owned())),
("nightAvailable", Presented::big(5)),
("height", Presented::Number(7.0)),
("memo", Presented::Null),
("raw", Presented::Bytes(vec![1, 2])),
])
);
}
}