1use std::collections::BTreeMap;
6
7#[derive(Default, Debug, PartialEq)]
8struct Run {
9 label: String,
10 samples: Vec<f64>,
12 valid: Vec<bool>,
14 channels: Vec<String>,
16 offsets: BTreeMap<u16, i32>,
18}
19structio::object!(Run {
20 label,
21 samples,
22 valid,
23 channels,
24 offsets
25});
26
27#[derive(Default, Debug, PartialEq)]
31struct Frame<'a> {
32 id: u32,
33 payload: &'a [u8],
34 note: &'a str,
35}
36structio::beve_object!(['de] Frame<'de> { id, payload, note });
37
38fn run() -> Run {
39 Run {
40 label: "sweep 3".into(),
41 samples: (0..1000).map(|i| i as f64 / 7.0).collect(),
42 valid: (0..1000).map(|i| i % 5 != 0).collect(),
43 channels: vec!["temp".into(), "pressure".into()],
44 offsets: BTreeMap::from([(1u16, -20), (2, 40)]),
45 }
46}
47
48fn send_frames(values: &[Run], sink: &mut impl std::io::Write) -> std::io::Result<()> {
59 let mut body = Vec::new();
60 for value in values {
61 structio::write_beve_into(value, &mut body);
64 sink.write_all(&(body.len() as u32).to_le_bytes())?;
65 sink.write_all(&body)?;
66 }
67 Ok(())
68}
69
70fn stream_frames(values: &[Run], sink: &mut impl std::io::Write) -> std::io::Result<()> {
71 for value in values {
72 sink.write_all(&(structio::beve_size(value) as u32).to_le_bytes())?;
75 structio::to_beve_writer(value, &mut *sink)?;
76 }
77 Ok(())
78}
79
80fn frame_aligned(query: &str, samples: &[f64]) -> Vec<u8> {
81 let mut frame = vec![0u8; 8]; frame.extend_from_slice(query.as_bytes());
83
84 let body = structio::beve_size_aligned_after(samples, frame.len());
88 frame[..8].copy_from_slice(&(body as u64).to_le_bytes());
89 structio::append_beve_aligned(samples, &mut frame);
90
91 frame
92}
93fn main() -> Result<(), Box<dyn std::error::Error>> {
96 let value = run();
97
98 let text = structio::to_string(&value);
100 let binary = structio::to_beve(&value);
101
102 assert_eq!(structio::from_str::<Run>(&text)?, value);
103 assert_eq!(structio::from_beve::<Run>(&binary)?, value);
104
105 println!("json {:>6} bytes", text.len());
106 println!(
107 "beve {:>6} bytes ({:.0}% of the text)",
108 binary.len(),
109 100.0 * binary.len() as f64 / text.len() as f64
110 );
111 println!(
114 " {} of those bytes are the sample payload, {} the flags",
115 value.samples.len() * 8,
116 value.valid.len().div_ceil(8)
117 );
118
119 let mut into = Run::default();
123 structio::read_beve_into(&mut into, &binary)?;
124 let at = into.samples.as_ptr();
125 structio::read_beve_into(&mut into, &binary)?;
126 assert_eq!(into.samples.as_ptr(), at, "the allocation was reused");
127
128 let frame = Frame {
130 id: 9,
131 payload: &[0xDE, 0xAD, 0xBE, 0xEF],
132 note: "no copies here",
133 };
134 let bytes = structio::to_beve(&frame);
135 let back: Frame = structio::from_beve(&bytes)?;
136 assert_eq!(back, frame);
137 let inside = (back.note.as_ptr() as usize) - (bytes.as_ptr() as usize) < bytes.len();
138 println!("borrowed fields point into the input: {inside}");
139
140 assert_eq!(
146 structio::from_beve::<Run>(&structio::to_beve_aligned(&value))?,
147 value
148 );
149 let padded = structio::to_beve_aligned(&value.samples);
150 let payload = padded.len() - value.samples.len() * 8;
151 assert_eq!(payload % 8, 0);
152 println!(
153 "the aligned form puts {} samples at byte {payload}",
154 value.samples.len()
155 );
156
157 let mut reader = structio::beve::Reader::new(&padded);
163 match reader.try_slice::<f64>() {
164 Some(block) => println!("borrowed {} samples with no copy at all", block.len()),
165 None => println!("this buffer is not one a &[f64] can point into"),
166 }
167
168 let mut file = Vec::new();
172 structio::to_beve_writer(&value, &mut file)?;
173 assert_eq!(file, binary);
174
175 let runs = [run(), run()];
177 let mut sink = Vec::new();
178 send_frames(&runs, &mut sink)?;
179
180 let mut streamed = Vec::new();
183 stream_frames(&runs, &mut streamed)?;
184 assert_eq!(streamed, sink);
185
186 let mut rest = &sink[..];
187 for want in &runs {
188 let (len, tail) = rest.split_at(4);
189 let len = u32::from_le_bytes(len.try_into()?) as usize;
190 let (frame, tail) = tail.split_at(len);
191 assert_eq!(&structio::from_beve::<Run>(frame)?, want);
192 rest = tail;
193 }
194 assert!(rest.is_empty());
195 println!("read back {} length-prefixed frames", runs.len());
196
197 for query in ["", "/sensor", "/a/rather/longer/route"] {
201 let frame = frame_aligned(query, &value.samples);
202 let base = 8 + query.len();
203 let stated = u64::from_le_bytes(frame[..8].try_into()?) as usize;
204 assert_eq!(frame.len() - base, stated);
205 assert_eq!((frame.len() - value.samples.len() * 8) % 8, 0);
206 assert_eq!(
207 structio::from_beve::<Vec<f64>>(&frame[base..])?,
208 value.samples
209 );
210 }
211 println!("aligned bodies stay aligned behind a header of any length");
212
213 assert_eq!(structio::beve_to_json(&binary)?, text);
218 let unknown = structio::beve_to_json(&structio::to_beve(&frame))?;
219 println!("a document with no declared type: {unknown}");
220
221 let archive = structio::to_beve(&vec![run(), run(), run()]);
227 let mut docs = structio::beve::Documents::array(&archive[..]).read_size(16);
228 let mut record = Run::default();
231 let mut count = 0;
232 while let Some(result) = docs.next_value_into(&mut record) {
233 result?;
234 count += 1;
235 }
236 println!(
237 "read {count} records out of {} bytes without ever holding the file",
238 archive.len()
239 );
240
241 let odd = vec![f64::NAN, f64::INFINITY, -0.0];
243 let back: Vec<f64> = structio::from_beve(&structio::to_beve(&odd))?;
244 assert!(back[0].is_nan() && back[1].is_infinite() && back[2].is_sign_negative());
245 println!("NaN, infinity, and negative zero survive the round trip");
246
247 let signal = vec![
251 structio::Complex::new(1.0f64, 2.0),
252 structio::Complex::new(3.0, -4.0),
253 ];
254 let bytes = structio::to_beve(&signal);
255 println!(
256 "{} complex samples in {} bytes: one header, one count, and the components",
257 signal.len(),
258 bytes.len()
259 );
260 assert_eq!(
261 structio::from_beve::<Vec<structio::Complex<f64>>>(&bytes)?,
262 signal
263 );
264
265 let grid = structio::Matrix::new(structio::MatrixLayout::RowMajor, vec![1, 2], signal.clone())?;
268 let bytes = structio::to_beve(&grid);
269 assert_eq!(
270 structio::from_beve::<structio::Matrix<structio::Complex<f64>>>(&bytes)?,
271 grid
272 );
273 println!("as a matrix: {}", structio::beve_to_json(&bytes)?);
274
275 #[derive(Default, Debug, PartialEq)]
281 struct JustTheLabel {
282 label: String,
283 }
284 structio::object!(JustTheLabel { label });
285
286 let partial = structio::from_beve_with::<structio::SkipUnknown, JustTheLabel>(&binary)?;
287 assert_eq!(partial.label, value.label);
288 println!("unknown members are stepped over: {:?}", partial.label);
289
290 Ok(())
291}