1use jrsonnet_types::ComplexValType;2use serde_json::{Map, Number, Value};34use crate::{5 error::{Error::*, Result},6 throw,7 typed::Typed,8 ObjValueBuilder, State, Val,9};1011impl Typed for Value {12 const TYPE: &'static ComplexValType = &ComplexValType::Any;1314 fn into_untyped(value: Self, s: State) -> Result<Val> {15 Ok(match value {16 Self::Null => Val::Null,17 Self::Bool(v) => Val::Bool(v),18 Self::Number(n) => Val::Num(n.as_f64().ok_or_else(|| {19 RuntimeError(format!("json number can't be represented as jsonnet: {}", n).into())20 })?),21 Self::String(s) => Val::Str((&s as &str).into()),22 Self::Array(a) => {23 let mut out: Vec<Val> = Vec::with_capacity(a.len());24 for v in a {25 out.push(Self::into_untyped(v, s.clone())?);26 }27 Val::Arr(out.into())28 }29 Self::Object(o) => {30 let mut builder = ObjValueBuilder::with_capacity(o.len());31 for (k, v) in o {32 builder33 .member((&k as &str).into())34 .value(s.clone(), Self::into_untyped(v, s.clone())?)?;35 }36 Val::Obj(builder.build())37 }38 })39 }4041 fn from_untyped(value: Val, s: State) -> Result<Self> {42 Ok(match value {43 Val::Bool(b) => Self::Bool(b),44 Val::Null => Self::Null,45 Val::Str(s) => Self::String((&s as &str).into()),46 Val::Num(n) => Self::Number(if n.fract() <= f64::EPSILON {47 (n as i64).into()48 } else {49 Number::from_f64(n).expect("jsonnet numbers can't be infinite or NaN")50 }),51 Val::Arr(a) => {52 let mut out = Vec::with_capacity(a.len());53 for item in a.iter(s.clone()) {54 out.push(Self::from_untyped(item?, s.clone())?);55 }56 Self::Array(out)57 }58 Val::Obj(o) => {59 let mut out = Map::new();60 for key in o.fields(61 #[cfg(feature = "exp-preserve-order")]62 cfg!(feature = "exp-serde-preserve-order"),63 ) {64 out.insert(65 (&key as &str).into(),66 Self::from_untyped(67 o.get(s.clone(), key)?68 .expect("key is present in fields, so value should exist"),69 s.clone(),70 )?,71 );72 }73 Self::Object(out)74 }75 Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),76 })77 }78}