Trait tskit::metadata::MetadataRoundtrip [−][src]
pub trait MetadataRoundtrip { fn encode(&self) -> Result<Vec<u8>, MetadataError>; fn decode(md: &[u8]) -> Result<Self, MetadataError>
where
Self: Sized; }
Expand description
Enable a type to be used as table metadata
See handle_metadata_return
for a macro to help implement this trait,
and its use in examples below.
We strongly recommend the use of the serde ecosystem
for row metadata.
For many use cases, we imagine that
bincode will be one of
the more useful serde
-related crates.
Examples
Mutation metadata
use tskit::handle_metadata_return; use tskit::TableAccess; #[derive(serde::Serialize, serde::Deserialize)] pub struct MyMutation { origin_time: i32, effect_size: f64, dominance: f64, } impl tskit::metadata::MetadataRoundtrip for MyMutation { fn encode(&self) -> Result<Vec<u8>, tskit::metadata::MetadataError> { handle_metadata_return!(bincode::serialize(&self)) } fn decode(md: &[u8]) -> Result<Self, tskit::metadata::MetadataError> { handle_metadata_return!(bincode::deserialize(md)) } } let mut tables = tskit::TableCollection::new(100.).unwrap(); let mutation = MyMutation{origin_time: 100, effect_size: -1e-4, dominance: 0.25}; // Add table row with metadata. tables.add_mutation_with_metadata(0, 0, tskit::TSK_NULL, 100., None, Some(&mutation)).unwrap(); // Decode the metadata // The two unwraps are: // 1. Handle Errors vs Option. // 2. Handle the option for the case of no error. let decoded = tables.mutations().metadata::<MyMutation>(0).unwrap().unwrap(); assert_eq!(mutation.origin_time, decoded.origin_time); match decoded.effect_size.partial_cmp(&mutation.effect_size) { Some(std::cmp::Ordering::Greater) => assert!(false), Some(std::cmp::Ordering::Less) => assert!(false), Some(std::cmp::Ordering::Equal) => (), None => panic!("bad comparison"), }; match decoded.dominance.partial_cmp(&mutation.dominance) { Some(std::cmp::Ordering::Greater) => assert!(false), Some(std::cmp::Ordering::Less) => assert!(false), Some(std::cmp::Ordering::Equal) => (), None => panic!("bad comparison"), };