tokio_dbus/
write.rs

1use crate::{buf::UnalignedBuf, BodyBuf, Signature};
2
3pub(crate) mod sealed {
4    pub trait Sealed {}
5}
6
7/// A type who's reference can be written directly to a buffer.
8///
9/// These types are written using methods such as [`BodyBuf::store`].
10///
11/// [`BodyBuf::store`]: crate::BodyBuf::store
12pub trait Write: self::sealed::Sealed {
13    /// The signature of the type.
14    #[doc(hidden)]
15    const SIGNATURE: &'static Signature;
16
17    /// Write `self` into `buf`.
18    #[doc(hidden)]
19    fn write_to(&self, buf: &mut BodyBuf);
20
21    /// Write `self` into `buf`.
22    #[doc(hidden)]
23    fn write_to_unaligned(&self, buf: &mut UnalignedBuf);
24}
25
26impl self::sealed::Sealed for [u8] {}
27
28/// Write a byte array to the buffer.
29///
30/// # Examples
31///
32/// ```
33/// use tokio_dbus::BodyBuf;
34///
35/// let mut buf = BodyBuf::new();
36/// buf.store(&b"foo"[..]);
37///
38/// assert_eq!(buf.signature(), "ay");
39/// assert_eq!(buf.get(), &[3, 0, 0, 0, 102, 111, 111]);
40/// # Ok::<_, tokio_dbus::Error>(())
41/// ```
42impl Write for [u8] {
43    const SIGNATURE: &'static Signature = Signature::new_const(b"ay");
44
45    #[inline]
46    fn write_to(&self, buf: &mut BodyBuf) {
47        buf.store_frame(self.len() as u32);
48        buf.extend_from_slice(self);
49    }
50
51    #[inline]
52    fn write_to_unaligned(&self, buf: &mut UnalignedBuf) {
53        buf.store(self.len() as u32);
54        buf.extend_from_slice(self);
55    }
56}
57
58impl_traits_for_write!([u8], &b"abcd"[..], "qay");
59
60impl self::sealed::Sealed for str {}
61
62/// Write a length-prefixed string to the buffer.
63///
64/// # Examples
65///
66/// ```
67/// use tokio_dbus::{BodyBuf, Signature};
68///
69/// let mut buf = BodyBuf::new();
70/// buf.store("foo");
71///
72/// assert_eq!(buf.signature(), Signature::STRING);
73/// assert_eq!(buf.get(), &[3, 0, 0, 0, 102, 111, 111, 0])
74/// ```
75impl Write for str {
76    const SIGNATURE: &'static Signature = Signature::STRING;
77
78    #[inline]
79    fn write_to(&self, buf: &mut BodyBuf) {
80        buf.store_frame(self.len() as u32);
81        buf.extend_from_slice_nul(self.as_bytes());
82    }
83
84    #[inline]
85    fn write_to_unaligned(&self, buf: &mut UnalignedBuf) {
86        buf.store(self.len() as u32);
87        buf.extend_from_slice_nul(self.as_bytes());
88    }
89}
90
91impl_traits_for_write!(str, "Hello World", "qs");