Skip to main content

mln_wire/
payload.rs

1//! Byte arrays that travel beside a message.
2//!
3//! In a message written with [`Payloads`] in its context, an array of at
4//! least `PAYLOAD_MIN` bytes is not written into the message: it is moved to
5//! the payloads, and the message refers to it by index. Reading the message
6//! with its payloads in the context gives them back to the arrays that refer
7//! to them, as they are. Fields opt in with `#[wire(with = "...")]`: `bytes`
8//! for a `Vec<u8>`, `shared_bytes` for an `Arc<Vec<u8>>` and `pod` for a
9//! `Vec` of plain values (vertices, indices). Without payloads in the
10//! context the arrays are written in the message.
11//!
12//! On wasm a host can hand over its payloads as the JS arrays they arrived
13//! in (`Payload::Host`). Each field copies its array into wasm memory, but
14//! for `pod::read_payload`, whose caller can keep it in JS.
15
16#[cfg(target_family = "wasm")]
17use crate::host_bytes::HostBytes;
18
19/// A payload as a message is read with it.
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub enum Payload {
22    Bytes(Vec<u8>),
23    /// A JS array, outside wasm memory.
24    #[cfg(target_family = "wasm")]
25    Host(HostBytes),
26}
27
28impl Payload {
29    /// The number of bytes.
30    #[must_use]
31    pub fn len(&self) -> usize {
32        match self {
33            Payload::Bytes(bytes) => bytes.len(),
34            #[cfg(target_family = "wasm")]
35            Payload::Host(bytes) => bytes.len(),
36        }
37    }
38
39    #[must_use]
40    pub fn is_empty(&self) -> bool {
41        self.len() == 0
42    }
43
44    /// The bytes in wasm memory: a JS array's, copied.
45    #[must_use]
46    pub fn into_vec(self) -> Vec<u8> {
47        match self {
48            Payload::Bytes(bytes) => bytes,
49            #[cfg(target_family = "wasm")]
50            Payload::Host(bytes) => bytes.to_vec(),
51        }
52    }
53}
54
55impl From<Vec<u8>> for Payload {
56    fn from(bytes: Vec<u8>) -> Self {
57        Payload::Bytes(bytes)
58    }
59}
60
61/// The smallest array that travels as a payload.
62pub(crate) const PAYLOAD_MIN: usize = 4096;
63
64/// The payloads of one message, as a part of the context it is written or
65/// read in: those written so far, or those not read yet.
66#[derive(Debug, Default)]
67pub struct Payloads(Vec<Option<Payload>>);
68
69impl Payloads {
70    /// The payloads of a message to write.
71    #[must_use]
72    pub fn new() -> Self {
73        Payloads::default()
74    }
75
76    /// The payloads written.
77    #[must_use]
78    pub fn into_vec(self) -> Vec<Payload> {
79        self.0.into_iter().flatten().collect()
80    }
81}
82
83/// The payloads of a message to read.
84impl From<Vec<Payload>> for Payloads {
85    fn from(payloads: Vec<Payload>) -> Self {
86        Payloads(payloads.into_iter().map(Some).collect())
87    }
88}
89
90impl crate::Context for Payloads {
91    fn provide<'a>(&'a mut self, request: &mut crate::Request<'a>) {
92        request.give_mut(self);
93    }
94}
95
96/// Writes an array: 0 and the bytes in the message, or 1 and the index of
97/// the payload it moved to.
98fn write(bytes: &[u8], w: &mut crate::Writer) {
99    let index = if bytes.len() >= PAYLOAD_MIN {
100        w.context_mut::<Payloads>().map(|Payloads(payloads)| {
101            payloads.push(Some(Payload::Bytes(bytes.to_vec())));
102            payloads.len() - 1
103        })
104    } else {
105        None
106    };
107    if let Some(index) = index {
108        w.push(1);
109        crate::write_varint(w, index as u64);
110    } else {
111        w.push(0);
112        crate::write_varint(w, bytes.len() as u64);
113        w.extend_from_slice(bytes);
114    }
115}
116
117/// Reads what `write` wrote.
118fn read_payload(r: &mut crate::Reader<'_>) -> Option<Payload> {
119    match r.byte()? {
120        0 => {
121            let len = r.length()?;
122            Some(Payload::Bytes(r.take(len)?.to_vec()))
123        }
124        1 => {
125            let index = r.varint()?;
126            let payload =
127                usize::try_from(index).ok().and_then(|index| r.context_mut::<Payloads>()?.0.get_mut(index)?.take());
128            payload.or_else(|| r.fail("a payload the message doesn't have"))
129        }
130        _ => r.fail_tag(),
131    }
132}
133
134fn read(r: &mut crate::Reader<'_>) -> Option<Vec<u8>> {
135    read_payload(r).map(Payload::into_vec)
136}
137
138/// A `Vec<u8>`.
139pub mod bytes {
140    pub fn write(bytes: &[u8], w: &mut crate::Writer) {
141        super::write(bytes, w);
142    }
143
144    pub fn read(r: &mut crate::Reader<'_>) -> Option<Vec<u8>> {
145        super::read(r)
146    }
147}
148
149/// An `Arc<Vec<u8>>` (encoded tile data and images).
150pub mod shared_bytes {
151    use std::sync::Arc;
152
153    pub fn write(bytes: &Arc<Vec<u8>>, w: &mut crate::Writer) {
154        super::write(bytes, w);
155    }
156
157    pub fn read(r: &mut crate::Reader<'_>) -> Option<Arc<Vec<u8>>> {
158        super::read(r).map(Arc::new)
159    }
160
161    /// An `Option<Arc<Vec<u8>>>`.
162    pub mod option {
163        use std::sync::Arc;
164
165        pub fn write(bytes: &Option<Arc<Vec<u8>>>, w: &mut crate::Writer) {
166            match bytes {
167                None => w.push(0),
168                Some(bytes) => {
169                    w.push(1);
170                    super::write(bytes, w);
171                }
172            }
173        }
174
175        pub fn read(r: &mut crate::Reader<'_>) -> Option<Option<Arc<Vec<u8>>>> {
176            match r.byte()? {
177                0 => Some(None),
178                1 => super::read(r).map(Some),
179                _ => r.fail("invalid option"),
180            }
181        }
182    }
183}
184
185/// A `Vec` of plain values, as their bytes.
186pub mod pod {
187    use super::Payload;
188
189    pub fn write<T: bytemuck::Pod>(values: &[T], w: &mut crate::Writer) {
190        super::write(bytemuck::cast_slice(values), w);
191    }
192
193    pub fn read<T: bytemuck::Pod>(r: &mut crate::Reader<'_>) -> Option<Vec<T>> {
194        Some(match read_payload::<T>(r)? {
195            Payload::Bytes(bytes) => bytemuck::pod_collect_to_vec(&bytes),
196            #[cfg(target_family = "wasm")]
197            Payload::Host(bytes) => bytes.to_pod_vec(),
198        })
199    }
200
201    /// The values' bytes as they arrived, a whole number of `T`s.
202    pub fn read_payload<T: bytemuck::Pod>(r: &mut crate::Reader<'_>) -> Option<Payload> {
203        let bytes = super::read_payload(r)?;
204        if !bytes.len().is_multiple_of(size_of::<T>()) {
205            return r.fail("bytes that are not a whole number of values");
206        }
207        Some(bytes)
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    #[derive(Debug, PartialEq, crate::Wire)]
216    struct Message {
217        #[wire(with = "bytes")]
218        small: Vec<u8>,
219        #[wire(with = "bytes")]
220        large: Vec<u8>,
221        #[wire(with = "pod")]
222        values: Vec<[u16; 2]>,
223    }
224
225    fn message() -> Message {
226        Message { small: vec![1, 2, 3], large: vec![7; PAYLOAD_MIN], values: vec![[1, 2]; PAYLOAD_MIN] }
227    }
228
229    /// With payloads in the context, the large arrays travel beside the
230    /// message; without, everything is in it.
231    #[test]
232    fn large_arrays_travel_beside_the_message() {
233        let mut payloads = Payloads::new();
234        let bytes = crate::to_vec_in(&message(), &mut payloads).unwrap();
235        let payloads = payloads.into_vec();
236        assert_eq!(payloads.len(), 2);
237        assert!(bytes.len() < 32);
238        let decoded: Message = crate::from_slice_in(&bytes, Payloads::from(payloads)).unwrap();
239        assert_eq!(decoded, message());
240
241        let inline = crate::to_vec(&message()).unwrap();
242        assert!(inline.len() > 5 * PAYLOAD_MIN);
243        assert_eq!(crate::from_slice::<Message>(&inline).unwrap(), message());
244    }
245
246    /// A message that refers to a payload it doesn't have is malformed.
247    #[test]
248    fn missing_payloads_are_errors() {
249        let bytes = crate::to_vec_in(&message(), Payloads::new()).unwrap();
250        assert!(crate::from_slice_in::<Message>(&bytes, Payloads::new()).is_err());
251    }
252}