[−][src]Trait zvariant::Encode
Trait for encoding of varius types.
All data types that implement Encode
also implement Decode
. As decoding require
allocation, one exception here is &str
. It only implements Encode
, while its owned
sibling, String
implements both traits.
Associated Constants
const SIGNATURE_CHAR: char
The signature charachter of the implementing type.
const SIGNATURE_STR: &'static str
The signature charachter of the implementing type, in string format.
const ALIGNMENT: usize
The alignment required for encoding of the implementing type, as number of bytes.
Required methods
fn encode_into(&self, bytes: &mut Vec<u8>, format: EncodingFormat)
Encode self
and append to the end of bytes
buffer.
fn to_variant(self) -> Variant
Unflatten self
into a Variant
.
Into
<Variant>
trait bound would have been better and it's possible but since
Into<T> for T
is provided implicitly, the default no-op implementation for Variant
won't do the right thing: unflatten it.
fn is(variant: &Variant) -> bool
Checks if variant value is of the generic type T
.
Examples
use zvariant::{Encode}; let v = "hello".to_variant(); assert!(!u32::is(&v)); assert!(<&str>::is(&v));
use zvariant::{Encode}; let v = 147u32.to_variant(); assert!(u32::is(&v)); assert!(!String::is(&v));
Provided methods
fn encode(&self, format: EncodingFormat) -> Vec<u8>
Encode self
into a new byte buffer and return it.
Since encoding typically requires alignment based on the position of the encoded value in the entire encoded message it is going to be part of, you can only use for the first value in a message.
fn signature(&self) -> Signature
Get the signature.
The default implementation works for simple types with single-character signatures.
Example
use zvariant::{Encode, Structure}; assert!("hello".signature() == "s"); assert!(7u32.signature() == "u"); let s = Structure::new() .add_field("hello") .add_field(7u32); assert!(s.signature() == "(su)");
fn add_padding(bytes: &mut Vec<u8>, format: EncodingFormat)
Append required padding to bytes
buffer.
Helper for implementations.
Example
use zvariant::{Encode, EncodingFormat}; let mut bytes = vec![0u8; 3]; u32::add_padding(&mut bytes, EncodingFormat::default()); // 1 byte padding needed for `u32` to be aligned to 4-bytes boundry assert!(bytes.len() == 4);
fn padding(n_bytes_before: usize, _format: EncodingFormat) -> usize
The required padding for the implementing type.
Helper for implementations.