Skip to content

Commit

Permalink
Implement From<Result> for Value
Browse files Browse the repository at this point in the history
  • Loading branch information
asv7c2 authored and pravic committed Jan 6, 2020
1 parent b36af4e commit 5c96354
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/value.rs
Expand Up @@ -922,6 +922,15 @@ impl<'a> From<&'a [u8]> for Value {
}
}

impl<R, E> From<Result<R, E>> for Value where R: Into<Value>, E: Into<Box<dyn std::error::Error>> {
fn from(val: Result<R, E>) -> Self {
match val {
Ok(r) => r.into(),
Err(e) => Value::error(&e.into().to_string()),
}
}
}

// /// Value from sequence of items satisfying `Into<Value>`.
// impl ::std::iter::FromIterator<Into<Value>> for Value {
// fn from_iter<I: IntoIterator<Item=Into<Value>>>(iterator: I) -> Self {
Expand Down
13 changes: 13 additions & 0 deletions tests/value.rs
Expand Up @@ -209,6 +209,19 @@ fn from_function_works() {
assert!(v.is_native_function());
}

#[test]
fn from_result_works() {
// create Err variant
let result: Result<i32, String> = Err("unknown error".to_string());
let v = Value::from(result);
assert_eq!(v.as_string().unwrap(), "unknown error");

// create Ok variant
let result: Result<i32, String> = Ok(100);
let v = Value::from(result);
assert_eq!(v.to_int().unwrap(), 100);
}

#[test]
fn parse_works() {
let items = ["", "null", "1", "\"2\"", "2.0", "true", "[3, 4]", r##"{"5": 5, "6": 6, seven: "seven"}"##];
Expand Down

0 comments on commit 5c96354

Please sign in to comment.