1use crate::error::{BinaryError, Result};
2use crate::zlib_pool::decompress_zlib_pooled;
3use bytes::{Buf, Bytes, BytesMut};
4use std::borrow::Cow;
5
6pub(crate) const MAX_DECOMPRESSED_SIZE: u64 = 16 * 1024 * 1024;
8
9pub const FORMAT_PLAIN: u8 = 0;
17
18pub const FORMAT_COMPRESSED: u8 = 2;
21
22pub fn check_plain_payload(data: &[u8]) -> Result<()> {
31 match data.split_first() {
32 Some((&format, _)) if format != FORMAT_PLAIN => {
33 Err(BinaryError::UnexpectedFormatByte(format))
34 }
35 Some((_, node_bytes)) if !node_bytes.is_empty() => Ok(()),
36 _ => Err(BinaryError::EmptyData),
38 }
39}
40
41pub fn pack(node_bytes: &[u8]) -> Vec<u8> {
44 let mut packed = Vec::with_capacity(node_bytes.len() + 1);
45 packed.push(FORMAT_PLAIN);
46 packed.extend_from_slice(node_bytes);
47 packed
48}
49
50fn decompress_zlib(compressed: &[u8]) -> Result<Vec<u8>> {
51 decompress_zlib_pooled(compressed, MAX_DECOMPRESSED_SIZE)
52 .map_err(|e| BinaryError::Zlib(e.to_string()))
53}
54
55pub fn unpack(data: &[u8]) -> Result<Cow<'_, [u8]>> {
58 if data.is_empty() {
59 return Err(BinaryError::EmptyData);
60 }
61 let data_type = data[0];
62 let data = &data[1..];
63
64 if (data_type & FORMAT_COMPRESSED) > 0 {
65 Ok(Cow::Owned(decompress_zlib(data)?))
66 } else {
67 Ok(Cow::Borrowed(data))
68 }
69}
70
71pub fn unpack_bytes(mut data: BytesMut) -> Result<Bytes> {
77 if data.is_empty() {
78 return Err(BinaryError::EmptyData);
79 }
80 let data_type = data[0];
81
82 if (data_type & FORMAT_COMPRESSED) > 0 {
83 Ok(Bytes::from(decompress_zlib(&data[1..])?))
84 } else {
85 data.advance(1);
86 Ok(data.freeze())
87 }
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93 use crate::marshal::{marshal, unmarshal_packed_ref, unmarshal_ref};
94 use crate::node::{Attrs, Node, NodeContent, NodeValue, OwnedNodeRef};
95
96 fn shapes() -> Vec<(&'static str, Node)> {
99 let mut attrs = Attrs::with_capacity(3);
100 attrs.push("id".to_string(), "ABC123");
101 attrs.push("hex".to_string(), NodeValue::from("DEADBEEF"));
102 attrs.push("nibble".to_string(), NodeValue::from("12-345.6"));
103
104 vec![
105 (
106 "children",
107 Node::new(
108 "iq",
109 attrs.clone(),
110 Some(NodeContent::Nodes(vec![
111 Node::new("ping", Attrs::new(), None),
112 Node::new(
113 "text",
114 Attrs::new(),
115 Some(NodeContent::String("hello".into())),
116 ),
117 ])),
118 ),
119 ),
120 (
121 "binary body",
122 Node::new(
123 "message",
124 Attrs::new(),
125 Some(NodeContent::Bytes(vec![0xAB; 512])),
126 ),
127 ),
128 ("packed attrs", Node::new("receipt", attrs, None)),
129 ]
130 }
131
132 #[test]
136 fn a_decoded_stanza_packs_back_to_the_bytes_it_arrived_as() {
137 for (shape, node) in shapes() {
138 let packed = marshal(&node).expect("marshal");
139 let node_bytes = unpack(&packed).expect("unpack").into_owned();
140 let owned = OwnedNodeRef::new(node_bytes).expect("decode");
141
142 let forwarded = pack(&owned.backing_bytes());
143 assert_eq!(
144 forwarded, packed,
145 "{shape}: pack(backing_bytes) must reproduce the marshal output"
146 );
147 assert_eq!(
148 unmarshal_packed_ref(&forwarded)
149 .expect("the forwarded payload decodes")
150 .to_owned(),
151 owned.to_owned_node(),
152 "{shape}: the forwarded stanza is still the same node"
153 );
154 }
155 }
156
157 #[test]
160 fn unpack_bytes_strips_the_same_byte_as_unpack() {
161 for (shape, node) in shapes() {
162 let packed = marshal(&node).expect("marshal");
163 let owned = unpack_bytes(BytesMut::from(&packed[..])).expect("unpack_bytes");
164
165 assert_eq!(
166 owned.as_ref(),
167 unpack(&packed).expect("unpack").as_ref(),
168 "{shape}"
169 );
170 assert_eq!(pack(&owned), packed, "{shape}");
171 }
172 }
173
174 #[test]
178 fn the_format_byte_is_uncompressed_and_the_decoder_never_reads_it() {
179 let node = Node::new("iq", Attrs::new(), None);
180 let packed = marshal(&node).expect("marshal");
181
182 assert_eq!(packed[0], FORMAT_PLAIN);
183 assert_eq!(FORMAT_PLAIN, 0);
184 assert_eq!(FORMAT_COMPRESSED, 2);
185
186 assert!(unmarshal_ref(&packed[1..]).is_ok());
188 assert!(unmarshal_ref(&packed).is_err());
190 }
191
192 #[test]
195 fn node_bytes_are_refused_where_a_packed_payload_belongs() {
196 let node = Node::new(
197 "iq",
198 Attrs::new(),
199 Some(NodeContent::Nodes(vec![Node::new(
200 "ping",
201 Attrs::new(),
202 None,
203 )])),
204 );
205 let packed = marshal(&node).expect("marshal");
206 let node_bytes = unpack(&packed).expect("unpack").into_owned();
207
208 assert!(check_plain_payload(&packed).is_ok());
209 assert!(matches!(
210 check_plain_payload(&node_bytes),
211 Err(BinaryError::UnexpectedFormatByte(byte)) if byte == node_bytes[0]
212 ));
213 assert!(matches!(
216 check_plain_payload(&[]),
217 Err(BinaryError::EmptyData)
218 ));
219 assert!(matches!(
220 check_plain_payload(&[FORMAT_PLAIN]),
221 Err(BinaryError::EmptyData)
222 ));
223 let mut compressed = packed.clone();
226 compressed[0] = FORMAT_COMPRESSED;
227 assert!(matches!(
228 check_plain_payload(&compressed),
229 Err(BinaryError::UnexpectedFormatByte(FORMAT_COMPRESSED))
230 ));
231
232 assert!(unmarshal_packed_ref(&packed).is_ok());
233 assert!(matches!(
234 unmarshal_packed_ref(&node_bytes),
235 Err(BinaryError::UnexpectedFormatByte(byte)) if byte == node_bytes[0]
236 ));
237 assert!(matches!(
238 unmarshal_packed_ref(&[]),
239 Err(BinaryError::EmptyData)
240 ));
241 }
242}