git.delta.rocks / jrsonnet / refs/commits / bc5c3a5e48f5

difftreelog

source

crates/jrsonnet-evaluator/src/integrations/serde.rs2.0 KiBsourcehistory
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) => Value::Bool(*b),18			Val::Null => Value::Null,19			Val::Str(s) => Value::String((&s as &str).into()),20			Val::Num(n) => Value::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::Lazy(v) => (&v.evaluate()?).try_into()?,26			Val::Arr(a) => {27				let mut out = Vec::with_capacity(a.len());28				for item in a.iter() {29					out.push(item.try_into()?);30				}31				Value::Array(out)32			}33			Val::Obj(o) => {34				let mut out = Map::new();35				for key in o.visible_fields() {36					out.insert(37						(&key as &str).into(),38						(&o.get(key)?.expect("field exists")).try_into()?,39					);40				}41				Value::Object(out)42			}43			Val::Func(_) | Val::Intristic(_, _) | Val::NativeExt(_, _) => {44				throw!(RuntimeError("tried to manifest function".into()))45			}46		})47	}48}4950impl From<&Value> for Val {51	fn from(v: &Value) -> Self {52		match v {53			Value::Null => Val::Null,54			Value::Bool(v) => Val::Bool(*v),55			Value::Number(n) => Val::Num(n.as_f64().expect("as f64")),56			Value::String(s) => Val::Str((s as &str).into()),57			Value::Array(a) => {58				let mut out = Vec::with_capacity(a.len());59				for v in a {60					out.push(v.into());61				}62				Val::Arr(Rc::new(out))63			}64			Value::Object(o) => {65				let mut entries = HashMap::with_capacity(o.len());66				for (k, v) in o {67					entries.insert(68						(k as &str).into(),69						ObjMember {70							add: false,71							visibility: Visibility::Normal,72							invoke: LazyBinding::Bound(LazyVal::new_resolved(v.into())),73							location: None,74						},75					);76				}77				Val::Obj(ObjValue::new(None, Rc::new(entries)))78			}79		}80	}81}