structio 0.7.0

High performance JSON and BEVE for Rust structs. No dependencies, no proc-macros, no intermediate representation.
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! A declaration that generates the write half alone.
//!
//! The format axis and the direction axis are both narrowable: `json_object!`
//! picks a format, and a declaration that leads with `write_only` picks a
//! direction. What that buys is entirely negative, and is the thing tested
//! here: no `Read` impl is generated, so no field's type has to have one, and
//! a type parameter carries neither the read bound nor the `Default` that a
//! read needs in order to construct the value it fills.
//!
//! Everything else has to be untouched. A narrowed declaration's output is the
//! output of the same declaration unnarrowed, byte for byte, through every
//! shape and both formats: the keys, the case rule, the adapters, the typed
//! array a positional struct packs into, the string array a run of a unit enum
//! packs into, and what `SkipNull` drops. Each of those is asserted against a
//! twin type declared both ways, because "the same code, minus one half" is
//! the claim the feature rests on and a twin is what can hold it to it.
//!
//! `tests/directions.rs` holds the case this does not answer: a struct that
//! really is read and written, with one field that means nothing in one of
//! those directions.

use std::collections::BTreeMap;

use structio::{
    Options, Pretty, SkipNull, beve, json, to_beve, to_beve_with, to_string, to_string_with,
};

// ---------------------------------------------------------------------------
// A type that can be written and cannot be read
// ---------------------------------------------------------------------------

/// A value the program can put on the wire and could not take off it.
///
/// It has no `Read` impl and no `Default`, which is what makes it the probe:
/// a declaration that demands either of those does not compile with this as a
/// field's type, so every use of it below is an assertion in itself.
struct Register(u32);

impl json::Write for Register {
    fn write<O: Options>(&self, w: &mut json::Writer<'_, O>) {
        self.0.write(w);
    }
}

impl beve::Write for Register {
    fn write<O: Options>(&self, w: &mut beve::Writer<'_, O>) {
        self.0.write(w);
    }
}

struct Surface {
    id: Register,
    volts: f64,
}
structio::object!(write_only Surface { id, volts });

#[test]
fn a_field_type_needs_no_read_impl_and_no_default() {
    let s = Surface {
        id: Register(7),
        volts: 3.25,
    };
    assert_eq!(to_string(&s), r#"{"id":7,"volts":3.25}"#);
    // Nothing reads a `Surface`, so what stands in for a round trip is a
    // transcode: it walks the BEVE bytes without the type, and so fails if the
    // member count in the object header disagrees with the members written
    // after it.
    assert_eq!(
        structio::transcode::beve_to_json(&to_beve(&s)).unwrap(),
        r#"{"id":7,"volts":3.25}"#
    );
}

// ---------------------------------------------------------------------------
// The same output as the declaration it is half of
// ---------------------------------------------------------------------------

/// Two structs with the same fields, declared both ways.
///
/// Every assertion below compares one against the other, which is what makes
/// the claim testable at all: `write_only` is not supposed to change a byte of
/// what goes out, only to stop generating what comes in.
#[derive(Default)]
struct BothWays {
    device_id: u32,
    label: String,
    reading: Option<f64>,
}
structio::object!(BothWays as "camelCase" {
    #[required] device_id,
    "tag" => label,
    reading,
});

struct WriteHalf {
    device_id: u32,
    label: String,
    reading: Option<f64>,
}
structio::object!(write_only WriteHalf as "camelCase" {
    device_id,
    "tag" => label,
    reading,
});

fn twins() -> (BothWays, WriteHalf) {
    (
        BothWays {
            device_id: 4,
            label: "north".into(),
            reading: None,
        },
        WriteHalf {
            device_id: 4,
            label: "north".into(),
            reading: None,
        },
    )
}

#[test]
fn the_keys_the_case_rule_and_the_bytes_are_unchanged() {
    let (both, half) = twins();
    assert_eq!(to_string(&half), to_string(&both));
    assert_eq!(
        to_string(&half),
        r#"{"deviceId":4,"tag":"north","reading":null}"#
    );
    assert_eq!(to_beve(&half), to_beve(&both));
}

#[test]
fn a_write_policy_reaches_it_the_same_way() {
    let (both, half) = twins();
    assert_eq!(
        to_string_with::<Pretty, _>(&half),
        to_string_with::<Pretty, _>(&both)
    );
    // `SkipNull` drops the absent `Option`, and BEVE has to drop it from the
    // member count as well as from the members: a disagreement between
    // `count_fields` and `write_fields` is a malformed document, not a
    // mismatched byte, so comparing against the twin is what catches it.
    assert_eq!(
        to_string_with::<SkipNull, _>(&half),
        r#"{"deviceId":4,"tag":"north"}"#
    );
    assert_eq!(
        to_beve_with::<SkipNull, _>(&half),
        to_beve_with::<SkipNull, _>(&both)
    );
}

// ---------------------------------------------------------------------------
// A field the declaration leaves out
// ---------------------------------------------------------------------------

struct Partial {
    kept: u32,
    #[allow(dead_code)]
    dropped: Register,
}
structio::object!(write_only Partial { kept, .. });

#[test]
fn a_declaration_may_still_end_in_rest() {
    let p = Partial {
        kept: 1,
        dropped: Register(9),
    };
    assert_eq!(to_string(&p), r#"{"kept":1}"#);
    assert_eq!(
        structio::transcode::beve_to_json(&to_beve(&p)).unwrap(),
        r#"{"kept":1}"#
    );
}

// ---------------------------------------------------------------------------
// An adapter with one half
// ---------------------------------------------------------------------------

/// An adapter for a position that is only ever written, carrying `WriteAs` and
/// no `ReadAs`.
struct Tenths;

impl json::WriteAs<u32> for Tenths {
    fn write<O: Options>(value: &u32, w: &mut json::Writer<'_, O>) {
        json::Write::write(&(*value as f64 / 10.0), w);
    }
}

impl beve::WriteAs<u32> for Tenths {
    fn write<O: Options>(value: &u32, w: &mut beve::Writer<'_, O>) {
        beve::Write::write(&(*value as f64 / 10.0), w);
    }
}

struct Adapted {
    scaled: u32,
}
structio::object!(write_only Adapted { scaled as Tenths });

#[test]
fn an_adapter_needs_only_its_write_half() {
    assert_eq!(to_string(&Adapted { scaled: 25 }), r#"{"scaled":2.5}"#);
    assert!(!to_beve(&Adapted { scaled: 25 }).is_empty());
}

// ---------------------------------------------------------------------------
// A positional struct
// ---------------------------------------------------------------------------

#[derive(Default)]
struct PointBoth {
    x: f64,
    y: f64,
}
structio::array!(PointBoth [ f64; x, y ]);

struct PointHalf {
    x: f64,
    y: f64,
}
structio::array!(write_only PointHalf [ f64; x, y ]);

#[test]
fn a_positional_struct_keeps_its_typed_array() {
    let (both, half) = (PointBoth { x: 1.5, y: -2.0 }, PointHalf { x: 1.5, y: -2.0 });
    assert_eq!(to_string(&half), "[1.5,-2]");
    assert_eq!(to_string(&half), to_string(&both));
    // The element type is what makes this one typed array rather than a
    // generic one, and it is written from the write half, so narrowing must
    // not lose it.
    assert_eq!(to_beve(&half), to_beve(&both));
}

/// A positional struct of a type that cannot be read, which is the array
/// shape's version of the probe.
struct Registers {
    a: Register,
    b: Register,
}
structio::array!(write_only Registers [ a, b ]);

#[test]
fn a_positional_element_needs_no_read_impl() {
    let r = Registers {
        a: Register(1),
        b: Register(2),
    };
    assert_eq!(to_string(&r), "[1,2]");
}

// ---------------------------------------------------------------------------
// Enums
// ---------------------------------------------------------------------------

#[derive(Default)]
enum LevelBoth {
    #[default]
    Info,
    Warning,
}
structio::unit_enum!(LevelBoth as "snake_case" { Info, "WARN" => Warning });

enum LevelHalf {
    Info,
    Warning,
}
structio::unit_enum!(write_only LevelHalf as "snake_case" { Info, "WARN" => Warning });

#[test]
fn a_unit_enum_keeps_its_string_array_packing() {
    assert_eq!(to_string(&LevelHalf::Warning), r#""WARN""#);
    assert_eq!(to_string(&LevelHalf::Info), to_string(&LevelBoth::Info));
    // A run of a unit enum is one BEVE string array rather than a value per
    // element. That packing is `Write::ARRAY` and `write_payload`, both on the
    // write half, so a narrowed declaration has to carry them.
    let half = vec![LevelHalf::Info, LevelHalf::Warning];
    let both = vec![LevelBoth::Info, LevelBoth::Warning];
    assert_eq!(to_beve(&half), to_beve(&both));
}

#[derive(Default)]
struct Payload {
    mode: u8,
}
structio::object!(Payload { mode });

#[derive(Default)]
enum MsgBoth {
    #[default]
    Idle,
    Config(Payload),
}
structio::tagged_enum!(MsgBoth { Idle, Config(_) });

enum MsgHalf {
    Idle,
    Config(Payload),
}
structio::tagged_enum!(write_only MsgHalf { Idle, Config(_) });

#[test]
fn an_externally_tagged_enum_narrows() {
    assert_eq!(
        to_string(&MsgHalf::Config(Payload { mode: 2 })),
        r#"{"Config":{"mode":2}}"#
    );
    assert_eq!(to_string(&MsgHalf::Idle), to_string(&MsgBoth::Idle));
    assert_eq!(
        to_beve(&MsgHalf::Config(Payload { mode: 2 })),
        to_beve(&MsgBoth::Config(Payload { mode: 2 }))
    );
}

#[derive(Default)]
enum TaggedBoth {
    #[default]
    Idle,
    Config(Payload),
}
structio::tagged_enum!(TaggedBoth as tag "kind" { Idle, Config(_) });

enum TaggedHalf {
    Idle,
    Config(Payload),
}
structio::tagged_enum!(write_only TaggedHalf as tag "kind" { Idle, Config(_) });

#[test]
fn an_internally_tagged_enum_narrows() {
    assert_eq!(
        to_string(&TaggedHalf::Config(Payload { mode: 2 })),
        r#"{"kind":"Config","mode":2}"#
    );
    assert_eq!(
        to_string(&TaggedHalf::Config(Payload { mode: 2 })),
        to_string(&TaggedBoth::Config(Payload { mode: 2 }))
    );
    assert_eq!(
        to_beve(&TaggedHalf::Config(Payload { mode: 2 })),
        to_beve(&TaggedBoth::Config(Payload { mode: 2 }))
    );
    // A variant carrying nothing is the tag member and nothing else, which is
    // the same object with one member either way.
    assert_eq!(to_string(&TaggedHalf::Idle), to_string(&TaggedBoth::Idle));
    assert_eq!(to_beve(&TaggedHalf::Idle), to_beve(&TaggedBoth::Idle));
}

// ---------------------------------------------------------------------------
// One format and one direction
// ---------------------------------------------------------------------------

struct JsonOnly {
    id: Register,
}
structio::json_object!(write_only JsonOnly { id });

struct BeveOnly<'a> {
    payload: &'a [u8],
}
structio::beve_object!(write_only ['a] BeveOnly<'a> { payload });

#[test]
fn the_two_axes_narrow_independently() {
    assert_eq!(to_string(&JsonOnly { id: Register(3) }), r#"{"id":3}"#);
    assert!(
        !to_beve(&BeveOnly {
            payload: &[1, 2, 3]
        })
        .is_empty()
    );
}

// ---------------------------------------------------------------------------
// Generics
// ---------------------------------------------------------------------------

/// The bound is `structio::Write` rather than `structio::ReadWrite + Default`,
/// which is the difference that lets `Register` be the parameter at all.
struct Sample<T> {
    value: T,
}
structio::object!(write_only [T: structio::Write] Sample<T> { value });

#[test]
fn a_type_parameter_carries_the_write_bound_alone() {
    assert_eq!(
        to_string(&Sample {
            value: Register(11)
        }),
        r#"{"value":11}"#
    );
    assert_eq!(to_string(&Sample { value: 2u8 }), r#"{"value":2}"#);
}
// ---------------------------------------------------------------------------
// The derive says the same thing
// ---------------------------------------------------------------------------

#[cfg(feature = "derive")]
#[derive(structio::Structio)]
#[structio(write_only, rename_all = "camelCase")]
struct Derived {
    device_id: u32,
    #[structio(rename = "tag")]
    label: String,
    reading: Option<f64>,
}

#[cfg(feature = "derive")]
#[derive(structio::Structio)]
#[structio(write_only)]
struct DerivedSample<T> {
    value: T,
}

#[cfg(feature = "derive")]
#[test]
fn the_derive_expands_to_the_narrowed_declaration() {
    let derived = Derived {
        device_id: 4,
        label: "north".into(),
        reading: None,
    };
    let (both, _) = twins();
    assert_eq!(to_string(&derived), to_string(&both));
    assert_eq!(to_beve(&derived), to_beve(&both));
    // And the parameter of a derived generic loses the same two bounds.
    assert_eq!(
        to_string(&DerivedSample {
            value: Register(11)
        }),
        r#"{"value":11}"#
    );
}

// ---------------------------------------------------------------------------
// The two axes, in every combination
// ---------------------------------------------------------------------------

#[derive(Default)]
struct PairBoth {
    a: u32,
    b: u32,
}
structio::json_array!(PairBoth [ a, b ]);

struct PairJson {
    a: u32,
    b: u32,
}
structio::json_array!(write_only PairJson [ a, b ]);

#[derive(Default)]
struct PairBeveBoth {
    a: u32,
    b: u32,
}
structio::beve_array!(PairBeveBoth [ u32; a, b ]);

struct PairBeve {
    a: u32,
    b: u32,
}
structio::beve_array!(write_only PairBeve [ u32; a, b ]);

#[derive(Default)]
enum JsonMsgBoth {
    #[default]
    Idle,
    Config(Payload),
}
structio::json_tagged_enum!(JsonMsgBoth as tag "kind" { Idle, Config(_) });

enum JsonMsgHalf {
    Idle,
    Config(Payload),
}
structio::json_tagged_enum!(write_only JsonMsgHalf as tag "kind" { Idle, Config(_) });

#[derive(Default)]
enum BeveMsgBoth {
    #[default]
    Idle,
    Config(Payload),
}
structio::beve_tagged_enum!(BeveMsgBoth as "kebab-case" { Idle, Config(_) });

enum BeveMsgHalf {
    Idle,
    Config(Payload),
}
structio::beve_tagged_enum!(write_only BeveMsgHalf as "kebab-case" { Idle, Config(_) });

#[test]
fn every_one_format_macro_narrows_to_one_direction() {
    assert_eq!(
        to_string(&PairJson { a: 1, b: 2 }),
        to_string(&PairBoth { a: 1, b: 2 })
    );
    assert_eq!(
        to_beve(&PairBeve { a: 1, b: 2 }),
        to_beve(&PairBeveBoth { a: 1, b: 2 })
    );
    assert_eq!(
        to_string(&JsonMsgHalf::Config(Payload { mode: 1 })),
        to_string(&JsonMsgBoth::Config(Payload { mode: 1 }))
    );
    assert_eq!(to_string(&JsonMsgHalf::Idle), to_string(&JsonMsgBoth::Idle));
    // A case rule over variant names, on the narrowed side of a tagged enum.
    assert_eq!(
        to_beve(&BeveMsgHalf::Config(Payload { mode: 1 })),
        to_beve(&BeveMsgBoth::Config(Payload { mode: 1 }))
    );
    assert_eq!(to_beve(&BeveMsgHalf::Idle), to_beve(&BeveMsgBoth::Idle));
}

// ---------------------------------------------------------------------------
// Narrowed types inside other types
// ---------------------------------------------------------------------------

struct Inner {
    id: Register,
}
structio::object!(write_only Inner { id });

struct Outer {
    inner: Inner,
    many: Vec<Inner>,
    maybe: Option<Inner>,
    named: BTreeMap<String, Inner>,
}
structio::object!(write_only Outer { inner, many, maybe, named });

#[test]
fn a_narrowed_type_nests_in_containers_and_in_itself() {
    let o = Outer {
        inner: Inner { id: Register(1) },
        many: vec![Inner { id: Register(2) }, Inner { id: Register(3) }],
        maybe: None,
        named: BTreeMap::from([("k".to_string(), Inner { id: Register(4) })]),
    };
    assert_eq!(
        to_string(&o),
        r#"{"inner":{"id":1},"many":[{"id":2},{"id":3}],"maybe":null,"named":{"k":{"id":4}}}"#
    );
    // A container writes its elements through the same `Write` the narrowed
    // declaration generated, and BEVE has to count them the same way, so a
    // transcode of the whole tree is what checks the nesting.
    assert_eq!(
        structio::transcode::beve_to_json(&to_beve(&o)).unwrap(),
        to_string(&o)
    );
    assert_eq!(
        structio::transcode::beve_to_json(&to_beve_with::<SkipNull, _>(&o)).unwrap(),
        to_string_with::<SkipNull, _>(&o)
    );
}

// ---------------------------------------------------------------------------
// Generics beyond one type parameter
// ---------------------------------------------------------------------------

struct Slot<'a, T, const N: usize>
where
    T: Clone,
{
    label: &'a str,
    value: T,
}
structio::object!(write_only ['a, T: Clone + structio::Write, const N: usize] Slot<'a, T, N> {
    label, value
});

#[test]
fn a_lifetime_a_const_parameter_and_a_folded_bound() {
    let s: Slot<'_, u8, 4> = Slot {
        label: "x",
        value: 2,
    };
    assert_eq!(to_string(&s), r#"{"label":"x","value":2}"#);
    assert!(!to_beve(&s).is_empty());
}

// ---------------------------------------------------------------------------
// The derive, through every shape it claims
// ---------------------------------------------------------------------------

#[cfg(feature = "derive")]
#[derive(structio::Structio)]
#[structio(write_only, array, element = "f64")]
struct DerivedPoint {
    x: f64,
    y: f64,
}

#[cfg(feature = "derive")]
#[derive(structio::Structio)]
#[structio(write_only, rename_all = "snake_case")]
enum DerivedLevel {
    Info,
    #[structio(rename = "WARN")]
    Warning,
}

#[cfg(feature = "derive")]
#[derive(structio::Structio)]
#[structio(write_only, tag = "kind")]
enum DerivedMsg {
    Idle,
    Config(Payload),
}

#[cfg(feature = "derive")]
#[derive(structio::Structio)]
#[structio(write_only, json)]
struct DerivedJson<'a, T, const N: usize>
where
    T: Clone,
{
    label: &'a str,
    value: T,
}

#[cfg(feature = "derive")]
#[test]
fn the_derive_narrows_every_shape_it_claims() {
    // Positional, with the element type that makes BEVE store it as one
    // typed array: the same bytes as the macro twin declared the same way.
    assert_eq!(
        to_beve(&DerivedPoint { x: 1.5, y: -2.0 }),
        to_beve(&PointHalf { x: 1.5, y: -2.0 })
    );
    assert_eq!(to_string(&DerivedPoint { x: 1.5, y: -2.0 }), "[1.5,-2]");

    // A unit enum, including the BEVE string-array packing of a run.
    assert_eq!(to_string(&DerivedLevel::Warning), r#""WARN""#);
    assert_eq!(
        to_beve(&vec![DerivedLevel::Info, DerivedLevel::Warning]),
        to_beve(&vec![LevelHalf::Info, LevelHalf::Warning])
    );

    // An internally tagged enum.
    assert_eq!(
        to_string(&DerivedMsg::Config(Payload { mode: 2 })),
        r#"{"kind":"Config","mode":2}"#
    );
    assert_eq!(to_string(&DerivedMsg::Idle), to_string(&TaggedHalf::Idle));

    // One format, one direction, a lifetime, a const parameter and a `where`
    // clause folded onto the parameter it bounds.
    let d: DerivedJson<'_, u8, 4> = DerivedJson {
        label: "x",
        value: 2,
    };
    assert_eq!(to_string(&d), r#"{"label":"x","value":2}"#);
}