facet-json 0.46.1

JSON serialization for facet using the new format architecture
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! Regression test for https://github.com/facet-rs/facet/issues/2124
//!
//! Internally-tagged enums with newtype variants wrapping structs or other
//! tagged enums fail to serialize/deserialize.

use facet::Facet;
use facet_testhelpers::test;

// ---------------------------------------------------------------------------
// Shared types
// ---------------------------------------------------------------------------

#[derive(Facet, Clone, PartialEq, Debug)]
pub struct Filter {
    pub name: String,
}

#[derive(Facet, Clone, PartialEq, Debug)]
#[facet(tag = "add_type")]
#[repr(C)]
pub enum AddOp {
    Full,
    Filtered { filter: Filter },
}

#[derive(Facet, Clone, PartialEq, Debug)]
#[facet(tag = "inner_type")]
#[repr(C)]
pub enum Inner {
    Include(AddOp),
    Exclude(Filter),
}

#[derive(Facet, Clone, PartialEq, Debug)]
#[facet(tag = "outer_type")]
#[repr(C)]
pub enum Outer {
    Nested(Inner),
    Simple { value: f64 },
}

// ---------------------------------------------------------------------------
// Newtype variant wrapping a plain struct
// ---------------------------------------------------------------------------

#[test]
fn test_issue_2124_inner_exclude() {
    let expected = Inner::Exclude(Filter { name: "x".into() });

    // Roundtrip
    let json = facet_json::to_string(&expected).unwrap();
    let back: Inner = facet_json::from_str(&json).unwrap();
    assert_eq!(expected, back);

    // Deserialize from known JSON
    let back: Inner = facet_json::from_str(r#"{"inner_type":"Exclude","name":"x"}"#).unwrap();
    assert_eq!(expected, back);
}

// ---------------------------------------------------------------------------
// Newtype wrapping a tagged enum (two levels of tags)
// ---------------------------------------------------------------------------

#[test]
fn test_issue_2124_inner_include_full() {
    let expected = Inner::Include(AddOp::Full);

    let json = facet_json::to_string(&expected).unwrap();
    let back: Inner = facet_json::from_str(&json).unwrap();
    assert_eq!(expected, back);

    let back: Inner =
        facet_json::from_str(r#"{"inner_type":"Include","add_type":"Full"}"#).unwrap();
    assert_eq!(expected, back);
}

#[test]
fn test_issue_2124_inner_include_filtered() {
    let expected = Inner::Include(AddOp::Filtered {
        filter: Filter { name: "f".into() },
    });

    let json = facet_json::to_string(&expected).unwrap();
    let back: Inner = facet_json::from_str(&json).unwrap();
    assert_eq!(expected, back);

    let back: Inner = facet_json::from_str(
        r#"{"inner_type":"Include","add_type":"Filtered","filter":{"name":"f"}}"#,
    )
    .unwrap();
    assert_eq!(expected, back);
}

// ---------------------------------------------------------------------------
// Three levels of tags (outer → inner → add_type)
// ---------------------------------------------------------------------------

#[test]
fn test_issue_2124_outer_nested_include_filtered() {
    let expected = Outer::Nested(Inner::Include(AddOp::Filtered {
        filter: Filter { name: "f".into() },
    }));

    let json = facet_json::to_string(&expected).unwrap();
    let back: Outer = facet_json::from_str(&json).unwrap();
    assert_eq!(expected, back);

    let back: Outer = facet_json::from_str(
        r#"{"outer_type":"Nested","inner_type":"Include","add_type":"Filtered","filter":{"name":"f"}}"#,
    )
    .unwrap();
    assert_eq!(expected, back);
}

#[test]
fn test_issue_2124_outer_nested_exclude() {
    let expected = Outer::Nested(Inner::Exclude(Filter {
        name: "gone".into(),
    }));

    let json = facet_json::to_string(&expected).unwrap();
    let back: Outer = facet_json::from_str(&json).unwrap();
    assert_eq!(expected, back);

    let back: Outer =
        facet_json::from_str(r#"{"outer_type":"Nested","inner_type":"Exclude","name":"gone"}"#)
            .unwrap();
    assert_eq!(expected, back);
}

#[test]
fn test_issue_2124_outer_simple() {
    // Struct variant (not a newtype) — should already work, included for completeness.
    let expected = Outer::Simple { value: 1.5 };

    let json = facet_json::to_string(&expected).unwrap();
    let back: Outer = facet_json::from_str(&json).unwrap();
    assert_eq!(expected, back);

    let back: Outer = facet_json::from_str(r#"{"outer_type":"Simple","value":1.5}"#).unwrap();
    assert_eq!(expected, back);
}

// ---------------------------------------------------------------------------
// Three-level nesting: Top(tagged) → Middle(tagged newtype) → Config(struct)
// ---------------------------------------------------------------------------

#[derive(Facet, Clone, PartialEq, Debug)]
pub struct Config {
    pub enabled: bool,
}

#[derive(Facet, Clone, PartialEq, Debug)]
#[facet(tag = "level2")]
#[repr(C)]
pub enum Middle {
    Wrap(Config),
}

#[derive(Facet, Clone, PartialEq, Debug)]
#[facet(tag = "level1")]
#[repr(C)]
pub enum Top {
    Deep(Middle),
}

#[test]
fn test_issue_2124_three_level_nesting() {
    let expected = Top::Deep(Middle::Wrap(Config { enabled: true }));

    let json = facet_json::to_string(&expected).unwrap();
    let back: Top = facet_json::from_str(&json).unwrap();
    assert_eq!(expected, back);

    let back: Top =
        facet_json::from_str(r#"{"level1":"Deep","level2":"Wrap","enabled":true}"#).unwrap();
    assert_eq!(expected, back);
}

// ---------------------------------------------------------------------------
// Mixed variant kinds: unit + struct + newtype in one tagged enum
// ---------------------------------------------------------------------------

#[derive(Facet, Clone, PartialEq, Debug)]
#[facet(tag = "kind")]
#[repr(C)]
pub enum Mixed {
    Unit,
    Named { x: i32 },
    Newtype(Filter),
}

#[test]
fn test_issue_2124_mixed_variants() {
    // Unit and Named variants should already work; Newtype is the new case.
    let cases: Vec<(Mixed, &str)> = vec![
        (Mixed::Unit, r#"{"kind":"Unit"}"#),
        (Mixed::Named { x: 42 }, r#"{"kind":"Named","x":42}"#),
        (
            Mixed::Newtype(Filter { name: "abc".into() }),
            r#"{"kind":"Newtype","name":"abc"}"#,
        ),
    ];

    for (expected, known_json) in cases {
        let json = facet_json::to_string(&expected).unwrap();
        let back: Mixed = facet_json::from_str(&json).unwrap();
        assert_eq!(expected, back);

        let back: Mixed = facet_json::from_str(known_json).unwrap();
        assert_eq!(expected, back);
    }
}

// ---------------------------------------------------------------------------
// Newtype wrapping a struct with optional fields (defaults must apply)
// ---------------------------------------------------------------------------

#[derive(Facet, Clone, PartialEq, Debug)]
pub struct OptFields {
    pub required: String,
    pub optional: Option<i32>,
}

#[derive(Facet, Clone, PartialEq, Debug)]
#[facet(tag = "t")]
#[repr(C)]
pub enum WithOpt {
    Val(OptFields),
}

// ---------------------------------------------------------------------------
// Regression test: newtype wrapping a struct with #[facet(flatten)].
// Previously the newtype deserialization path used `field_lookup.find()` (a
// flat name→index lookup) which did not recurse into flattened sub-structs.
// Fixed by extracting `read_tagged_object_fields` which uses `find_field_path`
// when `has_flatten` is set.
// ---------------------------------------------------------------------------

#[derive(Facet, Clone, PartialEq, Debug)]
pub struct GeoCoords {
    pub lat: f64,
    pub lng: f64,
}

#[derive(Facet, Clone, PartialEq, Debug)]
pub struct Location {
    pub label: String,
    #[facet(flatten)]
    pub coords: GeoCoords,
}

#[derive(Facet, Clone, PartialEq, Debug)]
#[facet(tag = "type")]
#[repr(C)]
pub enum Place {
    /// Newtype variant wrapping a struct that has a flattened field.
    /// JSON: {"type":"Pin","label":"HQ","lat":1.0,"lng":2.0}
    Pin(Location),
    /// Struct variant for comparison.
    Inline {
        label: String,
        #[facet(flatten)]
        coords: GeoCoords,
    },
}

#[test]
fn test_issue_2124_newtype_with_flatten_struct_variant_works() {
    // Struct variant with flatten — this already works via the has_flatten /
    // find_field_path code path. Included to contrast with the newtype case.
    let expected = Place::Inline {
        label: "HQ".into(),
        coords: GeoCoords { lat: 1.0, lng: 2.0 },
    };

    let json = facet_json::to_string(&expected).unwrap();
    let back: Place = facet_json::from_str(&json).unwrap();
    assert_eq!(expected, back);

    let back: Place =
        facet_json::from_str(r#"{"type":"Inline","label":"HQ","lat":1.0,"lng":2.0}"#).unwrap();
    assert_eq!(expected, back);
}

#[test]
fn test_issue_2124_newtype_with_flatten() {
    // Newtype variant wrapping a struct with #[facet(flatten)].
    let expected = Place::Pin(Location {
        label: "HQ".into(),
        coords: GeoCoords { lat: 1.0, lng: 2.0 },
    });

    let json = facet_json::to_string(&expected).unwrap();
    let back: Place = facet_json::from_str(&json).unwrap();
    assert_eq!(expected, back);

    let back: Place =
        facet_json::from_str(r#"{"type":"Pin","label":"HQ","lat":1.0,"lng":2.0}"#).unwrap();
    assert_eq!(expected, back);
}

// ---------------------------------------------------------------------------
// Regression test: newtype wrapping an internally-tagged enum whose struct
// variant has #[facet(flatten)]. Same root cause as above, also fixed by the
// shared `read_tagged_object_fields` helper.
// ---------------------------------------------------------------------------

#[derive(Facet, Clone, PartialEq, Debug)]
pub struct Metadata {
    pub author: String,
    pub version: u32,
}

#[derive(Facet, Clone, PartialEq, Debug)]
#[facet(tag = "kind")]
#[repr(C)]
pub enum Document {
    Report {
        title: String,
        #[facet(flatten)]
        meta: Metadata,
    },
}

#[derive(Facet, Clone, PartialEq, Debug)]
#[facet(tag = "wrapper")]
#[repr(C)]
pub enum Envelope {
    Doc(Document),
}

#[test]
fn test_issue_2124_newtype_inner_enum_with_flatten() {
    // Two-level newtype: Envelope(tagged) → Document(tagged) → Report { flatten }
    let expected = Envelope::Doc(Document::Report {
        title: "Annual".into(),
        meta: Metadata {
            author: "Alice".into(),
            version: 3,
        },
    });

    let json = facet_json::to_string(&expected).unwrap();
    let back: Envelope = facet_json::from_str(&json).unwrap();
    assert_eq!(expected, back);

    let back: Envelope = facet_json::from_str(
        r#"{"wrapper":"Doc","kind":"Report","title":"Annual","author":"Alice","version":3}"#,
    )
    .unwrap();
    assert_eq!(expected, back);
}

// ---------------------------------------------------------------------------
// Duplicate tag keys across nesting levels must produce a clear error
// ---------------------------------------------------------------------------

#[derive(Facet, Clone, PartialEq, Debug)]
#[facet(tag = "type")]
#[repr(C)]
pub enum InnerSameTag {
    A { x: i32 },
}

#[derive(Facet, Clone, PartialEq, Debug)]
#[facet(tag = "type")]
#[repr(C)]
pub enum OuterSameTag {
    Wrap(InnerSameTag),
}

#[test]
fn test_issue_2124_duplicate_tag_key_serialize_error() {
    // Both enums use #[facet(tag = "type")]. When flattened into a single
    // object the two "type" keys are ambiguous — serialization must fail.
    let value = OuterSameTag::Wrap(InnerSameTag::A { x: 1 });
    let result = facet_json::to_string(&value);
    assert!(
        result.is_err(),
        "expected error for duplicate tag key, got: {result:?}"
    );
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("same tag key"),
        "error should mention 'same tag key', got: {err}"
    );
}

#[test]
fn test_issue_2124_duplicate_tag_key_deserialize_error() {
    // Attempting to deserialize a JSON object where both nesting levels share
    // the same tag key must fail with a clear error.
    let json = r#"{"type":"Wrap","type":"A","x":1}"#;
    let result = facet_json::from_str::<OuterSameTag>(json);
    assert!(
        result.is_err(),
        "expected error for duplicate tag key, got: {result:?}"
    );
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("same tag key"),
        "error should mention 'same tag key', got: {err}"
    );
}

// ---------------------------------------------------------------------------
// Flattened field name equals tag key — the field is silently shadowed
// ---------------------------------------------------------------------------

#[derive(Facet, Clone, PartialEq, Debug)]
pub struct HasTypeField {
    /// This field has the same name as the tag key used by the wrapping enum.
    pub kind: String,
    pub other: i32,
}

#[derive(Facet, Clone, PartialEq, Debug)]
#[facet(tag = "kind")]
#[repr(C)]
pub enum TagCollidesWithField {
    Wrap(HasTypeField),
}

#[test]
fn test_issue_2124_field_name_equals_tag_key_roundtrip() {
    // The struct field `kind` collides with the enum's tag key `kind`.
    // During serialization the tag is written first, then the struct's fields
    // are flattened — producing two `kind` entries in the JSON object.
    let value = TagCollidesWithField::Wrap(HasTypeField {
        kind: "should_be_lost".into(),
        other: 42,
    });

    let json = facet_json::to_string(&value).unwrap();
    // The JSON will contain two "kind" keys — the tag and the field.
    assert!(
        json.contains(r#""kind":"Wrap"#),
        "tag must be present: {json}"
    );

    // Deserializing back fails: the tag skip logic swallows all "kind" keys,
    // so the required struct field is never populated → missing field error.
    let result = facet_json::from_str::<TagCollidesWithField>(&json);
    assert!(
        result.is_err(),
        "should error because the struct field is shadowed by the tag key"
    );
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("kind"),
        "error should mention the missing field 'kind', got: {err}"
    );
}

#[test]
fn test_issue_2124_field_name_equals_tag_key_deser_from_known() {
    // Explicit JSON where the struct's `kind` field appears (after the tag).
    // The deserializer skips all occurrences of the tag key, so the required
    // field is never set — resulting in a missing-field error.
    let json = r#"{"kind":"Wrap","kind":"hello","other":99}"#;
    let result = facet_json::from_str::<TagCollidesWithField>(json);
    assert!(
        result.is_err(),
        "should error because the struct field is shadowed by the tag key"
    );
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("kind"),
        "error should mention the missing field 'kind', got: {err}"
    );
}

// ---------------------------------------------------------------------------
// Unknown fields in the newtype-chain path (without flatten)
// ---------------------------------------------------------------------------

#[test]
fn test_issue_2124_unknown_fields_skipped_in_newtype() {
    // Extra/unknown keys in the JSON should be silently skipped when
    // deserializing through a newtype chain (no #[facet(flatten)]).
    let json = r#"{"inner_type":"Exclude","name":"x","unknown_key":"ignored","another":123}"#;
    let back: Inner = facet_json::from_str(json).unwrap();
    assert_eq!(back, Inner::Exclude(Filter { name: "x".into() }));
}

#[test]
fn test_issue_2124_unknown_fields_skipped_in_nested_newtype() {
    // Three-level nesting with unknown fields scattered in the JSON object.
    let json = r#"{"outer_type":"Nested","bogus":true,"inner_type":"Include","add_type":"Full","extra":"nope"}"#;
    let back: Outer = facet_json::from_str(json).unwrap();
    assert_eq!(back, Outer::Nested(Inner::Include(AddOp::Full)));
}

// ---------------------------------------------------------------------------
// Unknown fields in the newtype-chain path (with flatten)
// ---------------------------------------------------------------------------

#[test]
fn test_issue_2124_unknown_fields_skipped_with_flatten_newtype() {
    // Place::Pin is a newtype wrapping Location which has #[facet(flatten)].
    // Unknown keys should be silently skipped.
    let json = r#"{"type":"Pin","label":"HQ","lat":1.0,"lng":2.0,"unknown":"skip_me"}"#;
    let back: Place = facet_json::from_str(json).unwrap();
    assert_eq!(
        back,
        Place::Pin(Location {
            label: "HQ".into(),
            coords: GeoCoords { lat: 1.0, lng: 2.0 },
        })
    );
}

#[test]
fn test_issue_2124_unknown_fields_skipped_with_flatten_nested_enum() {
    // Envelope::Doc is a newtype wrapping Document (tagged enum) whose
    // Report variant has #[facet(flatten)]. Unknown keys should be skipped.
    let json = r#"{"wrapper":"Doc","kind":"Report","title":"Annual","author":"Alice","version":3,"junk":false}"#;
    let back: Envelope = facet_json::from_str(json).unwrap();
    assert_eq!(
        back,
        Envelope::Doc(Document::Report {
            title: "Annual".into(),
            meta: Metadata {
                author: "Alice".into(),
                version: 3,
            },
        })
    );
}

// ---------------------------------------------------------------------------
// Newtype wrapping a struct with optional fields (defaults must apply)
// ---------------------------------------------------------------------------

#[test]
fn test_issue_2124_newtype_optional_fields() {
    let cases: Vec<(WithOpt, &str)> = vec![
        (
            WithOpt::Val(OptFields {
                required: "hi".into(),
                optional: None,
            }),
            r#"{"t":"Val","required":"hi","optional":null}"#,
        ),
        (
            WithOpt::Val(OptFields {
                required: "hi".into(),
                optional: Some(7),
            }),
            r#"{"t":"Val","required":"hi","optional":7}"#,
        ),
    ];

    for (expected, known_json) in cases {
        let json = facet_json::to_string(&expected).unwrap();
        let back: WithOpt = facet_json::from_str(&json).unwrap();
        assert_eq!(expected, back);

        let back: WithOpt = facet_json::from_str(known_json).unwrap();
        assert_eq!(expected, back);
    }
}