Debian Codegraph @

src/binary_data.rs

raw symbols SCIP
1 use std::ops::Deref;
2 use std::os::fd::{AsRawFd, OwnedFd};
3 use std::sync::Arc;
4
5 use serde::{Deserialize, Deserializer, Serialize, Serializer};
6
7 #[derive(zvariant::Type, Debug, Clone)]
8 #[zvariant(signature = "h")]
9 pub struct BinaryData {
10 pub(crate) memfd: Arc<zvariant::OwnedFd>,
11 }
12
13 impl 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
22 impl<'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
33 impl AsRawFd for BinaryData {
34 fn as_raw_fd(&self) -> std::os::unix::prelude::RawFd {
35 self.memfd.as_raw_fd()
36 }
37 }
38
39 impl AsRawFd for &BinaryData {
40 fn as_raw_fd(&self) -> std::os::unix::prelude::RawFd {
41 self.memfd.as_raw_fd()
42 }
43 }
44
45 impl 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
54 impl 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)]
69 pub struct BinaryDataRef {
70 mmap: memmap::Mmap,
71 }
72
73 impl Deref for BinaryDataRef {
74 type Target = [u8];
75
76 fn deref(&self) -> &[u8] {
77 self.mmap.deref()
78 }
79 }
80
81 impl AsRef<[u8]> for BinaryDataRef {
82 fn as_ref(&self) -> &[u8] {
83 self.mmap.deref()
84 }
85 }