zvariant/serialized/context.rs
1use crate::{Endian, serialized::Format};
2
3/// The encoding context to use with the [serialization] and [deserialization] API.
4///
5/// The encoding is dependent on the position of the encoding in the entire message and hence the
6/// need to [specify] the byte position of the data being serialized or deserialized. Simply pass
7/// `0` if serializing or deserializing to or from the beginning of message, or the preceding bytes
8/// end on an 8-byte boundary.
9///
10/// # Examples
11///
12/// ```
13/// use zvariant::Endian;
14/// use zvariant::serialized::Context;
15/// use zvariant::to_bytes;
16///
17/// let str_vec = vec!["Hello", "World"];
18/// let ctxt = Context::new_dbus(Endian::Little, 0);
19/// let encoded = to_bytes(ctxt, &str_vec).unwrap();
20///
21/// // Let's decode the 2nd element of the array only
22/// let slice = encoded.slice(14..);
23/// let decoded: &str = slice.deserialize().unwrap().0;
24/// assert_eq!(decoded, "World");
25/// ```
26///
27/// [serialization]: zvariant#functions
28/// [deserialization]: zvariant::serialized::Data::deserialize
29/// [specify]: Context::new
30#[derive(Debug, PartialEq, Eq, Copy, Clone)]
31pub struct Context {
32 format: Format,
33 position: usize,
34 endian: Endian,
35}
36
37impl Context {
38 /// Create a new encoding context.
39 pub fn new(format: Format, endian: Endian, position: usize) -> Self {
40 Self {
41 format,
42 position,
43 endian,
44 }
45 }
46
47 /// Convenient wrapper for [`new`] to create a context for D-Bus format.
48 ///
49 /// [`new`]: #method.new
50 pub fn new_dbus(endian: Endian, position: usize) -> Self {
51 Self::new(Format::DBus, endian, position)
52 }
53
54 /// Convenient wrapper for [`new`] to create a context for GVariant format.
55 ///
56 /// [`new`]: #method.new
57 #[cfg(feature = "gvariant")]
58 pub fn new_gvariant(endian: Endian, position: usize) -> Self {
59 Self::new(Format::GVariant, endian, position)
60 }
61
62 /// The [`Format`] of this context.
63 pub fn format(self) -> Format {
64 self.format
65 }
66
67 /// The [`Endian`] of this context.
68 pub fn endian(self) -> Endian {
69 self.endian
70 }
71
72 /// The byte position of the value to be encoded or decoded, in the entire message.
73 pub fn position(self) -> usize {
74 self.position
75 }
76}