facet-cbor 0.3.2

CBOR serialization for Facet types
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use facet::Facet;
use facet_cbor::to_vec;
use std::collections::HashMap;

// =============================================================================
// Primitive scalars
// =============================================================================

#[test]
fn test_u32() {
    // 42 → major 0, value 42 (0x18 0x2a)
    let bytes = to_vec(&42u32).unwrap();
    assert_eq!(bytes, vec![0x18, 0x2a]);
}

#[test]
fn test_u32_small() {
    // 0 → 0x00
    assert_eq!(to_vec(&0u32).unwrap(), vec![0x00]);
    // 23 → 0x17
    assert_eq!(to_vec(&23u32).unwrap(), vec![0x17]);
    // 24 → 0x18, 0x18
    assert_eq!(to_vec(&24u32).unwrap(), vec![0x18, 0x18]);
}

#[test]
fn test_u64_large() {
    // 1_000_000 = 0x000F4240 → major 0, additional 26 (4 bytes), big-endian
    let bytes = to_vec(&1_000_000u64).unwrap();
    assert_eq!(bytes, vec![0x1a, 0x00, 0x0f, 0x42, 0x40]);
}

#[test]
fn test_i64_positive() {
    // 100 → major 0, value 100 (0x18, 0x64)
    let bytes = to_vec(&100i64).unwrap();
    assert_eq!(bytes, vec![0x18, 0x64]);
}

#[test]
fn test_i64_negative() {
    // -1 → major 1, value 0 (0x20)
    assert_eq!(to_vec(&-1i64).unwrap(), vec![0x20]);
    // -10 → major 1, value 9 (0x29)
    assert_eq!(to_vec(&-10i64).unwrap(), vec![0x29]);
    // -100 → major 1, value 99 (0x38, 0x63)
    assert_eq!(to_vec(&-100i64).unwrap(), vec![0x38, 0x63]);
}

#[test]
fn test_string() {
    // "hello" → major 3, length 5, then UTF-8 bytes
    let bytes = to_vec(&String::from("hello")).unwrap();
    assert_eq!(bytes, vec![0x65, b'h', b'e', b'l', b'l', b'o']);
}

#[test]
fn test_empty_string() {
    let bytes = to_vec(&String::from("")).unwrap();
    assert_eq!(bytes, vec![0x60]); // major 3, length 0
}

#[test]
fn test_bool() {
    assert_eq!(to_vec(&true).unwrap(), vec![0xf5]);
    assert_eq!(to_vec(&false).unwrap(), vec![0xf4]);
}

#[test]
fn test_f64() {
    // 1.0 as f64 → 0xfb + 8 bytes big-endian IEEE 754
    let bytes = to_vec(&1.0f64).unwrap();
    assert_eq!(bytes.len(), 9);
    assert_eq!(bytes[0], 0xfb);
    assert_eq!(&bytes[1..], &1.0f64.to_be_bytes());
}

#[test]
fn test_f32() {
    let bytes = to_vec(&1.0f32).unwrap();
    assert_eq!(bytes.len(), 5);
    assert_eq!(bytes[0], 0xfa);
    assert_eq!(&bytes[1..], &1.0f32.to_be_bytes());
}

#[test]
fn test_unit() {
    assert_eq!(to_vec(&()).unwrap(), vec![0xf6]); // null
}

// =============================================================================
// Structs
// =============================================================================

#[derive(Facet)]
struct Point {
    x: i32,
    y: i32,
}

#[test]
fn test_struct() {
    let p = Point { x: 1, y: 2 };
    let bytes = to_vec(&p).unwrap();
    // map(2) { "x": 1, "y": 2 }
    let expected = vec![
        0xa2, // map of 2 items
        // "x"
        0x61, // text(1)
        b'x', // 1
        0x01, // "y"
        0x61, // text(1)
        b'y', // 2
        0x02,
    ];
    assert_eq!(bytes, expected);
}

#[derive(Facet)]
struct Nested {
    name: String,
    point: Point,
}

#[test]
fn test_nested_struct() {
    let n = Nested {
        name: String::from("A"),
        point: Point { x: 10, y: 20 },
    };
    let bytes = to_vec(&n).unwrap();
    // map(2) { "name": "A", "point": map(2) { "x": 10, "y": 20 } }
    let mut expected = Vec::new();
    expected.push(0xa2); // map(2)
    // "name"
    expected.extend_from_slice(&[0x64, b'n', b'a', b'm', b'e']);
    // "A"
    expected.extend_from_slice(&[0x61, b'A']);
    // "point"
    expected.extend_from_slice(&[0x65, b'p', b'o', b'i', b'n', b't']);
    // map(2) { "x": 10, "y": 20 }
    expected.push(0xa2);
    expected.extend_from_slice(&[0x61, b'x']);
    expected.push(0x0a); // 10
    expected.extend_from_slice(&[0x61, b'y']);
    expected.push(0x14); // 20
    assert_eq!(bytes, expected);
}

// =============================================================================
// Enums
// =============================================================================

#[derive(Facet)]
#[repr(u8)]
enum Color {
    Red,
    Green,
    Blue,
}

#[test]
fn test_unit_variant() {
    let bytes = to_vec(&Color::Red).unwrap();
    // map(1) { "Red": null }
    let mut expected = Vec::new();
    expected.push(0xa1); // map(1)
    expected.extend_from_slice(&[0x63, b'R', b'e', b'd']); // "Red"
    expected.push(0xf6); // null
    assert_eq!(bytes, expected);
}

#[derive(Facet)]
#[repr(u8)]
#[allow(dead_code)]
enum Shape {
    Circle { radius: f64 },
    Rectangle { width: f64, height: f64 },
}

#[test]
fn test_struct_variant() {
    let s = Shape::Circle { radius: 1.5 };
    let bytes = to_vec(&s).unwrap();
    // map(1) { "Circle": map(1) { "radius": 1.5 } }
    let mut expected = Vec::new();
    expected.push(0xa1); // map(1)
    expected.extend_from_slice(&[0x66, b'C', b'i', b'r', b'c', b'l', b'e']); // "Circle"
    expected.push(0xa1); // map(1)
    expected.extend_from_slice(&[0x66, b'r', b'a', b'd', b'i', b'u', b's']); // "radius"
    expected.push(0xfb); // float64
    expected.extend_from_slice(&1.5f64.to_be_bytes());
    assert_eq!(bytes, expected);
}

#[derive(Facet)]
#[repr(u8)]
#[allow(dead_code)]
enum Value {
    Num(i64),
    Text(String),
}

#[test]
fn test_newtype_variant() {
    let v = Value::Num(42);
    let bytes = to_vec(&v).unwrap();
    // map(1) { "Num": 42 }
    let mut expected = Vec::new();
    expected.push(0xa1);
    expected.extend_from_slice(&[0x63, b'N', b'u', b'm']); // "Num"
    expected.extend_from_slice(&[0x18, 0x2a]); // 42
    assert_eq!(bytes, expected);
}

// =============================================================================
// Containers
// =============================================================================

#[test]
fn test_vec() {
    let v = vec![1u32, 2, 3];
    let bytes = to_vec(&v).unwrap();
    // array(3) [1, 2, 3]
    assert_eq!(bytes, vec![0x83, 0x01, 0x02, 0x03]);
}

#[test]
fn test_vec_u8_as_bytes() {
    let v: Vec<u8> = vec![0xde, 0xad, 0xbe, 0xef];
    let bytes = to_vec(&v).unwrap();
    // byte string(4)
    assert_eq!(bytes, vec![0x44, 0xde, 0xad, 0xbe, 0xef]);
}

#[test]
fn test_option_some() {
    let v: Option<u32> = Some(42);
    let bytes = to_vec(&v).unwrap();
    // Just the inner value: 42
    assert_eq!(bytes, vec![0x18, 0x2a]);
}

#[test]
fn test_option_none() {
    let v: Option<u32> = None;
    let bytes = to_vec(&v).unwrap();
    // null
    assert_eq!(bytes, vec![0xf6]);
}

#[test]
fn test_hashmap() {
    let mut m = HashMap::new();
    m.insert(String::from("a"), 1u32);
    let bytes = to_vec(&m).unwrap();
    // map(1) { "a": 1 }
    let mut expected = Vec::new();
    expected.push(0xa1); // map(1)
    expected.extend_from_slice(&[0x61, b'a']); // "a"
    expected.push(0x01); // 1
    assert_eq!(bytes, expected);
}

// =============================================================================
// Deterministic encoding
// =============================================================================

#[test]
fn test_deterministic() {
    let p = Point { x: 42, y: -7 };
    let bytes1 = to_vec(&p).unwrap();
    let bytes2 = to_vec(&p).unwrap();
    assert_eq!(
        bytes1, bytes2,
        "same input must produce identical CBOR bytes"
    );
}

// =============================================================================
// Internally-tagged enums (#[facet(tag = "...")])
// =============================================================================

/// All-unit enum with internal tag: each variant serializes as just a string
#[derive(Facet, Debug, PartialEq)]
#[repr(u8)]
#[facet(tag = "tag", rename_all = "snake_case")]
#[allow(dead_code)]
enum PrimType {
    Bool,
    U8,
    U16,
    String,
}

#[test]
fn test_internally_tagged_unit_variant() {
    // Unit variant with internal tag → just the renamed variant name as a string
    let bytes = to_vec(&PrimType::Bool).unwrap();
    // Should be just text("bool")
    assert_eq!(bytes, vec![0x64, b'b', b'o', b'o', b'l']);
}

#[test]
fn test_internally_tagged_unit_variant_u8() {
    let bytes = to_vec(&PrimType::U8).unwrap();
    // text("u8")
    assert_eq!(bytes, vec![0x62, b'u', b'8']);
}

#[test]
fn test_internally_tagged_unit_variant_string() {
    let bytes = to_vec(&PrimType::String).unwrap();
    // text("string")
    assert_eq!(bytes, vec![0x66, b's', b't', b'r', b'i', b'n', b'g']);
}

/// Enum with struct variants and internal tag
#[derive(Facet, Debug, PartialEq)]
#[repr(u8)]
#[facet(tag = "tag", rename_all = "snake_case")]
#[allow(dead_code)]
enum TaggedShape {
    Struct { name: String, field_count: u32 },
    Primitive { primitive_type: String },
}

#[test]
fn test_internally_tagged_struct_variant() {
    let s = TaggedShape::Primitive {
        primitive_type: "bool".to_string(),
    };
    let bytes = to_vec(&s).unwrap();
    // map(2) { "tag": "primitive", "primitive_type": "bool" }
    let decoded: std::collections::HashMap<String, String> =
        facet_cbor::from_slice(&bytes).unwrap();
    assert_eq!(decoded.get("tag").unwrap(), "primitive");
    assert_eq!(decoded.get("primitive_type").unwrap(), "bool");
}

#[test]
fn test_internally_tagged_struct_variant_multi_field() {
    let s = TaggedShape::Struct {
        name: "Foo".to_string(),
        field_count: 3,
    };
    let bytes = to_vec(&s).unwrap();
    // Should be map(3) { "tag": "struct", "name": "Foo", "field_count": 3 }
    // Verify by decoding as a generic map
    let mut offset = 0;
    // Read map header
    assert_eq!(bytes[0], 0xa3); // map(3)
    offset += 1;

    // Read "tag" key
    let tag_key_len = bytes[offset] - 0x60;
    offset += 1;
    let tag_key = std::str::from_utf8(&bytes[offset..offset + tag_key_len as usize]).unwrap();
    assert_eq!(tag_key, "tag");
    offset += tag_key_len as usize;

    // Read "struct" value
    let tag_val_len = bytes[offset] - 0x60;
    offset += 1;
    let tag_val = std::str::from_utf8(&bytes[offset..offset + tag_val_len as usize]).unwrap();
    assert_eq!(tag_val, "struct");
}

/// Mixed enum: both unit and struct variants
#[derive(Facet, Debug, PartialEq)]
#[repr(u8)]
#[facet(tag = "tag", rename_all = "snake_case")]
#[allow(dead_code)]
enum MixedTagged {
    Unit,
    WithData { value: u32 },
}

#[test]
fn test_internally_tagged_mixed_unit() {
    let bytes = to_vec(&MixedTagged::Unit).unwrap();
    // text("unit")
    assert_eq!(bytes, vec![0x64, b'u', b'n', b'i', b't']);
}

#[test]
fn test_internally_tagged_mixed_struct() {
    let bytes = to_vec(&MixedTagged::WithData { value: 42 }).unwrap();
    // map(2) { "tag": "with_data", "value": 42 }
    assert_eq!(bytes[0], 0xa2); // map(2)
}

/// Roundtrip test: serialize then deserialize
#[test]
fn test_internally_tagged_roundtrip_unit() {
    let original = PrimType::U16;
    let bytes = to_vec(&original).unwrap();
    let decoded: PrimType = facet_cbor::from_slice(&bytes).unwrap();
    assert_eq!(decoded, original);
}

#[test]
fn test_internally_tagged_roundtrip_struct() {
    let original = TaggedShape::Primitive {
        primitive_type: "u32".to_string(),
    };
    let bytes = to_vec(&original).unwrap();
    let decoded: TaggedShape = facet_cbor::from_slice(&bytes).unwrap();
    assert_eq!(decoded, original);
}

#[test]
fn test_internally_tagged_roundtrip_struct_multi_field() {
    let original = TaggedShape::Struct {
        name: "Point".to_string(),
        field_count: 2,
    };
    let bytes = to_vec(&original).unwrap();
    let decoded: TaggedShape = facet_cbor::from_slice(&bytes).unwrap();
    assert_eq!(decoded, original);
}

#[test]
fn test_internally_tagged_roundtrip_mixed() {
    for original in [MixedTagged::Unit, MixedTagged::WithData { value: 99 }] {
        let bytes = to_vec(&original).unwrap();
        let decoded: MixedTagged = facet_cbor::from_slice(&bytes).unwrap();
        assert_eq!(decoded, original);
    }
}

/// Verify that rename_all = "snake_case" converts PascalCase correctly
#[derive(Facet, Debug, PartialEq)]
#[repr(u8)]
#[facet(tag = "tag", rename_all = "snake_case")]
#[allow(dead_code)]
enum CasingTest {
    SimpleCase,
    TwoWords,
    XMLParser,
}

#[test]
fn test_rename_all_snake_case() {
    // SimpleCase → "simple_case"
    let bytes = to_vec(&CasingTest::SimpleCase).unwrap();
    let s = std::str::from_utf8(&bytes[1..]).unwrap(); // skip length byte
    assert_eq!(s, "simple_case");
}

#[test]
fn test_rename_all_two_words() {
    let bytes = to_vec(&CasingTest::TwoWords).unwrap();
    let s = std::str::from_utf8(&bytes[1..]).unwrap();
    assert_eq!(s, "two_words");
}

/// Verify externally-tagged enums still use original names (no rename)
#[derive(Facet, Debug, PartialEq)]
#[repr(u8)]
#[allow(dead_code)]
enum NoRename {
    MyVariant,
}

#[test]
fn test_externally_tagged_no_rename() {
    let bytes = to_vec(&NoRename::MyVariant).unwrap();
    // map(1) { "MyVariant": null } — should use original PascalCase name
    let mut expected = Vec::new();
    expected.push(0xa1); // map(1)
    expected.extend_from_slice(&[0x69]); // text(9)
    expected.extend_from_slice(b"MyVariant");
    expected.push(0xf6); // null
    assert_eq!(bytes, expected);
}

/// Verify externally-tagged + rename_all uses renamed names
#[derive(Facet, Debug, PartialEq)]
#[repr(u8)]
#[facet(rename_all = "snake_case")]
#[allow(dead_code)]
enum ExtRename {
    MyVariant,
}

#[test]
fn test_externally_tagged_with_rename() {
    let bytes = to_vec(&ExtRename::MyVariant).unwrap();
    // map(1) { "my_variant": null } — should use renamed name
    let mut expected = Vec::new();
    expected.push(0xa1); // map(1)
    expected.extend_from_slice(&[0x6a]); // text(10)
    expected.extend_from_slice(b"my_variant");
    expected.push(0xf6); // null
    assert_eq!(bytes, expected);
}

// =============================================================================
// Negative integer encoding
// =============================================================================

#[test]
fn test_negative_integers_use_major_1() {
    // -1 → 0x20 (major 1, additional 0)
    let bytes = to_vec(&-1i32).unwrap();
    assert_eq!(bytes[0] >> 5, 1, "first byte should have major type 1");
    assert_eq!(bytes, vec![0x20]);

    // -24 → 0x37 (major 1, additional 23)
    let bytes = to_vec(&-24i32).unwrap();
    assert_eq!(bytes, vec![0x37]);

    // -25 → 0x38, 0x18 (major 1, additional 24, value 24)
    let bytes = to_vec(&-25i32).unwrap();
    assert_eq!(bytes, vec![0x38, 0x18]);
}