Expand description
§protean
A flexible data type with serde support (serde feature).
§Why?
I found myself making a similar data type quite often for serialized communication of flexible values.
Note: A lot of serialization formats are not “self-describing”
and commonly use integer discriminants for enum variants. This
crate will make sure to never reorder variants.
§Owned Example
The protean crate supports borrowing from owned data (like a Vec<u8>)
without copying or cloning.
use std::sync::Arc;
use protean::{DataCell, OwnedDataCell};
let buffer = Vec::from(b"Hello, world!");
let data = OwnedDataCell::build(
buffer,
// We could also deserialize from the buffer using serde...
|bytes| DataCell::text(str::from_utf8(bytes).unwrap()),
);
assert_eq!(data.as_text(), Some("Hello, world!"));
// You can also use helper methods to build DataCell
// variants from owned data...
let data = OwnedDataCell::text("Hello, world!");
assert_eq!(data.as_text(), Some("Hello, world!"));
let data = OwnedDataCell::bytes(Arc::from(*b"Hello, world!"));
assert_eq!(data.as_bytes(), Some(&b"Hello, world!"[..]));§Conversion Example
use protean::DataCell;
let float_number = DataCell::f32(255.0);
let as_int = float_number.try_as_u8().expect("Float as number...");
assert_eq!(as_int, 255u8);
// Floats above ~16.7 million cannot be safely
// represented as an int, which we catch.
let high_float_number = DataCell::f32(17_000_000.0);
assert_eq!(high_float_number.try_as_u32(), None);
// ... but it does work for f64:
let high_float_number = DataCell::f64(17_000_000.0);
assert_eq!(high_float_number.try_as_u32(), Some(17_000_000));
// Integers can also be safely converted to floats
// if they fit without precision loss.
let int_number = DataCell::u32(2_930);
assert_eq!(int_number.try_as_f32(), Some(2_930.0));
// Again, precision starts to fall off around 16.7 million:
let high_int_number = DataCell::u32(17_000_000);
assert_eq!(high_int_number.try_as_f32(), None);
// ... but works for f64:
assert_eq!(high_int_number.try_as_f64(), Some(17_000_000.0));Structs§
- Owned
Data Cell - A DataCell that borrows from an owned buffer without copying.
Enums§
- Data
Cell - A flexible, fundamental unit of data.