Debian Codegraph @

src/common/bin_serde.rs

raw symbols SCIP
1 //! Binary serialization, and an implementation over Unix pipes.
2 use sealed::DeSerializeBytes;
3 use std::{
4 io::{self, Read, Write},
5 marker::PhantomData,
6 os::{
7 fd::{AsFd, BorrowedFd},
8 unix::net::UnixStream,
9 },
10 };
11
12 mod sealed {
13 pub trait DeSerializeBytes {
14 fn zero_init() -> Self;
15 fn as_mut_ref(&mut self) -> &mut [u8];
16 }
17
18 impl<const N: usize> DeSerializeBytes for [u8; N] {
19 fn zero_init() -> [u8; N] {
20 [0; N]
21 }
22 fn as_mut_ref(&mut self) -> &mut [u8] {
23 self.as_mut_slice()
24 }
25 }
26 }
27
28 /// Serialization/deserialization trait using a byte array as storage.
29 pub trait DeSerialize {
30 /// Usually `[u8; std::mem::size_of::<Self>()]`.
31 type Bytes: sealed::DeSerializeBytes;
32 fn serialize(&self) -> Self::Bytes;
33 fn deserialize(bytes: Self::Bytes) -> Self;
34 }
35
36 /// A binary pipe that can send and receive typed messages.
37 ///
38 /// By default, if only one generic is included,
39 /// the types of the [BinPipe::write()] and [BinPipe::read()] messages
40 /// are the same.
41 pub struct BinPipe<R: DeSerialize, W: DeSerialize = R> {
42 sock: UnixStream,
43 _read_marker: PhantomData<R>,
44 _write_marker: PhantomData<W>,
45 }
46
47 impl<R: DeSerialize, W: DeSerialize> BinPipe<R, W> {
48 /// A pipe abstracting over a [UnixStream] with easier
49 /// binary serialization, to help with the buffer sizes and ser/de steps.
50 /// Uses [UnixStream::pair()].
51 pub fn pair() -> io::Result<(BinPipe<R, W>, BinPipe<W, R>)> {
52 let (first, second) = UnixStream::pair()?;
53 Ok((
54 BinPipe {
55 sock: first,
56 _read_marker: PhantomData::<R>,
57 _write_marker: PhantomData::<W>,
58 },
59 // R and W are inverted here since the type of what's written in one
60 // pipe is read in the other, and vice versa.
61 BinPipe {
62 sock: second,
63 _read_marker: PhantomData::<W>,
64 _write_marker: PhantomData::<R>,
65 },
66 ))
67 }
68
69 /// Read a `R` from the pipe.
70 pub fn read(&mut self) -> io::Result<R> {
71 let mut bytes = R::Bytes::zero_init();
72 self.sock.read_exact(bytes.as_mut_ref())?;
73 Ok(R::deserialize(bytes))
74 }
75
76 /// Write a `W` to the pipe.
77 pub fn write(&mut self, bytes: &W) -> io::Result<()> {
78 self.sock.write_all(bytes.serialize().as_mut_ref())?;
79 Ok(())
80 }
81
82 /// Calls [std::net::TcpStream::set_nonblocking] on the underlying socket.
83 #[cfg(debug_assertions)]
84 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
85 self.sock.set_nonblocking(nonblocking)
86 }
87 }
88
89 impl<R: DeSerialize, W: DeSerialize> AsFd for BinPipe<R, W> {
90 fn as_fd(&self) -> BorrowedFd<'_> {
91 self.sock.as_fd()
92 }
93 }
94
95 impl DeSerialize for i32 {
96 type Bytes = [u8; std::mem::size_of::<Self>()];
97
98 fn serialize(&self) -> Self::Bytes {
99 self.to_ne_bytes()
100 }
101 fn deserialize(bytes: Self::Bytes) -> Self {
102 Self::from_ne_bytes(bytes)
103 }
104 }
105
106 #[cfg(test)]
107 mod tests {
108 use super::*;
109
110 #[test]
111 pub fn single_type() {
112 let (mut tx, mut rx) = BinPipe::pair().unwrap();
113 tx.write(&42i32).unwrap();
114 assert_eq!(rx.read().unwrap(), 42);
115 rx.write(&23i32).unwrap();
116 assert_eq!(tx.read().unwrap(), 23);
117 }
118
119 impl DeSerialize for u8 {
120 type Bytes = [u8; std::mem::size_of::<Self>()];
121 fn serialize(&self) -> [u8; 1] {
122 self.to_ne_bytes()
123 }
124 fn deserialize(bytes: [u8; 1]) -> Self {
125 Self::from_ne_bytes(bytes)
126 }
127 }
128
129 #[test]
130 pub fn different_types() {
131 let (mut tx, mut rx) = BinPipe::pair().unwrap();
132 tx.write(&42i32).unwrap();
133 assert_eq!(rx.read().unwrap(), 42);
134 rx.write(&23u8).unwrap();
135 assert_eq!(tx.read().unwrap(), 23);
136 }
137 }