Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement TryInto for Value #947

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions src/value/mod.rs
Expand Up @@ -880,6 +880,7 @@ mod from;
mod index;
mod partial_eq;
mod ser;
mod try_into;

/// Convert a `T` into `serde_json::Value` which is an enum that can represent
/// any valid JSON data.
Expand Down
163 changes: 163 additions & 0 deletions src/value/try_into.rs
@@ -0,0 +1,163 @@
use core::convert::TryInto;
use alloc::string::String;
use alloc::vec::Vec;
use crate::map::Map;
use crate::error::Error;
use super::Value;

impl TryInto<String> for Value {
type Error = Error;

fn try_into(self) -> Result<String, Error> {
match self {
Value::String(s) => Ok(s),
_ => Err(<Error as serde::de::Error>::custom("value is not a string")),
}
}
}

impl<'a> TryInto<&'a String> for &'a Value {
type Error = Error;

fn try_into(self) -> Result<&'a String, Error> {
match self {
Value::String(s) => Ok(s),
_ => Err(<Error as serde::de::Error>::custom("value is not a string")),
}
}
}

impl<'a> TryInto<&'a str> for &'a Value {
type Error = Error;

fn try_into(self) -> Result<&'a str, Error> {
self.as_str().ok_or_else(|| <Error as serde::de::Error>::custom("value is not a string"))
}
}

impl TryInto<f64> for Value {
type Error = Error;

fn try_into(self) -> Result<f64, Error> {
self.as_f64().ok_or_else(|| <Error as serde::de::Error>::custom("value is not an f64"))
}
}


impl TryInto<f64> for &Value {
type Error = Error;

fn try_into(self) -> Result<f64, Error> {
self.as_f64().ok_or_else(|| <Error as serde::de::Error>::custom("value is not an f64"))
}
}

impl TryInto<i64> for Value {
type Error = Error;

fn try_into(self) -> Result<i64, Error> {
self.as_i64().ok_or_else(|| <Error as serde::de::Error>::custom("value is not an i64"))
}
}

impl TryInto<i64> for &Value {
type Error = Error;

fn try_into(self) -> Result<i64, Error> {
self.as_i64().ok_or_else(|| <Error as serde::de::Error>::custom("value is not an i64"))
}
}

impl TryInto<u64> for Value {
type Error = Error;

fn try_into(self) -> Result<u64, Error> {
self.as_u64().ok_or_else(|| <Error as serde::de::Error>::custom("value is not an u64"))
}
}

impl TryInto<u64> for &Value {
type Error = Error;

fn try_into(self) -> Result<u64, Error> {
self.as_u64().ok_or_else(|| <Error as serde::de::Error>::custom("value is not an u64"))
}
}

impl TryInto<bool> for Value {
type Error = Error;

fn try_into(self) -> Result<bool, Error> {
self.as_bool().ok_or_else(|| <Error as serde::de::Error>::custom("value is not a bool"))
}
}

impl TryInto<bool> for &Value {
type Error = Error;

fn try_into(self) -> Result<bool, Error> {
self.as_bool().ok_or_else(|| <Error as serde::de::Error>::custom("value is not a bool"))
}
}

impl<'a> TryInto<&'a Vec<Value>> for &'a Value {
type Error = Error;

fn try_into(self) -> Result<&'a Vec<Value>, Error> {
self.as_array().ok_or_else(|| <Error as serde::de::Error>::custom("value is not an array"))
}
}

impl<'a> TryInto<&'a [Value]> for &'a Value {
type Error = Error;

fn try_into(self) -> Result<&'a [Value], Error> {
self.as_array().map(|v| v.as_slice()).ok_or_else(|| <Error as serde::de::Error>::custom("value is not an array"))
}
}

impl TryInto<Vec<Value>> for Value {
type Error = Error;

fn try_into(self) -> Result<Vec<Value>, Error> {
match self {
Value::Array(a) => Ok(a),
_ => Err(<Error as serde::de::Error>::custom("value is not an array")),
}
}
}

impl TryInto<Map<String, Value>> for Value {
type Error = Error;

fn try_into(self) -> Result<Map<String, Value>, Error> {
match self {
Value::Object(o) => Ok(o),
_ => Err(<Error as serde::de::Error>::custom("value is not an object")),
}
}
}

impl<'a> TryInto<&'a Map<String, Value>> for &'a Value {
type Error = Error;

fn try_into(self) -> Result<&'a Map<String, Value>, Error> {
self.as_object().ok_or_else(|| <Error as serde::de::Error>::custom("value is not an object"))
}
}

impl TryInto<()> for Value {
type Error = Error;

fn try_into(self) -> Result<(), Error> {
self.as_null().ok_or_else(|| <Error as serde::de::Error>::custom("value is not a null"))
}
}

impl TryInto<()> for &Value {
type Error = Error;

fn try_into(self) -> Result<(), Error> {
self.as_null().ok_or_else(|| <Error as serde::de::Error>::custom("value is not a null"))
}
}
87 changes: 87 additions & 0 deletions tests/test.rs
Expand Up @@ -2060,6 +2060,93 @@ fn test_partialeq_bool() {
assert_ne!(v, 0);
}

#[test]
fn test_tryinto_string() {
use std::convert::TryInto;
let v = to_value("42").unwrap();
let s: &String = (&v).try_into().unwrap();
assert_eq!(s, "42");
let s: &str = (&v).try_into().unwrap();
assert_eq!(s, "42");
let s: String = v.clone().try_into().unwrap();
assert_eq!(s, "42");
}

#[test]
fn test_tryinto_number() {
use std::convert::TryInto;
let v = to_value(42).unwrap();
let n: u64 = (&v).try_into().unwrap();
assert_eq!(n, 42);
let n: i64 = (&v).try_into().unwrap();
assert_eq!(n, 42);
let n: f64 = (&v).try_into().unwrap();
assert_eq!(n, 42.0);
let n: u64 = v.clone().try_into().unwrap();
assert_eq!(n, 42);
let n: i64 = v.clone().try_into().unwrap();
assert_eq!(n, 42);
let n: f64 = v.clone().try_into().unwrap();
assert_eq!(n, 42.0);
}

#[test]
fn test_tryinto_bool() {
use std::convert::TryInto;
let v = to_value(true).unwrap();
let b: bool = (&v).try_into().unwrap();
assert_eq!(b, true);
let b: bool = v.try_into().unwrap();
assert_eq!(b, true);

let v = to_value(false).unwrap();
let b: bool = (&v).try_into().unwrap();
assert_eq!(b, false);
let b: bool = v.try_into().unwrap();
assert_eq!(b, false);
}

#[test]
fn test_tryinto_null() {
use std::convert::TryInto;
let v = to_value(()).unwrap();
let n: () = v.try_into().unwrap();
assert_eq!(n, ());
}

#[test]
fn test_tryinto_array() {
use std::convert::TryInto;

let v = json!([1, 2, 3]);
let a: &Vec<Value> = (&v).try_into().unwrap();
assert_eq!(a, &vec![1, 2, 3]);
let a: &[Value] = (&v).try_into().unwrap();
assert_eq!(a, vec![1, 2, 3]);
let a: Vec<Value> = v.try_into().unwrap();
assert_eq!(a, vec![1, 2, 3]);

let v = json!([1, 2.0, "foo", { "bar": "baz"}, null, false]);
let _a: &Vec<Value> = (&v).try_into().unwrap();
let _a: &[Value] = (&v).try_into().unwrap();
let _a: Vec<Value> = v.try_into().unwrap();
}

#[test]
fn test_tryinto_object() {
use std::convert::TryInto;
use serde_json::map::Map;

let mut map = Map::new();
map.insert("foo".to_string(), json!("bar"));

let v = json!({"foo": "bar"});
let m: &Map<String, Value> = (&v).try_into().unwrap();
assert_eq!(m, &map);
let m: Map<String, Value> = v.try_into().unwrap();
assert_eq!(m, map);
}

struct FailReader(io::ErrorKind);

impl io::Read for FailReader {
Expand Down