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
impl Value
Sourcepub fn from_reader(reader: impl Read) -> Result<Self>
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.
Sourcepub fn from_slice(bytes: &[u8]) -> Result<Self>
pub fn from_slice(bytes: &[u8]) -> Result<Self>
Sourcepub fn to_writer<W: Write>(&self, writer: &mut W) -> Result
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);Sourcepub fn value_type(&self) -> &'static str
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");Sourcepub fn get<I: Index>(&self, index: I) -> Option<&Self>
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);Sourcepub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Self>
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());Sourcepub fn is_object(&self) -> bool
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());Sourcepub fn as_object(&self) -> Option<&HashMap<String, Self>>
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);Sourcepub fn as_object_mut(&mut self) -> Option<&mut HashMap<String, Self>>
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());Sourcepub fn is_array(&self) -> bool
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());Sourcepub fn as_array(&self) -> Option<&Vec<Self>>
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);Sourcepub fn as_array_mut(&mut self) -> Option<&mut Vec<Self>>
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());Sourcepub fn is_string(&self) -> bool
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());Sourcepub fn as_str(&self) -> Option<&str>
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);Sourcepub fn is_number(&self) -> bool
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());Sourcepub fn as_number(&self) -> Option<&f64>
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);Sourcepub fn is_boolean(&self) -> bool
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());Sourcepub fn as_bool(&self) -> Option<bool>
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);Sourcepub fn is_null(&self) -> bool
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());Trait Implementations§
Source§impl<'de> Deserialize<'de> for Value
impl<'de> Deserialize<'de> for Value
Source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
Source§impl<I> Index<I> for Valuewhere
I: Index,
impl<I> Index<I> for Valuewhere
I: Index,
Source§fn index(&self, index: I) -> &Self
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 panicSource§impl<I> IndexMut<I> for Valuewhere
I: Index,
impl<I> IndexMut<I> for Valuewhere
I: Index,
Source§fn index_mut(&mut self, index: I) -> &mut Self
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);