zvariant/serialized/
context.rs

1use crate::{serialized::Format, Endian};
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 and deserialization]: index.html#functions
28/// [specify]: #method.new
29#[derive(Debug, PartialEq, Eq, Copy, Clone)]
30pub struct Context {
31    format: Format,
32    position: usize,
33    endian: Endian,
34}
35
36impl Context {
37    /// Create a new encoding context.
38    pub fn new(format: Format, endian: Endian, position: usize) -> Self {
39        Self {
40            format,
41            position,
42            endian,
43        }
44    }
45
46    /// Convenient wrapper for [`new`] to create a context for D-Bus format.
47    ///
48    /// [`new`]: #method.new
49    pub fn new_dbus(endian: Endian, position: usize) -> Self {
50        Self::new(Format::DBus, endian, position)
51    }
52
53    /// Convenient wrapper for [`new`] to create a context for GVariant format.
54    ///
55    /// [`new`]: #method.new
56    #[cfg(feature = "gvariant")]
57    pub fn new_gvariant(endian: Endian, position: usize) -> Self {
58        Self::new(Format::GVariant, endian, position)
59    }
60
61    /// The [`Format`] of this context.
62    pub fn format(self) -> Format {
63        self.format
64    }
65
66    /// The [`Endian`] of this context.
67    pub fn endian(self) -> Endian {
68        self.endian
69    }
70
71    /// The byte position of the value to be encoded or decoded, in the entire message.
72    pub fn position(self) -> usize {
73        self.position
74    }
75}