Struct jomini::BinaryDeserializer
source · [−]pub struct BinaryDeserializer;Expand description
A structure to deserialize binary data into Rust values.
By default, if a token is unable to be resolved then it will be ignored by the default.
Construct a custom instance through the builder method to tweak this behavior.
The example below demonstrates multiple ways to deserialize data
use jomini::{BinaryDeserializer, BinaryFlavor, Encoding, JominiDeserialize, Windows1252Encoding};
use serde::Deserialize;
use std::{borrow::Cow, collections::HashMap};
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct StructA {
#[serde(flatten)]
b: StructB,
#[serde(flatten)]
c: StructC,
}
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct StructB {
field1: String,
}
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct StructC {
field2: String,
}
#[derive(Debug, Default)]
pub struct BinaryTestFlavor;
impl BinaryFlavor for BinaryTestFlavor {
fn visit_f32(&self, data: [u8; 4]) -> f32 {
f32::from_le_bytes(data)
}
fn visit_f64(&self, data: [u8; 8]) -> f64 {
f64::from_le_bytes(data)
}
}
impl Encoding for BinaryTestFlavor {
fn decode<'a>(&self, data: &'a [u8]) -> Cow<'a, str> {
Windows1252Encoding::decode(data)
}
}
let data = [
0x82, 0x2d, 0x01, 0x00, 0x0f, 0x00, 0x03, 0x00, 0x45, 0x4e, 0x47,
0x83, 0x2d, 0x01, 0x00, 0x0f, 0x00, 0x03, 0x00, 0x45, 0x4e, 0x48,
];
let mut map = HashMap::new();
map.insert(0x2d82, String::from("field1"));
map.insert(0x2d83, String::from("field2"));
// the data can be parsed and deserialized in one step
let a: StructA = BinaryDeserializer::builder_flavor(BinaryTestFlavor)
.from_slice(&data[..], &map)?;
assert_eq!(a, StructA {
b: StructB { field1: "ENG".to_string() },
c: StructC { field2: "ENH".to_string() },
});
// or split into two steps, whatever is appropriate.
let tape = jomini::BinaryTape::from_slice(&data[..])?;
let deserializer = BinaryDeserializer::builder_flavor(BinaryTestFlavor);
let b: StructB = deserializer.from_tape(&tape, &map)?;
let c: StructC = deserializer.from_tape(&tape, &map)?;
assert_eq!(b, StructB { field1: "ENG".to_string() });
assert_eq!(c, StructC { field2: "ENH".to_string() });Implementations
sourceimpl BinaryDeserializer
impl BinaryDeserializer
sourcepub fn builder_flavor<F>(flavor: F) -> BinaryDeserializerBuilder<F> where
F: BinaryFlavor,
pub fn builder_flavor<F>(flavor: F) -> BinaryDeserializerBuilder<F> where
F: BinaryFlavor,
A customized builder for a certain flavor of binary data
Auto Trait Implementations
impl RefUnwindSafe for BinaryDeserializer
impl Send for BinaryDeserializer
impl Sync for BinaryDeserializer
impl Unpin for BinaryDeserializer
impl UnwindSafe for BinaryDeserializer
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more