1
use serde_derive::Deserialize;
2
use serde_derive::Serialize;
3

            
4
use std::borrow::Cow;
5
use std::marker::PhantomData;
6
use std::sync::OnceLock;
7

            
8
use serde::{Deserializer, Serializer};
9

            
10
use super::*;
11
use crate::format::{Float, Integer, CURRENT_VERSION};
12
use crate::value::Value;
13

            
14
58
fn init_tracing() {
15
58
    static INITIALIZED: OnceLock<()> = OnceLock::new();
16
58

            
17
58
    INITIALIZED.get_or_init(|| {
18
1
        #[cfg(not(feature = "tracing"))]
19
1
        println!("To see additional logs, run tests with the `tracing` feature enabled");
20
1

            
21
1
        tracing_subscriber::fmt()
22
1
            .pretty()
23
1
            // Enable everything.
24
1
            .with_max_level(tracing::Level::TRACE)
25
1
            .with_span_events(tracing_subscriber::fmt::format::FmtSpan::ENTER)
26
1
            // Set this to be the default, global collector for this application.
27
1
            .init();
28
58
    });
29
58
}
30

            
31
58
fn test_serialization<S: Serialize + for<'de> Deserialize<'de> + PartialEq + Debug>(
32
58
    value: &S,
33
58
    check_length: Option<usize>,
34
58
) {
35
116
    test_serialization_with(value, check_length, |value, deserialized| {
36
116
        assert_eq!(value, deserialized);
37
116
    });
38
58
}
39

            
40
58
fn test_serialization_with<
41
58
    S: Serialize + for<'de> Deserialize<'de> + PartialEq + Debug,
42
58
    F: FnMut(&S, &S),
43
58
>(
44
58
    value: &S,
45
58
    check_length: Option<usize>,
46
58
    mut callback: F,
47
58
) {
48
58
    init_tracing();
49
58
    let bytes = to_vec(&value).unwrap();
50
58
    println!("{value:?}: {bytes:02x?}");
51
58
    let deserialized = from_slice::<S>(&bytes).unwrap();
52
58
    callback(value, &deserialized);
53
58
    if let Some(check_length) = check_length {
54
        // Subtract 4 bytes from the serialized output to account for the header.
55
42
        assert_eq!(bytes.len() - 4, check_length);
56
16
    }
57

            
58
    // Do the same, but using the reader interface.
59
58
    let mut bytes = Vec::new();
60
58
    to_writer(value, &mut bytes).unwrap();
61
58
    println!("{value:?}: {bytes:02x?}");
62
58
    let deserialized = from_reader(&bytes[..]).unwrap();
63
58
    callback(value, &deserialized);
64
58
}
65

            
66
use std::fmt::Debug;
67

            
68
210
#[derive(Serialize, PartialEq, Deserialize, Debug, Default)]
69
struct NumbersStruct {
70
    u8: u8,
71
    u16: u16,
72
    char: char,
73
    u32: u32,
74
    u64: u64,
75
    u128: u128,
76
    i8: i8,
77
    i16: i16,
78
    i32: i32,
79
    i64: i64,
80
    i128: i128,
81
    f32: f32,
82
    f64: f64,
83
}
84

            
85
48
#[derive(Serialize, PartialEq, Deserialize, Debug)]
86
enum EnumVariants {
87
    Unit,
88
    Tuple(u64),
89
    TupleTwoArgs(u64, u64),
90
    Struct { arg: u64 },
91
}
92

            
93
#[test]
94
1
fn numbers() {
95
1
    test_serialization(&NumbersStruct::default(), None);
96
1
    test_serialization(
97
1
        &NumbersStruct {
98
1
            u8: u8::MAX,
99
1
            u16: u16::MAX,
100
1
            char: char::MAX,
101
1
            u32: u32::MAX,
102
1
            u64: u64::MAX,
103
1
            u128: u128::MAX,
104
1
            i8: i8::MIN,
105
1
            i16: i16::MIN,
106
1
            i32: i32::MIN,
107
1
            i64: i64::MIN,
108
1
            i128: i128::MIN,
109
1
            f32: 1.,
110
1
            f64: 1.,
111
1
        },
112
1
        None,
113
1
    );
114
1
}
115

            
116
#[test]
117
1
fn number_packing() {
118
1
    test_serialization(&0_u128, Some(2));
119
1
    test_serialization(&(2_u128.pow(8) - 1), Some(2));
120
1
    test_serialization(&2_u128.pow(8), Some(3));
121
1
    test_serialization(&(2_u128.pow(16) - 1), Some(3));
122
1
    test_serialization(&2_u128.pow(16), Some(4));
123
1
    test_serialization(&(2_u128.pow(24) - 1), Some(4));
124
1
    test_serialization(&2_u128.pow(24), Some(5));
125
1
    test_serialization(&(2_u128.pow(32) - 1), Some(5));
126
1
    test_serialization(&2_u128.pow(32), Some(7));
127
1
    test_serialization(&(2_u128.pow(48) - 1), Some(7));
128
1
    test_serialization(&2_u128.pow(48), Some(9));
129
1
    test_serialization(&(2_u128.pow(64) - 1), Some(9));
130
1
    test_serialization(&2_u128.pow(64), Some(17));
131
1

            
132
1
    test_serialization(&0_i128, Some(2));
133
1
    test_serialization(&(2_i128.pow(7) - 1), Some(2));
134
1
    test_serialization(&2_i128.pow(7), Some(3));
135
1
    test_serialization(&(2_i128.pow(15) - 1), Some(3));
136
1
    test_serialization(&2_i128.pow(15), Some(4));
137
1
    test_serialization(&(2_i128.pow(23) - 1), Some(4));
138
1
    test_serialization(&2_i128.pow(23), Some(5));
139
1
    test_serialization(&(2_i128.pow(31) - 1), Some(5));
140
1
    test_serialization(&2_i128.pow(31), Some(7));
141
1
    test_serialization(&(2_i128.pow(47) - 1), Some(7));
142
1
    test_serialization(&2_i128.pow(47), Some(9));
143
1
    test_serialization(&-(2_i128.pow(7)), Some(2));
144
1
    test_serialization(&-(2_i128.pow(7) + 1), Some(3));
145
1
    test_serialization(&-(2_i128.pow(15)), Some(3));
146
1
    test_serialization(&-(2_i128.pow(15) + 1), Some(4));
147
1
    test_serialization(&-(2_i128.pow(23)), Some(4));
148
1
    test_serialization(&-(2_i128.pow(23) + 1), Some(5));
149
1
    test_serialization(&-(2_i128.pow(31)), Some(5));
150
1
    test_serialization(&-(2_i128.pow(31) + 1), Some(7));
151
1
    test_serialization(&-(2_i128.pow(47)), Some(7));
152
1
    test_serialization(&-(2_i128.pow(47) + 1), Some(9));
153
1
    test_serialization(&-(2_i128.pow(63)), Some(9));
154
1
    test_serialization(&-(2_i128.pow(63) + 1), Some(17));
155
1

            
156
1
    // Float packing relies on bitwise conversions and is lossless.
157
1
    test_serialization(&f64::INFINITY, Some(3));
158
1
    test_serialization(&f64::NEG_INFINITY, Some(3));
159
1
    test_serialization(&0_f64, Some(3));
160
1
    test_serialization(&-0_f64, Some(3));
161
1
    test_serialization(&0.1_f64, Some(9));
162
1
    test_serialization(&0.1_f32, Some(5));
163
1
}
164

            
165
#[test]
166
1
fn tuples() {
167
1
    test_serialization(&(1, true, 3), None);
168
1
}
169

            
170
#[test]
171
1
fn enums() {
172
1
    test_serialization(&EnumVariants::Unit, None);
173
1

            
174
1
    test_serialization(&EnumVariants::Tuple(0), None);
175
1

            
176
1
    test_serialization(&EnumVariants::TupleTwoArgs(1, 2), None);
177
1

            
178
1
    test_serialization(&EnumVariants::Struct { arg: 3 }, None);
179
1

            
180
1
    test_serialization(&Some(EnumVariants::Unit), None);
181
1
}
182

            
183
#[test]
184
1
fn vectors() {
185
1
    test_serialization(&vec![0_u64, 1], None);
186
1
    test_serialization(
187
1
        &vec![NumbersStruct::default(), NumbersStruct::default()],
188
1
        None,
189
1
    );
190
1
}
191

            
192
#[test]
193
1
fn option() {
194
1
    test_serialization(&Option::<u64>::None, None);
195
1
    test_serialization(&Some(0_u64), None);
196
1
    test_serialization(&Some(u64::MAX), None);
197
1
}
198

            
199
#[test]
200
1
fn phantom() {
201
1
    test_serialization(&PhantomData::<u64>, None);
202
1
}
203

            
204
30
#[derive(Serialize, PartialEq, Deserialize, Debug, Default)]
205
struct StringsAndBytes<'a> {
206
    bytes: Cow<'a, [u8]>,
207
    #[serde(with = "serde_bytes")]
208
    bytes_borrowed: Cow<'a, [u8]>,
209
    #[serde(with = "serde_bytes")]
210
    serde_bytes_byte_slice: &'a [u8],
211
    #[serde(with = "serde_bytes")]
212
    serde_bytes_byte_vec: Vec<u8>,
213
    str_ref: &'a str,
214
    string: String,
215
}
216

            
217
#[test]
218
1
fn borrowing_data() {
219
1
    let original = StringsAndBytes {
220
1
        bytes: Cow::Borrowed(b"hello"),
221
1
        bytes_borrowed: Cow::Borrowed(b"hello"),
222
1
        serde_bytes_byte_slice: b"hello",
223
1
        serde_bytes_byte_vec: b"world".to_vec(),
224
1
        str_ref: "hello",
225
1
        string: String::from("world"),
226
1
    };
227
1
    let serialized = to_vec(&original).unwrap();
228
1
    let deserialized = from_slice(&serialized).unwrap();
229
1
    assert_eq!(original, deserialized);
230
1
    assert!(matches!(deserialized.bytes_borrowed, Cow::Borrowed(_)));
231
1
}
232

            
233
#[test]
234
1
fn limiting_input() {
235
1
    let original = StringsAndBytes {
236
1
        bytes: Cow::Borrowed(b"hello"),
237
1
        bytes_borrowed: Cow::Borrowed(b"hello"),
238
1
        serde_bytes_byte_slice: b"hello",
239
1
        serde_bytes_byte_vec: b"world".to_vec(),
240
1
        str_ref: "hello",
241
1
        string: String::from("world"),
242
1
    };
243
1
    let serialized = to_vec(&original).unwrap();
244
1
    // There are 6 values that contain 5 bytes each. A limit of 30 should be perfect.
245
1
    assert!(Config::default()
246
1
        .allocation_budget(30)
247
1
        .deserialize::<StringsAndBytes<'_>>(&serialized)
248
1
        .is_ok());
249
1
    assert!(Config::default()
250
1
        .allocation_budget(29)
251
1
        .deserialize::<StringsAndBytes<'_>>(&serialized)
252
1
        .is_err());
253

            
254
    // Test number limits.
255
1
    let serialized = to_vec(&NumbersStruct {
256
1
        u8: u8::MAX,
257
1
        u16: u16::MAX,
258
1
        char: char::MAX,
259
1
        u32: u32::MAX,
260
1
        u64: u64::MAX,
261
1
        u128: u128::MAX,
262
1
        i8: i8::MIN,
263
1
        i16: i16::MIN,
264
1
        i32: i32::MIN,
265
1
        i64: i64::MIN,
266
1
        i128: i128::MIN,
267
1
        f32: f32::MAX,
268
1
        f64: f64::MIN,
269
1
    })
270
1
    .unwrap();
271
1
    assert!(Config::default()
272
1
        .allocation_budget(78)
273
1
        .deserialize::<NumbersStruct>(&serialized)
274
1
        .is_ok());
275
1
    assert!(Config::default()
276
1
        .allocation_budget(77)
277
1
        .deserialize::<NumbersStruct>(&serialized)
278
1
        .is_err());
279
1
}
280

            
281
2
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
282
struct TupleStruct(u32, u8);
283

            
284
#[test]
285
1
fn tuple_struct() {
286
1
    test_serialization(&TupleStruct(1, 2), None);
287
1
}
288

            
289
#[test]
290
1
fn value() {
291
1
    macro_rules! roundtrip {
292
1
        ($value:expr) => {{
293
1
            assert_eq!(
294
1
                from_slice::<Value<'_>>(&to_vec(&$value).unwrap()).unwrap(),
295
1
                $value
296
1
            );
297
1
        }};
298
1
    }
299
1

            
300
1
    roundtrip!(Value::None);
301
1
    roundtrip!(Value::Unit);
302
1
    roundtrip!(Value::Bool(true));
303
1
    roundtrip!(Value::Bool(false));
304
1
    roundtrip!(Value::Integer(Integer::from(i8::MAX)));
305
1
    roundtrip!(Value::Integer(Integer::from(i16::MAX)));
306
1
    roundtrip!(Value::Integer(Integer::from(i32::MAX)));
307
1
    roundtrip!(Value::Integer(Integer::from(i64::MAX)));
308
1
    roundtrip!(Value::Integer(Integer::from(i128::MAX)));
309
1
    roundtrip!(Value::Integer(Integer::from(u8::MAX)));
310
1
    roundtrip!(Value::Integer(Integer::from(u16::MAX)));
311
1
    roundtrip!(Value::Integer(Integer::from(u32::MAX)));
312
1
    roundtrip!(Value::Integer(Integer::from(u64::MAX)));
313
1
    roundtrip!(Value::Integer(Integer::from(u128::MAX)));
314
1
    roundtrip!(Value::Float(Float::from(std::f64::consts::PI)));
315
1
    roundtrip!(Value::Float(Float::from(std::f32::consts::PI)));
316
1
    roundtrip!(Value::Sequence(vec![Value::None]));
317
1
    roundtrip!(Value::Mappings(vec![(Value::None, Value::Unit)]));
318

            
319
1
    let original_value = Value::Bytes(Cow::Borrowed(b"hello"));
320
1
    let encoded_bytes = to_vec(&original_value).unwrap();
321
1
    let borrowed_decoded: Value<'_> = from_slice(&encoded_bytes).unwrap();
322
1
    assert_eq!(Value::String(Cow::Borrowed("hello")), borrowed_decoded);
323
1
    assert!(matches!(borrowed_decoded, Value::String(Cow::Borrowed(_))));
324

            
325
1
    let original_value = Value::Bytes(Cow::Borrowed(b"\xFE\xED\xD0\xD0"));
326
1
    let encoded_bytes = to_vec(&original_value).unwrap();
327
1
    let borrowed_decoded: Value<'_> = from_slice(&encoded_bytes).unwrap();
328
1
    assert_eq!(
329
1
        Value::Bytes(Cow::Borrowed(b"\xFE\xED\xD0\xD0")),
330
1
        borrowed_decoded
331
1
    );
332
1
    assert!(matches!(borrowed_decoded, Value::Bytes(Cow::Borrowed(_))));
333
1
}
334

            
335
#[test]
336
1
fn incompatible_version() {
337
1
    let mut incompatible_header = Vec::new();
338
1
    format::write_header(&mut incompatible_header, CURRENT_VERSION + 1).unwrap();
339
1
    assert!(matches!(
340
1
        from_slice::<()>(&incompatible_header),
341
        Err(Error::IncompatibleVersion)
342
    ));
343
1
}
344

            
345
#[test]
346
1
fn invalid_char_cast() {
347
1
    let bytes = to_vec(&0x11_0000_u32).unwrap();
348
1

            
349
1
    assert!(matches!(
350
1
        from_slice::<char>(&bytes),
351
        Err(Error::InvalidUtf8(_))
352
    ));
353
1
}
354

            
355
#[test]
356
1
fn bytes_to_identifier() {
357
1
    let mut valid_bytes = Vec::new();
358
1
    format::write_header(&mut valid_bytes, CURRENT_VERSION).unwrap();
359
1
    format::write_named(&mut valid_bytes).unwrap();
360
1
    format::write_bytes(&mut valid_bytes, b"Unit").unwrap();
361
1

            
362
1
    assert_eq!(
363
1
        from_slice::<EnumVariants>(&valid_bytes).unwrap(),
364
1
        EnumVariants::Unit
365
1
    );
366

            
367
1
    let mut invalid_bytes = Vec::new();
368
1
    format::write_header(&mut invalid_bytes, CURRENT_VERSION).unwrap();
369
1
    format::write_named(&mut invalid_bytes).unwrap();
370
1
    format::write_bytes(&mut invalid_bytes, &0xFFFF_FFFF_u32.to_be_bytes()).unwrap();
371
1

            
372
1
    assert!(matches!(
373
1
        from_slice::<EnumVariants>(&invalid_bytes),
374
        Err(Error::InvalidUtf8(_))
375
    ));
376
1
}
377

            
378
#[test]
379
1
fn invalid_symbol() {
380
1
    let mut valid_bytes = Vec::new();
381
1
    format::write_header(&mut valid_bytes, CURRENT_VERSION).unwrap();
382
1
    format::write_atom_header(&mut valid_bytes, format::Kind::Symbol, 4).unwrap();
383
1
    format::write_bytes(&mut valid_bytes, &0xFFFF_FFFF_u32.to_be_bytes()).unwrap();
384
1

            
385
1
    assert!(matches!(
386
1
        from_slice::<Value<'_>>(&valid_bytes),
387
        Err(Error::InvalidUtf8(_))
388
    ));
389
1
}
390

            
391
#[test]
392
1
fn unknown_special() {
393
1
    let mut invalid_bytes = Vec::new();
394
1
    format::write_header(&mut invalid_bytes, CURRENT_VERSION).unwrap();
395
1
    format::write_atom_header(
396
1
        &mut invalid_bytes,
397
1
        format::Kind::Special,
398
1
        format::SPECIAL_COUNT,
399
1
    )
400
1
    .unwrap();
401
1

            
402
1
    assert!(from_slice::<()>(&invalid_bytes).is_err());
403
1
}
404

            
405
/// In `BonsaiDb`, sometimes it's nice to use a `()` as an associated type
406
/// as a default. To allow changing data that was previously serialized as a
407
/// `()` but now has a new type, Pot allows converting between unit types
408
/// and defaults of all major serialized types. The net effect is if you
409
/// start with a derived `BonsaiDb` view with no `value =` argument, `()` is
410
/// used instead. With this flexibility, changing the value type to another
411
/// type will sometimes be able to work without requiring rebuilding the
412
/// views on deployment.
413
#[test]
414
#[allow(clippy::cognitive_complexity)]
415
1
fn unit_adaptations() {
416
1
    #[derive(Deserialize)]
417
1
    struct Test {
418
1
        #[serde(default)]
419
1
        value: u32,
420
1
    }
421
1

            
422
1
    let unit = to_vec(&()).unwrap();
423
1
    assert!(from_slice::<Option<()>>(&unit).unwrap().is_some());
424
1
    assert_eq!(from_slice::<Test>(&unit).unwrap().value, 0);
425
1
    assert_eq!(from_slice::<&[u8]>(&unit).unwrap(), b"");
426
1
    assert_eq!(from_slice::<serde_bytes::ByteBuf>(&unit).unwrap(), b"");
427
1
    assert_eq!(from_slice::<&str>(&unit).unwrap(), "");
428
1
    assert_eq!(from_slice::<u8>(&unit).unwrap(), 0);
429
1
    assert_eq!(from_slice::<u16>(&unit).unwrap(), 0);
430
1
    assert_eq!(from_slice::<u32>(&unit).unwrap(), 0);
431
1
    assert_eq!(from_slice::<u64>(&unit).unwrap(), 0);
432
1
    assert_eq!(from_slice::<u128>(&unit).unwrap(), 0);
433
1
    assert_eq!(from_slice::<i8>(&unit).unwrap(), 0);
434
1
    assert_eq!(from_slice::<i16>(&unit).unwrap(), 0);
435
1
    assert_eq!(from_slice::<i32>(&unit).unwrap(), 0);
436
1
    assert_eq!(from_slice::<i64>(&unit).unwrap(), 0);
437
1
    assert_eq!(from_slice::<i128>(&unit).unwrap(), 0);
438
1
    assert!(!from_slice::<bool>(&unit).unwrap());
439

            
440
1
    let none = to_vec(&Option::<()>::None).unwrap();
441
1
    assert!(from_slice::<Option<()>>(&none).unwrap().is_none());
442
1
    assert!(from_slice::<Option<Test>>(&none).unwrap().is_none());
443
1
    assert_eq!(from_slice::<&[u8]>(&none).unwrap(), b"");
444
1
    assert_eq!(from_slice::<serde_bytes::ByteBuf>(&none).unwrap(), b"");
445
1
    assert_eq!(from_slice::<&str>(&none).unwrap(), "");
446
1
    assert_eq!(from_slice::<u8>(&none).unwrap(), 0);
447
1
    assert_eq!(from_slice::<u16>(&none).unwrap(), 0);
448
1
    assert_eq!(from_slice::<u32>(&none).unwrap(), 0);
449
1
    assert_eq!(from_slice::<u64>(&none).unwrap(), 0);
450
1
    assert_eq!(from_slice::<u128>(&none).unwrap(), 0);
451
1
    assert_eq!(from_slice::<i8>(&none).unwrap(), 0);
452
1
    assert_eq!(from_slice::<i16>(&none).unwrap(), 0);
453
1
    assert_eq!(from_slice::<i32>(&none).unwrap(), 0);
454
1
    assert_eq!(from_slice::<i64>(&none).unwrap(), 0);
455
1
    assert_eq!(from_slice::<i128>(&none).unwrap(), 0);
456
1
    assert!(!from_slice::<bool>(&none).unwrap());
457
1
}
458

            
459
#[test]
460
1
fn invalid_numbers() {
461
1
    let mut invalid_float_byte_len = Vec::new();
462
1
    format::write_header(&mut invalid_float_byte_len, CURRENT_VERSION).unwrap();
463
1
    format::write_atom_header(&mut invalid_float_byte_len, format::Kind::Float, 0).unwrap();
464
1

            
465
1
    assert!(from_slice::<f32>(&invalid_float_byte_len).is_err());
466

            
467
1
    assert!(
468
1
        format::Float::read_from(format::Kind::Symbol, 0, &mut &invalid_float_byte_len[..])
469
1
            .is_err(),
470
1
    );
471

            
472
1
    let mut invalid_signed_byte_len = Vec::new();
473
1
    format::write_header(&mut invalid_signed_byte_len, CURRENT_VERSION).unwrap();
474
1
    format::write_atom_header(&mut invalid_signed_byte_len, format::Kind::Int, 10).unwrap();
475
1

            
476
1
    assert!(from_slice::<i32>(&invalid_signed_byte_len).is_err());
477

            
478
1
    assert!(
479
1
        format::Integer::read_from(format::Kind::Symbol, 0, &mut &invalid_signed_byte_len[..])
480
1
            .is_err(),
481
1
    );
482

            
483
1
    let mut invalid_unsigned_byte_len = Vec::new();
484
1
    format::write_header(&mut invalid_unsigned_byte_len, CURRENT_VERSION).unwrap();
485
1
    format::write_atom_header(&mut invalid_unsigned_byte_len, format::Kind::UInt, 10).unwrap();
486
1

            
487
1
    assert!(from_slice::<u32>(&invalid_unsigned_byte_len).is_err());
488
1
}
489

            
490
#[test]
491
#[allow(clippy::unnecessary_mut_passed)] // It's necessary.
492
1
fn not_human_readable() {
493
1
    let mut bytes = Vec::new();
494
1
    let mut serializer = ser::Serializer::new(&mut bytes).unwrap();
495
1
    assert!(!(&mut serializer).is_human_readable());
496
1
    ().serialize(&mut serializer).unwrap();
497
1

            
498
1
    let bytes = to_vec(&()).unwrap();
499
1
    let mut deserializer = de::Deserializer::from_slice(&bytes, usize::MAX).unwrap();
500
1
    assert!(!(&mut deserializer).is_human_readable());
501
1
}
502

            
503
#[test]
504
1
fn unexpected_eof() {
505
1
    let mut invalid_bytes = Vec::new();
506
1
    format::write_header(&mut invalid_bytes, CURRENT_VERSION).unwrap();
507
1
    format::write_atom_header(&mut invalid_bytes, format::Kind::Bytes, 10).unwrap();
508
1
    assert!(matches!(
509
1
        from_slice::<Vec<u8>>(&invalid_bytes),
510
        Err(Error::Eof)
511
    ));
512
1
}
513

            
514
#[test]
515
1
fn too_big_read() {
516
1
    let mut invalid_bytes = Vec::new();
517
1
    format::write_header(&mut invalid_bytes, CURRENT_VERSION).unwrap();
518
1
    format::write_atom_header(&mut invalid_bytes, format::Kind::Bytes, 10).unwrap();
519
1
    assert!(matches!(
520
1
        Config::default()
521
1
            .allocation_budget(9)
522
1
            .deserialize::<Vec<u8>>(&invalid_bytes),
523
        Err(Error::TooManyBytesRead)
524
    ));
525
1
}
526

            
527
2
#[derive(Serialize, Deserialize, Debug, PartialEq)]
528
struct Flatten {
529
    #[serde(flatten)]
530
    structure: Flattened,
531
    #[serde(flatten)]
532
    enumeration: EnumVariants,
533
}
534

            
535
4
#[derive(Serialize, Deserialize, Debug, PartialEq)]
536
struct Flattened {
537
    field: String,
538
}
539

            
540
#[test]
541
1
fn test_flatten() {
542
1
    test_serialization(
543
1
        &Flatten {
544
1
            structure: Flattened {
545
1
                field: String::from("flat"),
546
1
            },
547
1
            enumeration: EnumVariants::Struct { arg: 1 },
548
1
        },
549
1
        None,
550
1
    );
551
1
}
552

            
553
#[test]
554
1
fn direct_value_serialization() {
555
8
    fn roundtrip<T: Serialize + for<'de> Deserialize<'de> + PartialEq + Debug>(value: &T) {
556
8
        let as_value = Value::from_serialize(value).unwrap();
557
8
        let deserialized = as_value.deserialize_as::<T>().unwrap();
558
8
        assert_eq!(&deserialized, value);
559
8
    }
560
1

            
561
1
    roundtrip(&NumbersStruct {
562
1
        u8: u8::MAX,
563
1
        u16: u16::MAX,
564
1
        char: char::MAX,
565
1
        u32: u32::MAX,
566
1
        u64: u64::MAX,
567
1
        u128: u128::MAX,
568
1
        i8: i8::MIN,
569
1
        i16: i16::MIN,
570
1
        i32: i32::MIN,
571
1
        i64: i64::MIN,
572
1
        i128: i128::MIN,
573
1
        f32: f32::MAX,
574
1
        f64: f64::MIN,
575
1
    });
576
1

            
577
1
    roundtrip(&EnumVariants::Struct { arg: 1 });
578
1
    roundtrip(&EnumVariants::Tuple(1));
579
1
    roundtrip(&EnumVariants::TupleTwoArgs(1, 2));
580
1
    roundtrip(&EnumVariants::Unit);
581
1
    roundtrip(&Some(1_u32));
582
1
    roundtrip(&"hello".to_string());
583
1
    roundtrip(&b"hello".to_vec());
584
1
}
585

            
586
#[test]
587
1
fn borrowed_value_serialization() {
588
1
    #[track_caller]
589
2
    fn check<T, U>(value: &T)
590
2
    where
591
2
        T: Serialize + Debug,
592
2
        U: Debug + PartialEq<T> + for<'de> Deserialize<'de>,
593
2
    {
594
2
        let as_value = Value::from_serialize(value).unwrap();
595
2
        let deserialized = as_value.deserialize_as::<U>().unwrap();
596
2
        assert_eq!(&deserialized, value);
597
2
    }
598
1

            
599
1
    check::<_, Vec<u8>>(&b"hello");
600
1
    check::<_, String>(&"hello");
601
1
}
602

            
603
#[test]
604
1
fn value_error() {
605
1
    #[derive(Debug)]
606
1
    struct Fallible;
607
1

            
608
1
    impl Serialize for Fallible {
609
1
        fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
610
1
        where
611
1
            S: Serializer,
612
1
        {
613
1
            Err(serde::ser::Error::custom("oh no!"))
614
1
        }
615
1
    }
616
1

            
617
1
    assert_eq!(
618
1
        Value::from_serialize(Fallible),
619
1
        Err(ValueError::Custom(String::from("oh no!")))
620
1
    );
621
1
}
622

            
623
#[test]
624
1
fn persistent_symbols_slice() {
625
1
    let mut sender = ser::SymbolMap::default();
626
1
    let mut receiver = de::SymbolList::default();
627
1

            
628
1
    let mut bytes = sender.serialize_to_vec(&NumbersStruct::default()).unwrap();
629
1
    let _result = receiver.deserialize_slice::<NumbersStruct>(&bytes).unwrap();
630
1
    let symbol_count_after_first_send = receiver.len();
631
1
    let first_payload_len = bytes.len();
632
1

            
633
1
    // Send again, confirm the symbol list didn't grow.
634
1
    bytes.clear();
635
1
    sender
636
1
        .serialize_to(&mut bytes, &NumbersStruct::default())
637
1
        .unwrap();
638
1
    let _result = receiver.deserialize_slice::<NumbersStruct>(&bytes).unwrap();
639
1
    assert_eq!(symbol_count_after_first_send, receiver.len());
640
1
    println!(
641
1
        "First: {first_payload_len} bytes; Second: {} bytes",
642
1
        bytes.len()
643
1
    );
644
1
    assert!(first_payload_len > bytes.len());
645
1
}
646

            
647
#[test]
648
1
fn persistent_symbols_read() {
649
1
    let mut sender = ser::SymbolMap::default();
650
1
    let mut receiver = de::SymbolList::default();
651
1

            
652
1
    let mut bytes = sender.serialize_to_vec(&NumbersStruct::default()).unwrap();
653
1
    let _result = receiver
654
1
        .deserialize_from::<NumbersStruct>(&bytes[..])
655
1
        .unwrap();
656
1
    let symbol_count_after_first_send = receiver.len();
657
1
    let first_payload_len = bytes.len();
658
1

            
659
1
    // Send again, confirm the symbol list didn't grow.
660
1
    bytes.clear();
661
1
    sender
662
1
        .serialize_to(&mut bytes, &NumbersStruct::default())
663
1
        .unwrap();
664
1
    let _result = receiver
665
1
        .deserialize_from::<NumbersStruct>(&bytes[..])
666
1
        .unwrap();
667
1
    assert_eq!(symbol_count_after_first_send, receiver.len());
668
1
    println!(
669
1
        "First: {first_payload_len} bytes; Second: {} bytes",
670
1
        bytes.len()
671
1
    );
672
1
    assert!(first_payload_len > bytes.len());
673
1
}
674

            
675
#[test]
676
1
fn symbol_map_serialization() {
677
9
    #[derive(Serialize, Deserialize, Default, Eq, PartialEq, Debug)]
678
1
    struct Payload {
679
1
        a: usize,
680
1
        b: usize,
681
1
    }
682
1

            
683
1
    let mut sender = crate::ser::SymbolMap::default();
684
1
    assert!(sender.is_empty());
685
1
    let mut receiver = crate::de::SymbolMap::new();
686
1
    assert!(receiver.is_empty());
687

            
688
    // Send the first payload, populating the map.
689
1
    let mut bytes = sender.serialize_to_vec(&Payload::default()).unwrap();
690
1
    assert_eq!(sender.len(), 2);
691

            
692
1
    assert_eq!(
693
1
        receiver.deserialize_slice::<Payload>(&bytes).unwrap(),
694
1
        Payload::default()
695
1
    );
696
1
    assert_eq!(receiver.len(), 2);
697

            
698
    // Serialize the maps.
699
1
    let serialized_sender = crate::to_vec(&sender).unwrap();
700
1
    let serialized_receiver = crate::to_vec(&receiver).unwrap();
701
1
    // The serialization formats are the same despite using different
702
1
    // in-memory representations. This allows pre-serializing a dictionary
703
1
    // before starting the intial payload.
704
1
    assert_eq!(serialized_sender, serialized_receiver);
705
1
    let mut deserialized_sender =
706
1
        crate::from_slice::<crate::ser::SymbolMap>(&serialized_sender).unwrap();
707
1
    let mut deserialized_receiver =
708
1
        crate::from_slice::<crate::de::SymbolMap>(&serialized_receiver).unwrap();
709
1

            
710
1
    // Create a new payload and serialize it. Ensure the payloads produced
711
1
    // by the serialized map and the original map are identical.
712
1
    let new_payload = Payload { a: 1, b: 2 };
713
1
    bytes.clear();
714
1
    sender.serialize_to(&mut bytes, &new_payload).unwrap();
715
1
    let from_serialized_sender = deserialized_sender.serialize_to_vec(&new_payload).unwrap();
716
1
    assert_eq!(bytes, from_serialized_sender);
717

            
718
    // Deserialize the payload
719
1
    assert_eq!(
720
1
        receiver.deserialize_slice::<Payload>(&bytes).unwrap(),
721
1
        new_payload
722
1
    );
723
1
    assert_eq!(
724
1
        deserialized_receiver
725
1
            .deserialize_slice::<Payload>(&bytes)
726
1
            .unwrap(),
727
1
        new_payload
728
1
    );
729
1
}
730

            
731
#[test]
732
1
fn symbol_map_population() {
733
1
    let mut map = crate::ser::SymbolMap::default();
734
1
    map.populate_from(&NumbersStruct::default()).unwrap();
735
1
    map.populate_from(&EnumVariants::Struct { arg: 1 }).unwrap();
736
1
    map.populate_from(&EnumVariants::Tuple(0)).unwrap();
737
1
    map.populate_from(&EnumVariants::TupleTwoArgs(0, 1))
738
1
        .unwrap();
739
1
    assert_eq!(map.populate_from(&EnumVariants::Unit).unwrap(), 1);
740
1
    assert_eq!(map.populate_from(&EnumVariants::Unit).unwrap(), 0);
741
1
    dbg!(map);
742
1
}
743

            
744
#[test]
745
1
fn backwards_compatible() {
746
3
    #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
747
1
    struct Canary {
748
1
        name: String,
749
1
        id: u64,
750
1
    }
751
1

            
752
1
    let canary = Canary {
753
1
        name: String::from("coalmine"),
754
1
        id: 0xfeed_d0d0_dead_beef,
755
1
    };
756
1

            
757
1
    // This payload was generated with pot 1.0 using the same structure.
758
1
    // This structure should be updated to be more encompassing, but this at
759
1
    // least tests for basic compatibility.
760
1
    let v1_canary = [
761
1
        80, 111, 116, 0, 162, 200, 110, 97, 109, 101, 232, 99, 111, 97, 108, 109, 105, 110, 101,
762
1
        196, 105, 100, 71, 239, 190, 173, 222, 208, 208, 237, 254,
763
1
    ];
764
1
    let parsed: Canary = crate::from_slice(&v1_canary).unwrap();
765
1
    assert_eq!(canary, parsed);
766
1
}
767

            
768
#[test]
769
1
fn unit_enum_fix() {
770
1
    let test_payload = vec![EnumVariants::Unit, EnumVariants::Tuple(0)];
771
1
    let ambiguous = Config::new()
772
1
        .compatibility(Compatibility::Full)
773
1
        .serialize(&test_payload)
774
1
        .unwrap();
775
1
    let fixed = Config::new()
776
1
        .compatibility(Compatibility::V4)
777
1
        .serialize(&test_payload)
778
1
        .unwrap();
779
1
    assert_ne!(ambiguous, fixed);
780

            
781
1
    let bad_value: Value<'_> = crate::from_slice(&ambiguous).unwrap();
782
1
    let good_value: Value<'_> = crate::from_slice(&fixed).unwrap();
783
1
    match bad_value {
784
1
        Value::Sequence(sequence) => {
785
1
            assert_eq!(sequence[1], Value::None);
786
        }
787
        other => unreachable!("Unexpected value: {other:?}"),
788
    }
789
1
    match good_value {
790
1
        Value::Sequence(sequence) => {
791
1
            assert_eq!(sequence.len(), 2);
792
1
            assert_eq!(
793
1
                sequence[1],
794
1
                Value::Mappings(vec![(
795
1
                    Value::String(Cow::Borrowed("Tuple")),
796
1
                    Value::from(0_u8)
797
1
                )])
798
1
            );
799
        }
800
        other => unreachable!("Unexpected value: {other:?}"),
801
    }
802
1
}