glycin_common/
binary_data.rs

1use std::ops::Deref;
2use std::os::fd::{AsRawFd, OwnedFd};
3use std::sync::Arc;
4
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6
7#[derive(zvariant::Type, Debug, Clone)]
8#[zvariant(signature = "h")]
9pub struct BinaryData {
10    pub(crate) memfd: Arc<zvariant::OwnedFd>,
11}
12
13impl Serialize for BinaryData {
14    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
15    where
16        S: Serializer,
17    {
18        self.memfd.serialize(serializer)
19    }
20}
21
22impl<'de> Deserialize<'de> for BinaryData {
23    fn deserialize<D>(deserializer: D) -> Result<BinaryData, D::Error>
24    where
25        D: Deserializer<'de>,
26    {
27        Ok(Self {
28            memfd: Arc::new(zvariant::OwnedFd::deserialize(deserializer)?),
29        })
30    }
31}
32
33impl AsRawFd for BinaryData {
34    fn as_raw_fd(&self) -> std::os::unix::prelude::RawFd {
35        self.memfd.as_raw_fd()
36    }
37}
38
39impl AsRawFd for &BinaryData {
40    fn as_raw_fd(&self) -> std::os::unix::prelude::RawFd {
41        self.memfd.as_raw_fd()
42    }
43}
44
45impl From<OwnedFd> for BinaryData {
46    fn from(value: OwnedFd) -> Self {
47        let owned_fd = zvariant::OwnedFd::from(value);
48        BinaryData {
49            memfd: Arc::new(owned_fd),
50        }
51    }
52}
53
54impl BinaryData {
55    /// Get a copy of the binary data
56    pub fn get_full(&self) -> std::io::Result<Vec<u8>> {
57        Ok(self.get()?.to_vec())
58    }
59
60    /// Get a reference to the binary data
61    pub fn get(&self) -> std::io::Result<BinaryDataRef> {
62        Ok(BinaryDataRef {
63            mmap: { unsafe { memmap::MmapOptions::new().map_copy_read_only(&self.memfd)? } },
64        })
65    }
66}
67
68#[derive(Debug)]
69pub struct BinaryDataRef {
70    mmap: memmap::Mmap,
71}
72
73impl Deref for BinaryDataRef {
74    type Target = [u8];
75
76    fn deref(&self) -> &[u8] {
77        self.mmap.deref()
78    }
79}
80
81impl AsRef<[u8]> for BinaryDataRef {
82    fn as_ref(&self) -> &[u8] {
83        self.mmap.deref()
84    }
85}