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