Value

Enum Value 

Source
pub enum Value {
    Object(HashMap<String, Value>),
    Array(Vec<Value>),
    String(String),
    ByteString(Vec<u8>),
    Number(f64),
    Bool(bool),
    Null,
}
Expand description

Represents any valid MASON value.

Variants§

§

Object(HashMap<String, Value>)

§

Array(Vec<Value>)

§

String(String)

§

ByteString(Vec<u8>)

§

Number(f64)

§

Bool(bool)

§

Null

Implementations§

Source§

impl Value

Source

pub fn from_reader(reader: impl Read) -> Result<Self>

Deserialize a Value from an I/O stream of MASON.

The content of the I/O stream is buffered in memory using a std::io::BufReader.

It is expected that the input stream ends after the deserialized value. If the stream does not end, such as in the case of a persistent socket connection, this function will not return.

§Example
use std::fs::File;

fn main() {
    let value = Value::from_reader(File::open("test.mason").unwrap()).unwrap();
    println!("{:?}", value);
}
§Errors

This function can fail if the I/O stream is not valid MASON, or if any errors were encountered while reading from the stream.

Source

pub fn from_slice(bytes: &[u8]) -> Result<Self>

Deserialize a Value from a slice of MASON bytes.

§Example
let data = Value::from_slice(b"[1.0, true, null]").unwrap();
assert_eq!(data, Value::Array(vec![Value::Number(1.0), Value::Bool(true), Value::Null]))
§Errors

This function can fail if the byte slice is not valid MASON.

Source

pub fn to_writer<W: Write>(&self, writer: &mut W) -> Result

Serialize a Value using the given writer.

§Example
let value_string = r#"vec: [1, true, false, null]"#;
let value = Value::from_str(value_string).unwrap();

let mut writer = String::new();
Value::to_writer(&value, &mut writer);
assert_eq!(writer, value_string);

This is also the function used by Value’s display implementation:

let value_string = r#""some bytes": b"This \b \x0e\t is \x7f bytes!""#;
let value = Value::from_str(value_string).unwrap();

assert_eq!(value.to_string(), value_string);
Source

pub fn value_type(&self) -> &'static str

Return a string description of the Value.

let value = Value::from_str(r#"{a: 2, b: false}"#).unwrap();
assert_eq!(value.value_type(), "object");
assert_eq!(value["a"].value_type(), "number");
assert_eq!(value["b"].value_type(), "boolean");
Source

pub fn get<I: Index>(&self, index: I) -> Option<&Self>

Index into a MASON array or object. A string index can be used to access a value in an object, and a usize index can be used to access an element of an array.

Returns None if the type of self does not match the type of the index, for example if the index is a string and self is an array or a number. Also returns None if the given key does not exist in the object or the given index is not within the bounds of the array.

let object = Value::from_str(r#"{ "A": 65, "B": 66, "C": 67 }"#).unwrap();
assert_eq!(*object.get("A").unwrap(), Value::Number(65.0));

let array = Value::from_str(r#"[ "A", "B", "C" ]"#).unwrap();
assert_eq!(*array.get(2).unwrap(), Value::String("C".into()));

assert_eq!(array.get("A"), None);

Square brackets can also be used to index into a value in a more concise way. This returns Value::Null in cases where get would have returned None.

let object = Value::from_str(r#"{
    "A": ["a", "á", "à"],
    "B": ["b", "b́"],
    "C": ["c", "ć", "ć̣", "ḉ"],
}"#).unwrap();
assert_eq!(object["B"][0], Value::String("b".into()));

assert_eq!(object["D"], Value::Null);
assert_eq!(object[0]["x"]["y"]["z"], Value::Null);
Source

pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Self>

Mutably index into a MASON array or object. A string index can be used to access a value in an object, and a usize index can be used to access an element of an array.

Returns None if the type of self does not match the type of the index, for example if the index is a string and self is an array or a number. Also returns None if the given key does not exist in the object or the given index is not within the bounds of the array.

let mut object = Value::from_str(r#"{ "A": 65, "B": 66, "C": 67 }"#).unwrap();
*object.get_mut("A").unwrap() = Value::Number(69.0);

let mut array = Value::from_str(r#"[ "A", "B", "C" ]"#).unwrap();
*array.get_mut(2).unwrap() = Value::String("D".into());
Source

pub fn is_object(&self) -> bool

Returns true if the Value is an Object. Returns false otherwise.

For any Value on which is_object returns true, as_object and as_object_mut are guaranteed to return the hashmap representing the object.

let obj = Value::from_str(r#"{ "a": { "nested": true }, "b": ["an", "array"] }"#).unwrap();

assert!(obj.is_object());
assert!(obj["a"].is_object());

// array, not an object
assert!(!obj["b"].is_object());
Source

pub fn as_object(&self) -> Option<&HashMap<String, Self>>

If the Value is an Object, returns the associated object. Returns None otherwise.

let v = Value::from_str(r#"{ "a": { "nested": true }, "b": ["an", "array"] }"#).unwrap();

// The length of `{"nested": true}` is 1 entry.
assert_eq!(v["a"].as_object().unwrap().len(), 1);

// The array `["an", "array"]` is not an object.
assert_eq!(v["b"].as_object(), None);
Source

pub fn as_object_mut(&mut self) -> Option<&mut HashMap<String, Self>>

If the Value is an Object, returns the associated mutable object. Returns None otherwise.

let mut v = Value::from_str(r#"{ "a": { "nested": true } }"#).unwrap();

v["a"].as_object_mut().unwrap().clear();
assert_eq!(v, Value::from_str(r#"{ "a": {} }"#).unwrap());
Source

pub fn is_array(&self) -> bool

Returns true if the Value is an Array. Returns false otherwise.

For any Value on which is_array returns true, as_array and as_array_mut are guaranteed to return the vector representing the array.

let obj = Value::from_str(r#"{ "a": ["an", "array"], "b": { "an": "object" } }"#).unwrap();

assert!(obj["a"].is_array());

// an object, not an array
assert!(!obj["b"].is_array());
Source

pub fn as_array(&self) -> Option<&Vec<Self>>

If the Value is an Array, returns the associated vector. Returns None otherwise.

let v = Value::from_str(r#"{ "a": ["an", "array"], "b": { "an": "object" } }"#).unwrap();

// The length of `["an", "array"]` is 2 elements.
assert_eq!(v["a"].as_array().unwrap().len(), 2);

// The object `{"an": "object"}` is not an array.
assert_eq!(v["b"].as_array(), None);
Source

pub fn as_array_mut(&mut self) -> Option<&mut Vec<Self>>

If the Value is an Array, returns the associated mutable vector. Returns None otherwise.

let mut v = Value::from_str(r#"{ "a": ["an", "array"] }"#).unwrap();

v["a"].as_array_mut().unwrap().clear();
assert_eq!(v, Value::from_str(r#"{ "a": [] }"#).unwrap());
Source

pub fn is_string(&self) -> bool

Returns true if the Value is a String. Returns false otherwise.

For any Value on which is_string returns true, as_str is guaranteed to return the string slice.

let v = Value::from_str(r#"{ "a": "some string", "b": false }"#).unwrap();

assert!(v["a"].is_string());

// The boolean `false` is not a string.
assert!(!v["b"].is_string());
Source

pub fn as_str(&self) -> Option<&str>

If the Value is a String, returns the associated str. Returns None otherwise.

let v = Value::from_str(r#"{ "a": "some string", "b": false }"#).unwrap();

assert_eq!(v["a"].as_str(), Some("some string"));

// The boolean `false` is not a string.
assert_eq!(v["b"].as_str(), None);
Source

pub fn is_number(&self) -> bool

Returns true if the Value is a Number. Returns false otherwise.

let v = Value::from_str(r#"{ "a": 1, "b": "2" }"#).unwrap();

assert!(v["a"].is_number());

// The string `"2"` is a string, not a number.
assert!(!v["b"].is_number());
Source

pub fn as_number(&self) -> Option<&f64>

If the Value is a Number, returns the associated double. Returns None otherwise.

let v = Value::from_str(r#"{ "a": 1, "b": "2" }"#).unwrap();

assert_eq!(v["a"].as_number(), Some(&1.0));

// The string `"2"` is not a number.
assert_eq!(v["d"].as_number(), None);
Source

pub fn is_boolean(&self) -> bool

Returns true if the Value is a Boolean. Returns false otherwise.

For any Value on which is_boolean returns true, as_bool is guaranteed to return the boolean value.

let v = Value::from_str(r#"{ "a": false, "b": "false" }"#).unwrap();

assert!(v["a"].is_boolean());

// The string `"false"` is a string, not a boolean.
assert!(!v["b"].is_boolean());
Source

pub fn as_bool(&self) -> Option<bool>

If the Value is a Boolean, returns the associated bool. Returns None otherwise.

let v = Value::from_str(r#"{ "a": false, "b": "false" }"#).unwrap();

assert_eq!(v["a"].as_bool(), Some(false));

// The string `"false"` is a string, not a boolean.
assert_eq!(v["b"].as_bool(), None);
Source

pub fn is_null(&self) -> bool

Returns true if the Value is a Null. Returns false otherwise.

For any Value on which is_null returns true, as_null is guaranteed to return Some(()).

let v = Value::from_str(r#"{ "a": null, "b": false }"#).unwrap();

assert!(v["a"].is_null());

// The boolean `false` is not null.
assert!(!v["b"].is_null());
Source

pub fn as_null(&self) -> Option<()>

If the Value is a Null, returns (). Returns None otherwise.

let v = Value::from_str(r#"{ "a": null, "b": false }"#).unwrap();

assert_eq!(v["a"].as_null(), Some(()));

// The boolean `false` is not null.
assert_eq!(v["b"].as_null(), None);
Source

pub fn take(&mut self) -> Self

Takes the value out of the Value, leaving a Null in its place.

let mut v = Value::from_str(r#"{ "x": "y" }"#).unwrap();
assert_eq!(v["x"].take(), Value::String("y".into()));
assert_eq!(v, Value::from_str(r#"{ "x": null }"#).unwrap());

Trait Implementations§

Source§

impl Clone for Value

Source§

fn clone(&self) -> Value

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Value

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Value

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Value

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Value

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FromStr for Value

Source§

fn from_str(string: &str) -> Result<Self>

Deserialize a Value from a MASON string.

§Example
let data = Value::from_str("[1.0, true, null]").unwrap();
assert_eq!(data, Value::Array(vec![Value::Number(1.0), Value::Bool(true), Value::Null]))
§Errors

This function can fail if the string is not valid MASON.

Source§

type Err = Error

The associated error which can be returned from parsing.
Source§

impl<I> Index<I> for Value
where I: Index,

Source§

fn index(&self, index: I) -> &Self

Index into a mason_rs::Value using the syntax value[0] or value["k"].

Returns Value::Null if the type of self does not match the type of the index, or if the given key does not exist in the map or the given index is not within the bounds of the array.

§Examples

let data = Value::from_str(r#"{
    "x": {
        "y": ["z", "zz"]
    }
}"#).unwrap();

assert_eq!(
    data["x"]["y"],
    Value::Array(vec![
        Value::String("z".into()),
        Value::String("zz".into()),
    ]),
);
assert_eq!(data["x"]["y"][0], Value::String("z".into()));

assert_eq!(data["a"], Value::Null); // returns null for undefined values
assert_eq!(data["a"]["b"], Value::Null); // does not panic
Source§

type Output = Value

The returned type after indexing.
Source§

impl<I> IndexMut<I> for Value
where I: Index,

Source§

fn index_mut(&mut self, index: I) -> &mut Self

Write into a mason_rs::Value using the syntax value[0] = ... or value["k"] = ....

If the index is a number, the value must be an array of length bigger than or equal to the index. Indexing into a value that is not an array or an array that is too small will panic.

If the index is a string, the value must be an object or null which is treated like an empty object. If the key is not already present in the object, it will be inserted with a value of null. Indexing into a value that is neither an object nor null will panic.

§Examples
let mut data = Value::from_str(r#"{ "x": 0 }"#).unwrap();

// replace an existing key
data["x"] = Value::Number(1.0);

// insert a new key
data["y"] = Value::Array(vec![Value::Bool(false), Value::Bool(true)]);

// replace an array value
data["y"][0] = Value::Bool(true);

// insert a new array value
data["y"][2] = Value::Number(1.3);

// inserted a deeply nested key
data["a"]["b"]["c"]["d"] = Value::Bool(true);

println!("{:?}", data);
Source§

impl PartialEq for Value

Source§

fn eq(&self, other: &Value) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Value

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Value

Auto Trait Implementations§

§

impl Freeze for Value

§

impl RefUnwindSafe for Value

§

impl Send for Value

§

impl Sync for Value

§

impl Unpin for Value

§

impl UnwindSafe for Value

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,