1#[cfg(target_family = "wasm")]
17use crate::host_bytes::HostBytes;
18
19#[derive(Clone, Debug, PartialEq, Eq)]
21pub enum Payload {
22 Bytes(Vec<u8>),
23 #[cfg(target_family = "wasm")]
25 Host(HostBytes),
26}
27
28impl Payload {
29 #[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 #[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
61pub(crate) const PAYLOAD_MIN: usize = 4096;
63
64#[derive(Debug, Default)]
67pub struct Payloads(Vec<Option<Payload>>);
68
69impl Payloads {
70 #[must_use]
72 pub fn new() -> Self {
73 Payloads::default()
74 }
75
76 #[must_use]
78 pub fn into_vec(self) -> Vec<Payload> {
79 self.0.into_iter().flatten().collect()
80 }
81}
82
83impl 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
96fn 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
117fn 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
138pub 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
149pub 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 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
185pub 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 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 #[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 #[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}