Debian Codegraph @

third_party/rust/audioipc2/src/codec.rs

raw
1 // Copyright © 2017 Mozilla Foundation
2 //
3 // This program is made available under an ISC-style license. See the
4 // accompanying file LICENSE for details
5
6 //! `Encoder`s and `Decoder`s from items to/from `BytesMut` buffers.
7
8 // The assert in LengthDelimitedCodec::decode triggers this clippy warning but
9 // requires upgrading the workspace to Rust 2021 to resolve.
10 // This should be fixed in Rust 1.68, after which the following `allow` can be deleted.
11 #![allow(clippy::uninlined_format_args)]
12
13 use bincode::Options;
14 use byteorder::{ByteOrder, LittleEndian};
15 use bytes::{Buf, BufMut, BytesMut};
16 use serde::de::DeserializeOwned;
17 use serde::ser::Serialize;
18 use std::convert::TryInto;
19 use std::fmt::Debug;
20 use std::io;
21 use std::marker::PhantomData;
22 use std::mem::size_of;
23
24 ////////////////////////////////////////////////////////////////////////////////
25 // Split buffer into size delimited frames - This appears more complicated than
26 // might be necessary due to handling the possibility of messages being split
27 // across reads.
28
29 pub trait Codec {
30 /// The type of items to be encoded into byte buffer
31 type In;
32
33 /// The type of items to be returned by decoding from byte buffer
34 type Out;
35
36 /// Attempts to decode a frame from the provided buffer of bytes.
37 fn decode(&mut self, buf: &mut BytesMut) -> io::Result<Option<Self::Out>>;
38
39 /// A default method available to be called when there are no more bytes
40 /// available to be read from the I/O.
41 fn decode_eof(&mut self, buf: &mut BytesMut) -> io::Result<Self::Out> {
42 match self.decode(buf)? {
43 Some(frame) => Ok(frame),
44 None => Err(io::Error::new(
45 io::ErrorKind::Other,
46 "bytes remaining on stream",
47 )),
48 }
49 }
50
51 /// Encodes a frame into the buffer provided.
52 fn encode(&mut self, msg: Self::In, buf: &mut BytesMut) -> io::Result<()>;
53 }
54
55 /// Codec based upon bincode serialization
56 ///
57 /// Messages that have been serialized using bincode are prefixed with
58 /// the length of the message to aid in deserialization, so that it's
59 /// known if enough data has been received to decode a complete
60 /// message.
61 pub struct LengthDelimitedCodec<In, Out> {
62 state: State,
63 encode_buf: Vec<u8>,
64 __in: PhantomData<In>,
65 __out: PhantomData<Out>,
66 }
67
68 enum State {
69 Length,
70 Data(u32),
71 }
72
73 const MAX_MESSAGE_LEN: u32 = 1024 * 1024;
74 const MAGIC: u64 = 0xa4d1_019c_c910_1d4a;
75 const HEADER_LEN: usize = size_of::<u32>() + size_of::<u64>();
76
77 impl<In, Out> Default for LengthDelimitedCodec<In, Out> {
78 fn default() -> Self {
79 Self {
80 state: State::Length,
81 encode_buf: Vec::with_capacity(crate::ipccore::IPC_CLIENT_BUFFER_SIZE),
82 __in: PhantomData,
83 __out: PhantomData,
84 }
85 }
86 }
87
88 impl<In, Out> LengthDelimitedCodec<In, Out> {
89 // Lengths are encoded as little endian u32
90 fn decode_length(buf: &mut BytesMut) -> Option<u32> {
91 if buf.len() < HEADER_LEN {
92 // Not enough data
93 return None;
94 }
95
96 let magic = LittleEndian::read_u64(&buf[0..8]);
97 assert_eq!(magic, MAGIC);
98
99 // Consume the length field
100 let n = LittleEndian::read_u32(&buf[8..12]);
101 buf.advance(HEADER_LEN);
102 Some(n)
103 }
104
105 fn decode_data(buf: &mut BytesMut, n: u32) -> io::Result<Option<Out>>
106 where
107 Out: DeserializeOwned + Debug,
108 {
109 let n = n.try_into().unwrap();
110
111 // At this point, the buffer has already had the required capacity
112 // reserved. All there is to do is read.
113 if buf.len() < n {
114 return Ok(None);
115 }
116
117 trace!("Attempting to decode");
118 let msg = bincode::options()
119 .with_limit(MAX_MESSAGE_LEN as u64)
120 .deserialize::<Out>(&buf[..n])
121 .map_err(|e| match *e {
122 bincode::ErrorKind::Io(e) => e,
123 _ => io::Error::new(io::ErrorKind::Other, *e),
124 })?;
125 buf.advance(n);
126
127 trace!("... Decoded {:?}", msg);
128 Ok(Some(msg))
129 }
130 }
131
132 impl<In, Out> Codec for LengthDelimitedCodec<In, Out>
133 where
134 In: Serialize + Debug,
135 Out: DeserializeOwned + Debug,
136 {
137 type In = In;
138 type Out = Out;
139
140 fn decode(&mut self, buf: &mut BytesMut) -> io::Result<Option<Self::Out>> {
141 let n = match self.state {
142 State::Length => {
143 match Self::decode_length(buf) {
144 Some(n) => {
145 assert!(
146 n <= MAX_MESSAGE_LEN,
147 "assertion failed: {} <= {}",
148 n,
149 MAX_MESSAGE_LEN
150 );
151 self.state = State::Data(n);
152
153 // Ensure that the buffer has enough space to read the
154 // incoming payload
155 buf.reserve(n.try_into().unwrap());
156
157 n
158 }
159 None => return Ok(None),
160 }
161 }
162 State::Data(n) => n,
163 };
164
165 match Self::decode_data(buf, n)? {
166 Some(data) => {
167 // Update the decode state
168 self.state = State::Length;
169
170 // Make sure the buffer has enough space to read the next length header.
171 buf.reserve(HEADER_LEN);
172
173 Ok(Some(data))
174 }
175 None => Ok(None),
176 }
177 }
178
179 fn encode(&mut self, item: Self::In, buf: &mut BytesMut) -> io::Result<()> {
180 trace!("Attempting to encode");
181
182 self.encode_buf.clear();
183 if let Err(e) = bincode::options()
184 .with_limit(MAX_MESSAGE_LEN as u64)
185 .serialize_into::<_, Self::In>(&mut self.encode_buf, &item)
186 {
187 trace!("message encode failed: {:?}", *e);
188 match *e {
189 bincode::ErrorKind::Io(e) => return Err(e),
190 _ => return Err(io::Error::new(io::ErrorKind::Other, *e)),
191 }
192 }
193
194 let encoded_len = self.encode_buf.len();
195 assert!(encoded_len <= MAX_MESSAGE_LEN as usize);
196 buf.reserve(encoded_len + HEADER_LEN);
197 buf.put_u64_le(MAGIC);
198 buf.put_u32_le(encoded_len.try_into().unwrap());
199 buf.extend_from_slice(&self.encode_buf);
200
201 Ok(())
202 }
203 }