zvariant

Function from_slice_for_signature

source
pub fn from_slice_for_signature<'d, 'r: 'd, B, T>(
    bytes: &'r [u8],
    ctxt: EncodingContext<B>,
    signature: &Signature<'_>,
) -> Result<T>
where B: ByteOrder, T: Deserialize<'d> + ?Sized,
Expand description

Deserialize T from a given slice of bytes with the given signature.

Use this function instead of from_slice if the value being deserialized does not implement Type. Also, if T is an, or (potentially) contains an Fd, use from_slice_fds_for_signature instead.

§Examples

While Type derive supports enums, for this example, let’s supposed it doesn’t and we don’t want to manually implement Type trait either:

use std::convert::TryInto;
use serde::{Deserialize, Serialize};

use zvariant::{to_bytes_for_signature, from_slice_for_signature};
use zvariant::EncodingContext;

let ctxt = EncodingContext::<byteorder::LE>::new_dbus(0);
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
enum Unit {
    Variant1,
    Variant2,
    Variant3,
}

let signature = "u".try_into().unwrap();
let encoded = to_bytes_for_signature(ctxt, &signature, &Unit::Variant2).unwrap();
assert_eq!(encoded.len(), 4);
let decoded: Unit = from_slice_for_signature(&encoded, ctxt, &signature).unwrap();
assert_eq!(decoded, Unit::Variant2);

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
enum NewType<'s> {
    Variant1(&'s str),
    Variant2(&'s str),
    Variant3(&'s str),
}

let signature = "(us)".try_into().unwrap();
let encoded =
    to_bytes_for_signature(ctxt, &signature, &NewType::Variant2("hello")).unwrap();
assert_eq!(encoded.len(), 14);
let decoded: NewType<'_> = from_slice_for_signature(&encoded, ctxt, &signature).unwrap();
assert_eq!(decoded, NewType::Variant2("hello"));

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
enum Structs {
    Tuple(u8, u64),
    Struct { y: u8, t: u64 },
}

// TODO: Provide convenience API to create complex signatures
let signature = "(u(yt))".try_into().unwrap();
let encoded = to_bytes_for_signature(ctxt, &signature, &Structs::Tuple(42, 42)).unwrap();
assert_eq!(encoded.len(), 24);
let decoded: Structs = from_slice_for_signature(&encoded, ctxt, &signature).unwrap();
assert_eq!(decoded, Structs::Tuple(42, 42));

let s = Structs::Struct { y: 42, t: 42 };
let encoded = to_bytes_for_signature(ctxt, &signature, &s).unwrap();
assert_eq!(encoded.len(), 24);
let decoded: Structs = from_slice_for_signature(&encoded, ctxt, &signature).unwrap();
assert_eq!(decoded, Structs::Struct { y: 42, t: 42 });