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 #[expect(clippy::ref_option, reason = "`#[wire(with)]` passes the field by reference")]
166 pub fn write(bytes: &Option<Arc<Vec<u8>>>, w: &mut crate::Writer<'_>) {
167 match bytes {
168 None => w.push(0),
169 Some(bytes) => {
170 w.push(1);
171 super::write(bytes, w);
172 }
173 }
174 }
175
176 #[expect(clippy::option_option, reason = "a read that can fail, of an `Option`")]
177 pub fn read(r: &mut crate::Reader<'_>) -> Option<Option<Arc<Vec<u8>>>> {
178 match r.byte()? {
179 0 => Some(None),
180 1 => super::read(r).map(Some),
181 _ => r.fail("invalid option"),
182 }
183 }
184 }
185}
186
187pub mod pod {
189 use super::Payload;
190
191 pub fn write<T: bytemuck::Pod>(values: &[T], w: &mut crate::Writer<'_>) {
192 super::write(bytemuck::cast_slice(values), w);
193 }
194
195 pub fn read<T: bytemuck::Pod>(r: &mut crate::Reader<'_>) -> Option<Vec<T>> {
196 Some(match read_payload::<T>(r)? {
197 Payload::Bytes(bytes) => bytemuck::pod_collect_to_vec(&bytes),
198 #[cfg(target_family = "wasm")]
199 Payload::Host(bytes) => bytes.to_pod_vec(),
200 })
201 }
202
203 pub fn read_payload<T: bytemuck::Pod>(r: &mut crate::Reader<'_>) -> Option<Payload> {
205 let bytes = super::read_payload(r)?;
206 if !bytes.len().is_multiple_of(size_of::<T>()) {
207 return r.fail("bytes that are not a whole number of values");
208 }
209 Some(bytes)
210 }
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216
217 #[derive(Debug, PartialEq, crate::Wire)]
218 struct Message {
219 #[wire(with = "bytes")]
220 small: Vec<u8>,
221 #[wire(with = "bytes")]
222 large: Vec<u8>,
223 #[wire(with = "pod")]
224 values: Vec<[u16; 2]>,
225 }
226
227 fn message() -> Message {
228 Message { small: vec![1, 2, 3], large: vec![7; PAYLOAD_MIN], values: vec![[1, 2]; PAYLOAD_MIN] }
229 }
230
231 #[test]
234 fn large_arrays_travel_beside_the_message() {
235 let mut payloads = Payloads::new();
236 let bytes = crate::to_vec_in(&message(), &mut payloads).unwrap();
237 let payloads = payloads.into_vec();
238 assert_eq!(payloads.len(), 2);
239 assert!(bytes.len() < 32);
240 let decoded: Message = crate::from_slice_in(&bytes, Payloads::from(payloads)).unwrap();
241 assert_eq!(decoded, message());
242
243 let inline = crate::to_vec(&message()).unwrap();
244 assert!(inline.len() > 5 * PAYLOAD_MIN);
245 assert_eq!(crate::from_slice::<Message>(&inline).unwrap(), message());
246 }
247
248 #[test]
250 fn missing_payloads_are_errors() {
251 let bytes = crate::to_vec_in(&message(), Payloads::new()).unwrap();
252 assert!(crate::from_slice_in::<Message>(&bytes, Payloads::new()).is_err());
253 }
254}