1use crate::{2 error::{Error::*, LocError, Result},3 throw, LazyBinding, LazyVal, ObjMember, ObjValue, Val,4};5use jrsonnet_parser::Visibility;6use serde_json::{Map, Number, Value};7use std::{8 collections::HashMap,9 convert::{TryFrom, TryInto},10 rc::Rc,11};1213impl TryFrom<&Val> for Value {14 type Error = LocError;15 fn try_from(v: &Val) -> Result<Self> {16 Ok(match v {17 Val::Bool(b) => Self::Bool(*b),18 Val::Null => Self::Null,19 Val::Str(s) => Self::String((s as &str).into()),20 Val::Num(n) => Self::Number(if n.fract() <= f64::EPSILON {21 (*n as i64).into()22 } else {23 Number::from_f64(*n).expect("to json number")24 }),25 Val::Arr(a) => {26 let mut out = Vec::with_capacity(a.len());27 for item in a.iter() {28 out.push((&item?).try_into()?);29 }30 Self::Array(out)31 }32 Val::Obj(o) => {33 let mut out = Map::new();34 for key in o.visible_fields() {35 out.insert(36 (&key as &str).into(),37 (&o.get(key)?.expect("field exists")).try_into()?,38 );39 }40 Self::Object(out)41 }42 Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),43 })44 }45}4647impl From<&Value> for Val {48 fn from(v: &Value) -> Self {49 match v {50 Value::Null => Self::Null,51 Value::Bool(v) => Self::Bool(*v),52 Value::Number(n) => Self::Num(n.as_f64().expect("as f64")),53 Value::String(s) => Self::Str((s as &str).into()),54 Value::Array(a) => {55 let mut out = Vec::with_capacity(a.len());56 for v in a {57 out.push(LazyVal::new_resolved(v.into()));58 }59 Self::Arr(out.into())60 }61 Value::Object(o) => {62 let mut entries = HashMap::with_capacity(o.len());63 for (k, v) in o {64 entries.insert(65 (k as &str).into(),66 ObjMember {67 add: false,68 visibility: Visibility::Normal,69 invoke: LazyBinding::Bound(LazyVal::new_resolved(v.into())),70 location: None,71 },72 );73 }74 Self::Obj(ObjValue::new(None, Rc::new(entries)))75 }76 }77 }78}