beve 2.0.0

Rust implementation of the BEVE (Binary Efficient Versatile Encoding) specification with serde support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
#![deny(warnings)]

use beve::Complex;
use half::{bf16, f16};
use serde::{Deserialize, Serialize};

// Minimal SIZE encoder for tests (matches src/size.rs behavior)
fn write_size_for_test(mut n: u64, out: &mut Vec<u8>) {
    if n < (1 << 6) {
        out.push((n as u8) << 2);
        return;
    }
    if n < (1 << 14) {
        out.push((((n & 0x3f) as u8) << 2) | 0b01);
        n >>= 6;
        out.push(n as u8);
        return;
    }
    if n < (1 << 30) {
        out.push((((n & 0x3f) as u8) << 2) | 0b10);
        n >>= 6;
        out.push(n as u8);
        out.push((n >> 8) as u8);
        out.push((n >> 16) as u8);
        return;
    }
    out.push((((n & 0x3f) as u8) << 2) | 0b11);
    n >>= 6;
    for i in 0..7 {
        out.push((n >> (i * 8)) as u8);
    }
}

#[test]
fn fast_numeric_vs_serde() {
    macro_rules! check {
        ($t:ty, $val:expr) => {
            let v: Vec<$t> = $val;
            let fast = beve::to_vec_typed_slice(&v);
            let via_serde = beve::to_vec(&v).unwrap();
            assert_eq!(
                fast,
                via_serde,
                "mismatch for {}",
                std::any::type_name::<$t>()
            );
        };
    }
    check!(u8, vec![1, 2, 3, 4, 5]);
    check!(u16, vec![1, 512, 1024]);
    check!(u32, vec![1, 2, 3, 4]);
    check!(u64, vec![9, 10, 11]);
    check!(i8, vec![-1, 0, 1]);
    check!(i16, vec![-1, 0, 1, 1024]);
    check!(i32, vec![-1, 0, 1, 1_000_000]);
    check!(i64, vec![-1, 0, 1]);
    check!(f32, vec![1.0, -2.5, 3.25]);
    check!(f64, vec![1.0, -2.5, 3.25]);
}

#[test]
fn fast_bool_vs_serde() {
    let v = vec![
        true, false, true, true, false, true, false, true, false, true,
    ];
    let fast = beve::to_vec_bool_slice(&v);
    let via_serde = beve::to_vec(&v).unwrap();
    assert_eq!(fast, via_serde);

    // Ensure deserialization from fast-path bytes matches original
    let back: Vec<bool> = beve::from_slice(&fast).unwrap();
    assert_eq!(v, back);
}

#[test]
fn bool_packing_uses_lsb_order() {
    let bytes = beve::to_vec_bool_slice(&[true, false, true]);
    assert_eq!(bytes, vec![0x1c, 0x0c, 0x05]);
}

#[test]
fn fast_string_vs_serde() {
    let v = vec!["a".to_string(), "bb".to_string(), "ccc".to_string()];
    let fast = beve::to_vec_string_slice(&v);
    let via_serde = beve::to_vec(&v).unwrap();
    assert_eq!(fast, via_serde);

    let v2: Vec<&str> = vec!["x", "yy", "zzz"];
    let fast2 = beve::to_vec_str_slice(&v2);
    let via_serde2 = beve::to_vec(&v2).unwrap();
    assert_eq!(fast2, via_serde2);
}

#[test]
fn fast_bool_in_struct_vs_serde() {
    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct S {
        flags: Vec<bool>,
    }

    let v = vec![true, false, true, true, false, false, true, false, true];

    // Build expected struct bytes manually using fast-path for the field value
    let mut expected = Vec::new();
    expected.push(0x03); // string-keyed object header
    write_size_for_test(1, &mut expected); // one field
    let key = "flags";
    write_size_for_test(key.len() as u64, &mut expected);
    expected.extend_from_slice(key.as_bytes());
    expected.extend_from_slice(&beve::to_vec_bool_slice(&v));

    // Compare to serde-produced bytes
    let s = S { flags: v.clone() };
    let via_serde = beve::to_vec(&s).unwrap();
    assert_eq!(expected, via_serde);

    // And ensure from_slice can read the same payload back
    let back: S = beve::from_slice(&expected).unwrap();
    assert_eq!(back, s);
}

#[test]
fn fast_numeric_in_struct_vs_serde() {
    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct S<T> {
        data: Vec<T>,
    }

    macro_rules! check {
        ($t:ty, $val:expr) => {
            let v: Vec<$t> = $val;
            // Build expected object with typed array as the field value
            let mut expected = Vec::new();
            expected.push(0x03); // string-keyed object header
            write_size_for_test(1, &mut expected); // one field
            let key = "data";
            write_size_for_test(key.len() as u64, &mut expected);
            expected.extend_from_slice(key.as_bytes());
            expected.extend_from_slice(&beve::to_vec_typed_slice(&v));

            let s = S { data: v.clone() };
            let via_serde = beve::to_vec(&s).unwrap();
            assert_eq!(
                expected,
                via_serde,
                "mismatch for {}",
                std::any::type_name::<$t>()
            );

            // Deserialization roundtrip
            let back: S<$t> = beve::from_slice(&expected).unwrap();
            assert_eq!(back, s);
        };
    }

    check!(u8, vec![1, 2, 3, 4, 5]);
    check!(u16, vec![1, 512, 1024]);
    check!(u32, vec![1, 2, 3, 4]);
    check!(u64, vec![9, 10, 11]);
    check!(i8, vec![-1, 0, 1]);
    check!(i16, vec![-1, 0, 1, 1024]);
    check!(i32, vec![-1, 0, 1, 1_000_000]);
    check!(i64, vec![-1, 0, 1]);
    check!(f32, vec![1.0, -2.5, 3.25]);
    check!(f64, vec![1.0, -2.5, 3.25]);
}

#[test]
fn read_complex_slice_roundtrips_writer() {
    macro_rules! check {
        ($t:ty, $val:expr) => {
            let v: Vec<Complex<$t>> = $val;
            let bytes = beve::to_vec_complex_slice(&v);

            // Bulk reader round-trips the bulk writer.
            let bulk = beve::read_complex_slice::<$t>(&bytes).unwrap();
            assert_eq!(
                bulk,
                v,
                "bulk read mismatch for {}",
                std::any::type_name::<$t>()
            );

            // ...and agrees with the generic serde decode of the same bytes.
            let via_serde: Vec<Complex<$t>> = beve::from_slice(&bytes).unwrap();
            assert_eq!(
                bulk,
                via_serde,
                "bulk vs serde mismatch for {}",
                std::any::type_name::<$t>()
            );
        };
    }

    check!(
        f32,
        vec![
            Complex { re: 1.0, im: -2.0 },
            Complex { re: 3.5, im: 4.25 },
            Complex { re: -0.0, im: 1e9 },
        ]
    );
    check!(
        f64,
        vec![Complex { re: 1.0, im: -2.0 }, Complex { re: 3.5, im: 4.25 },]
    );
    check!(
        i32,
        vec![
            Complex { re: -1, im: 0 },
            Complex {
                re: 1,
                im: 1_000_000
            },
        ]
    );
    check!(
        u16,
        vec![Complex { re: 0, im: 65535 }, Complex { re: 7, im: 9 }]
    );
    // Widest width / only byte_code above 3 (16 bytes), where a `2 * ELEM_SIZE`
    // stride miscalculation would surface first.
    check!(
        u128,
        vec![Complex {
            re: 0u128,
            im: u128::MAX
        }]
    );
    check!(
        i128,
        vec![Complex {
            re: i128::MIN,
            im: i128::MAX
        }]
    );
    // Empty array: header only, no payload.
    check!(f64, vec![]);
    // Note: the half-float complex types (`Complex<f16>` / `Complex<bf16>`) are
    // intentionally omitted here. The bulk path (`to_vec_complex_slice` /
    // `read_complex_slice`) handles them, but `Complex<half>` does not implement
    // serde `Serialize`/`Deserialize`, so this macro's `from_slice` cross-check
    // cannot cover them. See `read_typed_slice_roundtrips_writer` for full
    // half-float coverage on the (serde-supported) non-complex path.
}

#[test]
fn read_complex_slice_rejects_mismatched_and_truncated() {
    let v = vec![
        Complex {
            re: 1.0f64,
            im: 2.0,
        },
        Complex { re: 3.0, im: 4.0 },
    ];
    let bytes = beve::to_vec_complex_slice(&v);

    // Wrong element width (decoding an f64 array as f32) is a type mismatch, not
    // a silent reinterpretation.
    assert!(beve::read_complex_slice::<f32>(&bytes).is_err());

    // A truncated payload is an EOF, not an out-of-bounds read.
    assert!(beve::read_complex_slice::<f64>(&bytes[..bytes.len() - 1]).is_err());

    // A non-complex value (a plain typed numeric array) is rejected.
    let typed = beve::to_vec_typed_slice(&[1.0f64, 2.0, 3.0]);
    assert!(beve::read_complex_slice::<f64>(&typed).is_err());

    // Same width, different class: an i64 complex array decoded as u64 trips the
    // class half of the type check independently of byte width (both byte_code 3).
    let signed = beve::to_vec_complex_slice(&[Complex { re: -1i64, im: 2 }]);
    assert!(beve::read_complex_slice::<u64>(&signed).is_err());

    // A scalar (non-array) complex is rejected: serde encodes a bare `Complex`
    // as a complex extension with the array flag clear.
    let scalar = beve::to_vec(&Complex {
        re: 1.0f64,
        im: 2.0,
    })
    .unwrap();
    assert!(beve::read_complex_slice::<f64>(&scalar).is_err());

    // Empty input: there is not even a header byte to read.
    assert!(beve::read_complex_slice::<f64>(&[]).is_err());
}

#[test]
fn read_typed_slice_roundtrips_writer() {
    macro_rules! check {
        ($t:ty, $val:expr) => {
            let v: Vec<$t> = $val;
            let bytes = beve::to_vec_typed_slice(&v);

            // Bulk reader round-trips the bulk writer.
            let bulk = beve::read_typed_slice::<$t>(&bytes).unwrap();
            assert_eq!(
                bulk,
                v,
                "bulk read mismatch for {}",
                std::any::type_name::<$t>()
            );

            // ...and agrees with the generic serde decode of the same bytes.
            let via_serde: Vec<$t> = beve::from_slice(&bytes).unwrap();
            assert_eq!(
                bulk,
                via_serde,
                "bulk vs serde mismatch for {}",
                std::any::type_name::<$t>()
            );
        };
    }

    check!(u8, vec![0, 1, 2, 255]);
    check!(u16, vec![0, 1, 1024, 65535]);
    check!(u32, vec![0, 1, 1_000_000]);
    check!(u64, vec![0, 1, u64::MAX]);
    check!(i8, vec![-128, -1, 0, 1, 127]);
    check!(i16, vec![-1, 0, 1, 1024]);
    check!(i32, vec![-1, 0, 1, 1_000_000]);
    check!(i64, vec![i64::MIN, -1, 0, 1, i64::MAX]);
    check!(f32, vec![1.0, -2.5, 3.25, -0.0]);
    check!(f64, vec![1.0, -2.5, 3.25, 1e9]);
    // The widest width (16 bytes) and the only `byte_code` above 3, where a
    // payload-stride miscalculation would surface first.
    check!(u128, vec![0, 1, u128::MAX]);
    check!(i128, vec![i128::MIN, -1, 0, 1, i128::MAX]);
    // The two 2-byte floats: same width and class, distinguished *only* by
    // `byte_code` (bf16 = 0, f16 = 1), so a round-trip locks that the reader keys
    // the right one. bf16's code-0 is the library's special case.
    check!(
        bf16,
        vec![
            bf16::from_f32(1.0),
            bf16::from_f32(-2.5),
            bf16::from_f32(3.25)
        ]
    );
    check!(
        f16,
        vec![f16::from_f32(1.0), f16::from_f32(-2.5), f16::from_f32(3.25)]
    );
    // Empty array: header only, no payload.
    check!(f64, vec![]);
}

#[test]
fn read_typed_slice_rejects_mismatched_and_truncated() {
    let v = vec![1.0f64, 2.0, 3.0];
    let bytes = beve::to_vec_typed_slice(&v);

    // Wrong element width (decoding an f64 array as f32) is a type mismatch, not a
    // silent reinterpretation.
    assert!(beve::read_typed_slice::<f32>(&bytes).is_err());

    // A truncated payload is an EOF, not an out-of-bounds read.
    assert!(beve::read_typed_slice::<f64>(&bytes[..bytes.len() - 1]).is_err());

    // Same width, different class: a u64 array decoded as i64 trips the class half
    // of the type check independently of byte width (both byte_code 3).
    let unsigned = beve::to_vec_typed_slice(&[1u64, 2, 3]);
    assert!(beve::read_typed_slice::<i64>(&unsigned).is_err());

    // Same width *and* class, different byte_code: a bf16 array (2-byte float,
    // byte_code 0) decoded as f16 (2-byte float, byte_code 1) trips the byte_code
    // half of the check, locking bf16's special-case code-0 against f16's code-1.
    let bf = beve::to_vec_typed_slice(&[bf16::from_f32(1.0), bf16::from_f32(2.0)]);
    assert!(beve::read_typed_slice::<f16>(&bf).is_err());

    // A complex array (extension type) is not a plain typed array and is rejected.
    let complex = beve::to_vec_complex_slice(&[Complex {
        re: 1.0f64,
        im: 2.0,
    }]);
    assert!(beve::read_typed_slice::<f64>(&complex).is_err());

    // A bit-packed boolean array shares the typed-array type tag but uses the
    // bool/string class, so it is rejected rather than misread as numbers.
    let bools = beve::to_vec_bool_slice(&[true, false, true]);
    assert!(beve::read_typed_slice::<u8>(&bools).is_err());

    // Empty input: there is not even a header byte to read.
    assert!(beve::read_typed_slice::<f64>(&[]).is_err());
}

#[test]
fn fast_string_in_struct_vs_serde() {
    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct S {
        labels: Vec<String>,
    }

    let v = vec!["alpha".to_string(), "beta".to_string(), "gamma".to_string()];

    let mut expected = Vec::new();
    expected.push(0x03); // string-keyed object header
    write_size_for_test(1, &mut expected); // one field
    let key = "labels";
    write_size_for_test(key.len() as u64, &mut expected);
    expected.extend_from_slice(key.as_bytes());
    expected.extend_from_slice(&beve::to_vec_string_slice(&v));

    let s = S { labels: v.clone() };
    let via_serde = beve::to_vec(&s).unwrap();
    assert_eq!(expected, via_serde);

    let back: S = beve::from_slice(&expected).unwrap();
    assert_eq!(back, s);
}