From e326f3c629f697595826cb828a3407f41bcc7faa Mon Sep 17 00:00:00 2001 From: Anand Krishnamoorthi <35780660+anakrish@users.noreply.github.com> Date: Sat, 6 Apr 2024 16:40:57 +0530 Subject: [PATCH] From and From (#196) Provide wrappers around serde_json::from_value and serde_yaml::from_value since they may not be apparent and the user may end up serializing to json/yaml and rereading as a regorus::Value Signed-off-by: Anand Krishnamoorthi --- src/engine.rs | 2 +- src/value.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/engine.rs b/src/engine.rs index 1f66ec1..4eaef8f 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -210,7 +210,7 @@ impl Engine { /// Evaluate rule(s) at given path. /// - /// [`eval_rule`] is often faster than [`eval_query`] and should be preferred if + /// [`Engine::eval_rule`] is often faster than [`Engine::eval_query`] and should be preferred if /// OPA style [`QueryResults`] are not needed. /// /// ``` diff --git a/src/value.rs b/src/value.rs index 5283fee..28cb001 100644 --- a/src/value.rs +++ b/src/value.rs @@ -584,6 +584,55 @@ impl From for Value { } } +impl From for Value { + /// Create a [`Value`] from [`serde_json::Value`]. + /// + /// Returns [`Value::Undefined`] in case of error. + /// ``` + /// # use regorus::*; + /// # fn main() -> anyhow::Result<()> { + /// let json_v = serde_json::json!({ "x":10, "y": 20 }); + /// let v = Value::from(json_v); + /// + /// assert_eq!(v["x"].as_u64()?, 10); + /// assert_eq!(v["y"].as_u64()?, 20); + /// # Ok(()) + /// # } + fn from(v: serde_json::Value) -> Self { + match serde_json::from_value(v) { + Ok(v) => v, + _ => Value::Undefined, + } + } +} + +#[cfg(feature = "yaml")] +impl From for Value { + /// Create a [`Value`] from [`serde_yaml::Value`]. + /// + /// Returns [`Value::Undefined`] in case of error. + /// ``` + /// # use regorus::*; + /// # fn main() -> anyhow::Result<()> { + /// let yaml = " + /// x: 10 + /// y: 20 + /// "; + /// let yaml_v : serde_yaml::Value = serde_yaml::from_str(&yaml).unwrap(); + /// let v = Value::from(yaml_v); + /// + /// assert_eq!(v["x"].as_u64()?, 10); + /// assert_eq!(v["y"].as_u64()?, 20); + /// # Ok(()) + /// # } + fn from(v: serde_yaml::Value) -> Self { + match serde_yaml::from_value(v) { + Ok(v) => v, + _ => Value::Undefined, + } + } +} + impl Value { /// Create a [`Value::Number`] from a string containing numeric representation of a number. ///