Struct kserd::ds::Kserd[][src]

pub struct Kserd<'a> {
    pub id: Option<Kstr<'a>>,
    pub val: Value<'a>,
}

The atomic value.

Kserd contains an optional identity (id), and the Value. Taken together the Kserd object can describe (almost) all Rust data structures. The identity can be mostly ignored for self-explanatory data such as primitives. It can be used to name structures, and plays a special role in unit structs and enum variants.

Kserd dereferences mutably to Value so all reading and mutating methods on Value can use directly. It is encouraged to use the methods rather than accessing the fields directly.

Kserd implements ordering and equality, it is important to note that ordering and equality is done only on the value, the identity is ignored.

Example

Use the methods to quickly see the data if the type is known. Mutating can be done directly.

let mut kserd = Kserd::new_str("Hi");

// access the data without needing to pattern match
assert_eq!(kserd.str(), Some("Hi"));
// using ctors will name your ds for you
assert_eq!(kserd.id(), Some("str"));
// if not of the type, nothing returned.
assert_eq!(kserd.int(), None);

kserd.str_mut().map(|s| {
    s.pop();
    s.push_str("ello, world!");
}); // mutate directly.
    // this method has the additional effect of cloning the string.
assert_eq!(kserd.str(), Some("Hello, world!"));

Fields

id: Option<Kstr<'a>>

The identity of the value.

This can be optional. Typically the identity is something like the struct or enum name.

val: Value<'a>

The Value.

This store the actual value, which comprises of primitive types or more complex nested types such as sequences or maps.

Implementations

impl Kserd<'static>[src]

Static lifetime constructors. These do not need a Serialize trait.

pub const fn new_unit() -> Self[src]

A new unit value ().

Example

let kserd = Kserd::new_unit();
assert_eq!(kserd.unit(), true);
assert_eq!(kserd.id(), None);

pub fn new_bool(value: bool) -> Self[src]

A new boolean value.

Example

let kserd = Kserd::new_bool(true);
assert_eq!(kserd.bool(), Some(true));
assert_eq!(kserd.id(), Some("bool"));

pub fn new_num<T: NumberType>(value: T) -> Self[src]

A new number value. The trait NumberType is implemented on all Rust primitive numbers so number literals can be used.

Example

let kserd = Kserd::new_num(123456);
assert_eq!(kserd.uint(), Some(123456));

let kserd = Kserd::new_num(-123456);
assert_eq!(kserd.int(), Some(-123456));

let kserd = Kserd::new_num(3.14);
assert_eq!(kserd.float(), Some(3.14));

pub fn new_string(string: String) -> Self[src]

A new string value. The ownership of the string is transferred and as such the Kserd has a static lifetime.

Example

let kserd = Kserd::new_string(String::from("Hello, world!"));
assert_eq!(kserd.str(), Some("Hello, world!"));
assert_eq!(kserd.id(), Some("String"));

pub fn new_barrv(byte_array: Vec<u8>) -> Self[src]

A new byte array value. The ownership of the vector is transferred and as such the Kserd has a static lifetime.

Example

let kserd = Kserd::new_barrv(vec![0,1,2,3]);
assert_eq!(kserd.barr(), Some([0,1,2,3].as_ref()));
assert_eq!(kserd.id(), Some("ByteVec"));

impl<'a> Kserd<'a>[src]

General lifetime contructors. These do not need a Serialize trait.

pub const fn new(value: Value<'a>) -> Self[src]

A new Kserd with the specified Value. No identity is ascribed to the Kserd.

Example

let kserd = Kserd::new(Value::Unit);
assert_eq!(kserd.val, Value::Unit);
assert_eq!(kserd.id, None);

pub fn with_id<S: Into<Kstr<'a>>>(
    identity: S,
    value: Value<'a>
) -> Result<Self, InvalidId>
[src]

A new Kserd with a specified identity and Value.

The identity is taken as a Kstr, meaning it can be a reference or owned. String and &str can be used as the identity. The identity must also be valid, that is, it cannot contain certain characters or Err will be returned.

It is recommended to construct Kserd in this manner rather than manually via setting the id and val fields as an invalid identity will not parse back from text.

Example

let kserd = Kserd::with_id("an-identity", Value::Bool(true)).unwrap();
assert_eq!(kserd.bool(), Some(true));
assert_eq!(kserd.id(), Some("an-identity"));

let kserd = Kserd::with_id("<an,> in(valid.)/{identity}\\=", Value::Unit);
assert_eq!(kserd.is_err(), true);

pub fn new_str(string: &'a str) -> Self[src]

A new string value. The Kserd borrows the string and has the same lifetime.

Example

let kserd = Kserd::new_str("Hello, world!");
assert_eq!(kserd.str(), Some("Hello, world!"));
assert_eq!(kserd.id(), Some("str"));

pub fn new_barr(byte_array: &'a [u8]) -> Self[src]

A new byte array value. The Kserd borrows the array and has the same lifetime.

Example

let kserd = Kserd::new_barr([0,1,2,5,10].as_ref());
assert_eq!(kserd.barr(), Some([0,1,2,5,10].as_ref()));
assert_eq!(kserd.id(), Some("barr"));

pub fn new_cntr<I, S>(iter: I) -> Result<Self, InvalidFieldName> where
    S: Into<Kstr<'a>>,
    I: IntoIterator<Item = (S, Kserd<'a>)>, 
[src]

Construct a new container Kserd from a list of field-value pairs.

Example

let pass = Kserd::new_cntr(vec![
    ("a", Kserd::new_num(0))
]).unwrap();

let fail = Kserd::new_cntr(vec![
    ("1 wrong/name", Kserd::new_num(0))
]);
assert_eq!(fail.is_err(), true);

pub fn new_map<I>(iter: I) -> Self where
    I: IntoIterator<Item = (Kserd<'a>, Kserd<'a>)>, 
[src]

Construct a new map value from a list of key-value pairs.

Example

let kserd = Kserd::new_map(vec![
    (Kserd::new_unit(), Kserd::new_num(0))
]);

impl<'a> Kserd<'a>[src]

pub fn id(&self) -> Option<&str>[src]

The identity. Same as the .id field but mapped as a &str.

Example

let kserd = Kserd::with_id("Hello", Value::Unit).unwrap();
assert_eq!(kserd.id(), Some("Hello"));

impl<'a> Kserd<'a>[src]

Conversions.

pub fn into_owned(self) -> Kserd<'static>[src]

Clones all data to make a static Kserd.

pub fn mk_brw(&self) -> Kserd<'_>[src]

Makes a copy of this Kserd that references data in the this Kserd.

This is particularly useful if you want to gaurantee that all data is of the borrowed variety when decoding back to a data structure (see Decoder for explanation).

There is a performance penalty as nested structures have to be rebuilt.

Example

let kserd = Kserd::new_string("Hello, world!".to_owned());
let brwed = kserd.mk_brw();
assert_eq!(kserd, brwed);

impl Kserd<'static>[src]

pub fn enc<T: Serialize>(data: &T) -> Result<Self, Error>[src]

Encode T into a Kserd.

Requires the encode feature.

Convenience function for data.serialize(Encoder).

See Encoder for usage.

impl<'a> Kserd<'a>[src]

pub fn decode<T: Deserialize<'a>>(self) -> Result<T, Error>[src]

Attempt to decode a Kserd into type T.

Requires the encode feature.

Convenience function for <T as Deserialize>::deserialize(Decoder(self)).

See Decoder for usage.

impl<'a> Kserd<'a>[src]

String representation.

pub fn as_str(&self) -> String[src]

Format the Kserd as a string using the default FormattingConfig.

Example

let kserd = Kserd::with_id("AStruct", Value::new_cntr(vec![
    ("a", Kserd::new_num(1_010_101)),
    ("b", Kserd::new_num(3.14)),
    ("c", Kserd::new_str("Hello, world!")),
    ("d", Kserd::new_barrv(vec![100,150,200,225]))
]).unwrap()).unwrap();

let s = kserd.as_str();
assert_eq!(
    &s,
    r#"AStruct (
    a = 1010101
    b = 3.14
    c = "Hello, world!"
    d = b91'"!Mo4'
)"#);

pub fn as_str_with_config(&self, config: FormattingConfig) -> String[src]

Format the Kserd as a string using the specified FormattingConfig.

Example

use kserd::fmt::FormattingConfig;

let kserd = Kserd::with_id("AStruct", Value::new_cntr(vec![
    ("a", Kserd::new_num(1_010_101)),
    ("b", Kserd::new_num(3.14)),
    ("c", Kserd::new_str("Hello, world!")),
    ("d", Kserd::new_barrv(vec![100,150,200,225]))
]).unwrap()).unwrap();

let config = FormattingConfig {
    id_on_containers: false, // don't give container name
    width_limit: None, // all inline
    ..Default::default()
};

let s = kserd.as_str_with_config(config);
assert_eq!(
    &s,
    r#"(a = 1010101, b = 3.14, c = "Hello, world!", d = b91'"!Mo4')"#
);

Methods from Deref<Target = Value<'a>>

pub fn unit(&self) -> bool[src]

Value is a unit value (Value::Unit).

Example

let value = Value::Unit;
assert_eq!(value.unit(), true);

pub fn bool(&self) -> Option<bool>[src]

Value is a boolean value.

Example

let value = Value::Bool(true);
assert_eq!(value.bool(), Some(true));

pub fn bool_mut(&mut self) -> Option<&mut bool>[src]

Value is a boolean value. Can be altered.

Example

let mut value = Value::Bool(false);
value.bool_mut().map(|x| *x = true);
assert_eq!(value.bool(), Some(true));

pub fn ch(&self) -> Option<char>[src]

Value is a string with a single character.

Example

let value = Value::new_str("A");
assert_eq!(value.ch(), Some('A'));

let value = Value::new_str("Hello, world!");
assert_eq!(value.ch(), None);

pub fn uint(&self) -> Option<u128>[src]

Value is an unsigned integer.

Example

let value = Value::new_num(123456);
assert_eq!(value.uint(), Some(123456));

pub fn int(&self) -> Option<i128>[src]

Value is a signed integer. A positive integer can be both signed and unsigned up to i128::max_value().

Example

let value = Value::new_num(-123456);
assert_eq!(value.int(), Some(-123456));

pub fn float(&self) -> Option<f64>[src]

Value is a floating point number. Both signed and unsigned integers can be represented as floats.

Example

let value = Value::new_num(-3.14);
assert_eq!(value.float(), Some(-3.14));

pub fn num_mut(&mut self) -> Option<&mut Number>[src]

Value is a numerical value, and can be altered.

Example

let mut value = Value::new_num(123456);
value.num_mut().map(|x| *x = Number::from(100));
assert_eq!(value.uint(), Some(100));

pub fn str(&self) -> Option<&str>[src]

Value is a string.

Example

let value = Value::new_str("Hello, world!");
assert_eq!(value.str(), Some("Hello, world!"));

pub fn str_mut(&mut self) -> Option<&mut String>[src]

Value is a string. Can be altered.

Clones string value if not owned.

Example

let mut value = Value::new_str("Hello");
value.str_mut().map(|x| { x.push_str(", world!"); });
assert_eq!(value.str(), Some("Hello, world!"));

pub fn barr(&self) -> Option<&[u8]>[src]

Value is a byte array.

Example

let value = Value::new_barr([0,1,2,5,10].as_ref());
assert_eq!(value.barr(), Some([0,1,2,5,10].as_ref()));

pub fn barr_mut(&mut self) -> Option<&mut Vec<u8>>[src]

Value is a byte array. Can be altered.

Clones data if not already owned.

Example

let mut value = Value::new_barr([0,1,2].as_ref());
value.barr_mut().map(|x| { x.push(3); });
assert_eq!(value.barr(), Some([0,1,2,3].as_ref()));

pub fn tuple(&self) -> Option<&Vec<Kserd<'a>>>[src]

Value is a tuple.

Example

let value = Value::Tuple(vec![Kserd::new_num(101)]);
assert_eq!(value.tuple(), Some(&vec![Kserd::new_num(101)]));

pub fn tuple_mut(&mut self) -> Option<&mut Vec<Kserd<'a>>>[src]

Value is a tuple. Can be altered.

Example

let mut value = Value::Tuple(vec![Kserd::new_num(101)]);
value.tuple_mut().map(|x| x.push(Kserd::new_str("Hello")));
assert_eq!(
    value.tuple(),
    Some(&vec![Kserd::new_num(101), Kserd::new_str("Hello")])
);

pub fn cntr(&self) -> Option<Accessor<&BTreeMap<Kstr<'a>, Kserd<'a>>>>[src]

Value is a container.

Returns an Accessor into the fields, which has utility methods for accessing the fields.

Example

let value = Value::new_cntr(vec![("a", Kserd::new_num(101))]).unwrap();
let accessor = value.cntr().unwrap();
assert_eq!(accessor.get_num("a"), Some(101.into()));

pub fn cntr_mut(
    &mut self
) -> Option<Accessor<&mut BTreeMap<Kstr<'a>, Kserd<'a>>>>
[src]

Value is a container. Can be altered.

Returns an Accessor into the fields, which has utility methods for accessing the fields.

Example

let mut value = Value::new_cntr(vec![("a", Kserd::new_num(101))]).unwrap();
let mut accessor = value.cntr_mut().unwrap();
accessor.get_num_mut("a").map(|x| *x = 1.into());
assert_eq!(value, Value::new_cntr(vec![("a", Kserd::new_num(1))]).unwrap());

pub fn seq(&self) -> Option<&Vec<Kserd<'a>>>[src]

Value is a sequence.

Example

let value = Value::Seq(vec![Kserd::new_num(101)]);
assert_eq!(value.seq(), Some(&vec![Kserd::new_num(101)]));

pub fn seq_mut(&mut self) -> Option<&mut Vec<Kserd<'a>>>[src]

Value is a sequence. Can be altered.

Example

let mut value = Value::Seq(vec![Kserd::new_num(101)]);
value.seq_mut().map(|x| x.push(Kserd::new_str("Hello")));
assert_eq!(
    value.seq(),
    Some(&vec![Kserd::new_num(101), Kserd::new_str("Hello")])
);

pub fn tuple_or_seq(&self) -> Option<&Vec<Kserd<'a>>>[src]

Value is a tuple or a sequence.

As tuple and sequence share the same backing store, testing for either can be useful.

Example

let value = Value::Seq(vec![Kserd::new_num(101)]);
assert_eq!(value.tuple_or_seq(), Some(&vec![Kserd::new_num(101)]));

pub fn tuple_or_seq_mut(&mut self) -> Option<&mut Vec<Kserd<'a>>>[src]

Value is a tuple or a sequence. Can be altered.

As tuple and sequence share the same backing store, testing for either can be useful.

Example

let mut value = Value::Tuple(vec![Kserd::new_num(101)]);
value.tuple_or_seq_mut().map(|x| x.push(Kserd::new_str("Hello")));
assert_eq!(
    value.tuple_or_seq(),
    Some(&vec![Kserd::new_num(101), Kserd::new_str("Hello")])
);

pub fn map(&self) -> Option<&BTreeMap<Kserd<'a>, Kserd<'a>>>[src]

Value is a map.

Example

let value = Value::new_map(vec![(
    Kserd::new_str("a"),
    Kserd::new_num(3.14)
)]);
let num = value.map().and_then(|map| {
    map.get(&Kserd::new_str("a"))
});
assert_eq!(num, Some(&Kserd::new_num(3.14)));

pub fn map_mut(&mut self) -> Option<&mut BTreeMap<Kserd<'a>, Kserd<'a>>>[src]

Value is a map. Can be altered.

Example

let mut value = Value::new_map(vec![(
    Kserd::new_str("a"),
    Kserd::new_num(3.14)
)]);

value.map_mut().and_then(|map| {
    map.get_mut(&Kserd::new_str("a"))
}).map(|x| *x = Kserd::new_str("Hello"));

let expect = Value::new_map(vec![(
    Kserd::new_str("a"),
    Kserd::new_str("Hello")
)]);

assert_eq!(value, expect);

pub fn mk_brw(&self) -> Value<'_>[src]

Makes a copy of this Value that references data in the this Value.

This is particularly useful if you want to gaurantee that all data is of the borrowed variety when decoding back to a data structure (see Decoder for explanation).

There is a performance penalty as nested structures have to be rebuilt.

Example

let value = Value::new_string("Hello, world!".to_owned());
let brwed = value.mk_brw();
assert_eq!(value, brwed);

Trait Implementations

impl<'a> Clone for Kserd<'a>[src]

impl<'a> Debug for Kserd<'a>[src]

impl<'a> Deref for Kserd<'a>[src]

type Target = Value<'a>

The resulting type after dereferencing.

impl<'a> DerefMut for Kserd<'a>[src]

impl<'a> Display for Kserd<'a>[src]

impl<'a> Eq for Kserd<'a>[src]

impl<'a> Ord for Kserd<'a>[src]

impl<'a> PartialEq<Kserd<'a>> for Kserd<'a>[src]

impl<'a> PartialOrd<Kserd<'a>> for Kserd<'a>[src]

impl<'a> ToKserd<'a> for Kserd<'a>[src]

Auto Trait Implementations

impl<'a> RefUnwindSafe for Kserd<'a>

impl<'a> Send for Kserd<'a>

impl<'a> Sync for Kserd<'a>

impl<'a> Unpin for Kserd<'a>

impl<'a> UnwindSafe for Kserd<'a>

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> Conv for T

impl<T> Conv for T

impl<T> FmtForward for T

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> Pipe for T where
    T: ?Sized

impl<T> Pipe for T

impl<T> PipeAsRef for T

impl<T> PipeBorrow for T

impl<T> PipeDeref for T

impl<T> PipeRef for T

impl<T> Tap for T

impl<T> Tap for T

impl<T, U> TapAsRef<U> for T where
    U: ?Sized

impl<T, U> TapBorrow<U> for T where
    U: ?Sized

impl<T> TapDeref for T

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T> ToString for T where
    T: Display + ?Sized
[src]

impl<T> TryConv for T

impl<T> TryConv for T

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.