tinyklv 0.1.0

The simplest Key-Length-Value (KLV) framework in Rust
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
//! Tests for `default(typ=...)` container attribute and `default` / `default = <expr>` field attributes
//!
//! Covers container-level type defaults (eliminating per-field dec/enc),
//! field-level `default = <expr>` values used when a key is absent,
//! field-level bare `default` which calls `Default::default()` on the field
//! type, override when the key is present, and non-KLV fields falling back
//! to `Default::default()`.
use super::types::*;
use tinyklv::dec::binary as decb;
use tinyklv::enc::binary as encb;
use tinyklv::prelude::*;

#[derive(Klv, Debug, PartialEq)]
#[klv(
    stream = &[u8],
    key(dec = decb::u8, enc = encb::u8),
    len(dec = decb::u8_as_usize, enc = encb::u8_from_usize),
    default(typ = Color,    dec = Color::decode_value,    enc = Color::encode_value),
    default(typ = Priority, dec = Priority::decode_value, enc = Priority::encode_value),
)]
struct DefaultTyped {
    #[klv(key = 0x01)]
    /// No per-field dec/enc - resolved from container defaults
    color: Color,

    #[klv(key = 0x02)]
    /// No per-field dec/enc - resolved from container defaults
    priority: Priority,

    #[klv(
        key = 0x03,
        dec = Velocity::decode_value,
        enc = Velocity::encode_value,
    )]
    /// Explicit dec/enc still works alongside container defaults
    velocity: Velocity,
}

#[derive(Klv, Debug, PartialEq)]
#[klv(
    stream = &[u8],
    key(dec = decb::u8, enc = encb::u8),
    len(dec = decb::u8_as_usize, enc = encb::u8_from_usize),
)]
struct DefaultExprColor {
    #[klv(
        key = 0x01,
        dec = Color::decode_value,
        enc = Color::encode_value,
        default = Color::Red,
    )]
    color: Color,
}

#[derive(Klv, Debug, PartialEq)]
#[klv(
    stream = &[u8],
    key(dec = decb::u8, enc = encb::u8),
    len(dec = decb::u8_as_usize, enc = encb::u8_from_usize),
)]
struct DefaultExprTimestamp {
    #[klv(
        key = 0x01,
        dec = Timestamp::decode_value,
        enc = Timestamp::encode_value,
        default = Timestamp { seconds: 0, nanos: 0 }
    )]
    timestamp: Timestamp,
}

#[derive(Klv, Debug, PartialEq)]
#[klv(
    stream = &[u8],
    key(dec = decb::u8, enc = encb::u8),
    len(dec = decb::u8_as_usize, enc = encb::u8_from_usize),
    allow_unimplemented_encode,
)]
struct WithNonKlvField {
    #[klv(
        key = 0x01,
        dec = Color::decode_value,
        enc = Color::encode_value,
    )]
    color: Color,
    // No #[klv] - should resolve to Default::default() = 0
    counter: u32,
}

#[derive(Debug, Clone, Copy, PartialEq, Default)]
enum Flavor {
    #[default]
    Vanilla,
    Chocolate,
    Strawberry,
    Mint,
}
impl tinyklv::DecodeValue<&[u8]> for Flavor {
    fn decode_value(input: &mut &[u8]) -> tinyklv::Result<Self> {
        let v = decb::u8(input)?;
        match v {
            0 => Ok(Flavor::Vanilla),
            1 => Ok(Flavor::Chocolate),
            2 => Ok(Flavor::Strawberry),
            3 => Ok(Flavor::Mint),
            _ => Err(winnow::error::ParserError::from_input(input)),
        }
    }
}
impl tinyklv::EncodeValue<Vec<u8>> for Flavor {
    fn encode_value(&self) -> Vec<u8> {
        let v = match self {
            Flavor::Vanilla => 0_u8,
            Flavor::Chocolate => 1,
            Flavor::Strawberry => 2,
            Flavor::Mint => 3,
        };
        encb::u8(v)
    }
}

#[derive(Debug, Clone, PartialEq)]
/// Custom struct with a non-trivial `Default` impl - distinguishes bare
/// `default` from an inline `default = <expr>` with the same literal values
pub struct Calibration {
    pub gain: f32,
    pub offset: i16,
}
impl Default for Calibration {
    fn default() -> Self {
        Calibration {
            gain: 1.0,
            offset: 0,
        }
    }
}
impl tinyklv::DecodeValue<&[u8]> for Calibration {
    fn decode_value(input: &mut &[u8]) -> tinyklv::Result<Self> {
        let gain = decb::be_f32(input)?;
        let offset = decb::be_i16(input)?;
        Ok(Calibration { gain, offset })
    }
}
impl tinyklv::EncodeValue<Vec<u8>> for Calibration {
    fn encode_value(&self) -> Vec<u8> {
        let mut v = encb::be_f32(self.gain);
        v.extend(encb::be_i16(self.offset));
        v
    }
}

#[derive(Klv, Debug, PartialEq)]
#[klv(
    stream = &[u8],
    key(dec = decb::u8, enc = encb::u8),
    len(dec = decb::u8_as_usize, enc = encb::u8_from_usize),
)]
struct DefaultBareU32 {
    #[klv(
        key = 0x01,
        dec = decb::be_u32,
        enc = *encb::be_u32,
        default,
    )]
    counter: u32,
}

#[derive(Klv, Debug, PartialEq)]
#[klv(
    stream = &[u8],
    key(dec = decb::u8, enc = encb::u8),
    len(dec = decb::u8_as_usize, enc = encb::u8_from_usize),
)]
struct DefaultBareStruct {
    #[klv(
        key = 0x01,
        dec = Calibration::decode_value,
        enc = Calibration::encode_value,
        default
    )]
    cal: Calibration,
}

#[derive(Klv, Debug, PartialEq)]
#[klv(
    stream = &[u8],
    key(dec = decb::u8, enc = encb::u8),
    len(dec = decb::u8_as_usize, enc = encb::u8_from_usize),
)]
struct DefaultBareEnum {
    #[klv(
        key = 0x01,
        dec = Flavor::decode_value,
        enc = Flavor::encode_value,
        default
    )]
    flavor: Flavor,
}

#[derive(Klv, Debug, PartialEq)]
#[klv(
    stream = &[u8],
    key(dec = decb::u8, enc = encb::u8),
    len(dec = decb::u8_as_usize, enc = encb::u8_from_usize),
)]
struct DefaultBareAndExpr {
    #[klv(
        key = 0x01,
        dec = Flavor::decode_value,
        enc = Flavor::encode_value,
        default
    )]
    flavor: Flavor,
    #[klv(
        key = 0x02,
        dec = Calibration::decode_value,
        enc = Calibration::encode_value,
        default = Calibration { gain: 2.5, offset: -7 }
    )]
    cal: Calibration,
}

#[derive(Klv, Debug, PartialEq)]
#[klv(
    stream = &[u8],
    key(dec = decb::u8, enc = encb::u8),
    len(dec = decb::u8_as_usize, enc = encb::u8_from_usize),
)]
struct DefaultBareOptionWrapped {
    #[klv(
        key = 0x01,
        dec = Flavor::decode_value,
        enc = Flavor::encode_value,
        default
    )]
    flavor: Option<Flavor>,
}

fn tlv(key: u8, value: Vec<u8>) -> Vec<u8> {
    let mut out = vec![key, value.len() as u8];
    out.extend(value);
    out
}

#[test]
/// Tests that `default(typ = ...)` container attributes resolve `dec`/`enc` for fields that omit them.
fn default_type_color_and_priority() {
    let original = DefaultTyped {
        color: Color::Alpha,
        priority: Priority::Critical,
        velocity: Velocity {
            dx: 10,
            dy: -20,
            dz: 5,
        },
    };
    // Decode from hand-built stream
    let mut stream: Vec<u8> = Vec::new();
    stream.extend(tlv(0x01, original.color.encode_value()));
    stream.extend(tlv(0x02, original.priority.encode_value()));
    stream.extend(tlv(0x03, original.velocity.encode_value()));
    let decoded = DefaultTyped::decode_value(&mut stream.as_slice()).unwrap();
    assert_eq!(decoded, original, "container-default decode should match");
}

#[test]
/// Verifies encode/decode roundtrip when most fields rely on container-level `default(typ = ...)` codecs.
fn default_type_roundtrip() {
    let original = DefaultTyped {
        color: Color::Red,
        priority: Priority::Medium,
        velocity: Velocity {
            dx: 0,
            dy: 0,
            dz: -1,
        },
    };
    let encoded = original.encode_value();
    let decoded = DefaultTyped::decode_value(&mut encoded.as_slice()).unwrap();
    assert_eq!(decoded, original, "roundtrip via container-level defaults");
}

#[test]
/// Tests that `default = Color::Red` supplies the fallback when the field's key is absent from the stream.
fn default_expr_color_enum_absent() {
    // Stream has no key 0x01 - `default = Color::Red` should be used
    let result = DefaultExprColor::decode_value(&mut [].as_slice()).unwrap();
    assert_eq!(
        result.color,
        Color::Red,
        "absent key should yield `default = <expr>` value"
    );
}

#[test]
/// Tests that a present key overrides the `default = Color::Red` fallback at decode time.
fn default_expr_color_enum_present() {
    // Stream has key 0x01 = Color::Blue - decoded value overrides default expression
    let stream = tlv(0x01, Color::Blue.encode_value());
    let result = DefaultExprColor::decode_value(&mut stream.as_slice()).unwrap();
    assert_eq!(
        result.color,
        Color::Blue,
        "present key should yield decoded value"
    );
}

#[test]
/// Tests that a struct-valued `default = Timestamp { ... }` fallback is applied when the key is absent.
fn default_expr_timestamp_struct_absent() {
    let zero = Timestamp {
        seconds: 0,
        nanos: 0,
    };
    let result = DefaultExprTimestamp::decode_value(&mut [].as_slice()).unwrap();
    assert_eq!(
        result.timestamp, zero,
        "absent key should yield `default = <expr>` Timestamp"
    );
}

#[test]
/// Tests that decoding a present `Timestamp` key overrides the struct-valued `default = <expr>` fallback.
fn default_expr_timestamp_struct_present() {
    let ts = Timestamp {
        seconds: 1_700_000_000,
        nanos: 12_345,
    };
    let stream = tlv(0x01, ts.encode_value());
    let result = DefaultExprTimestamp::decode_value(&mut stream.as_slice()).unwrap();
    assert_eq!(
        result.timestamp, ts,
        "present key should yield decoded Timestamp"
    );
}

#[test]
/// Verifies explicitly that the decoded value (`Color::Blue`) wins over the `default = Color::Red` fallback when both are available.
fn default_expr_overridden_when_present() {
    let stream = tlv(0x01, Color::Blue.encode_value());
    let result = DefaultExprColor::decode_value(&mut stream.as_slice()).unwrap();
    assert_ne!(
        result.color,
        Color::Red,
        "`default = <expr>` should be overridden by decoded value"
    );
    assert_eq!(
        result.color,
        Color::Blue,
        "decoded Color::Blue must win over Color::Red default"
    );
}

#[test]
/// Tests bare `default` on a primitive field - absent key yields `u32::default() == 0`.
fn default_bare_primitive_u32_absent() {
    let result = DefaultBareU32::decode_value(&mut [].as_slice()).unwrap();
    assert_eq!(
        result.counter, 0,
        "bare `default` on u32 must yield u32::default() == 0"
    );
}

#[test]
/// Tests bare `default` on a primitive field - present key overrides the `Default::default()` fallback.
fn default_bare_primitive_u32_present() {
    let stream = tlv(0x01, encb::be_u32(42));
    let result = DefaultBareU32::decode_value(&mut stream.as_slice()).unwrap();
    assert_eq!(
        result.counter, 42,
        "present key should override bare `default`"
    );
}

#[test]
/// Tests bare `default` on a custom struct - confirms it actually calls the type's `Default` impl.
///
/// `Calibration::default()` is `{ gain: 1.0, offset: 0 }`, distinct from the
/// struct's zero-initialized form, proving the codegen dispatches through the
/// `Default` trait rather than bit-zero memory.
fn default_bare_custom_struct_absent() {
    let result = DefaultBareStruct::decode_value(&mut [].as_slice()).unwrap();
    assert_eq!(
        result.cal,
        Calibration::default(),
        "bare `default` must call `<Calibration as Default>::default()`"
    );
    assert_eq!(result.cal.gain, 1.0);
    assert_eq!(result.cal.offset, 0);
}

#[test]
/// Tests bare `default` on a custom struct when the key is present - decoded value wins.
fn default_bare_custom_struct_present() {
    let cal = Calibration {
        gain: 3.15,
        offset: -42,
    };
    let stream = tlv(0x01, cal.encode_value());
    let result = DefaultBareStruct::decode_value(&mut stream.as_slice()).unwrap();
    assert_eq!(result.cal, cal, "present key overrides bare `default`");
}

#[test]
/// Tests bare `default` on an enum with `#[derive(Default)]` and `#[default]` variant.
fn default_bare_enum_with_derive_default_absent() {
    let result = DefaultBareEnum::decode_value(&mut [].as_slice()).unwrap();
    assert_eq!(
        result.flavor,
        Flavor::Vanilla,
        "bare `default` must yield the `#[default]` variant"
    );
}

#[test]
/// Tests a single struct that mixes bare `default` and `default = <expr>` on different fields.
fn default_bare_and_expr_mixed_absent() {
    let result = DefaultBareAndExpr::decode_value(&mut [].as_slice()).unwrap();
    assert_eq!(
        result.flavor,
        Flavor::Vanilla,
        "bare `default` field -> Default::default()"
    );
    assert_eq!(
        result.cal,
        Calibration {
            gain: 2.5,
            offset: -7
        },
        "`default = <expr>` field -> inlined expression"
    );
}

#[test]
/// Tests that bare `default` on an `Option<T>` field unwraps through
/// `unwrap_option_type` and calls `<T>::default()` (not `<Option<T>>::default()`).
fn default_bare_option_wrapped_absent() {
    let result = DefaultBareOptionWrapped::decode_value(&mut [].as_slice()).unwrap();
    assert_eq!(
        result.flavor,
        Some(Flavor::Vanilla),
        "Option<Flavor> with bare `default` should be `Some(Flavor::default())`"
    );
}

#[test]
/// Tests that a struct field without `#[klv(...)]` resolves to `Default::default()` while other fields decode normally.
fn non_klv_field_default() {
    let stream = tlv(0x01, Color::Green.encode_value());
    let result = WithNonKlvField::decode_value(&mut stream.as_slice()).unwrap();
    assert_eq!(
        result.color,
        Color::Green,
        "klv field should decode normally"
    );
    assert_eq!(
        result.counter, 0,
        "non-KLV field should be Default::default() = 0"
    );
}

#[test]
/// Tests that unknown keys in the stream do not perturb the default-valued non-KLV field.
fn non_klv_field_unaffected_by_unknown_keys() {
    let mut stream: Vec<u8> = tlv(0x01, Color::Alpha.encode_value());
    stream.extend_from_slice(&[0xFF, 0x02, 0xAB, 0xCD]);

    let result = WithNonKlvField::decode_value(&mut stream.as_slice()).unwrap();
    assert_eq!(result.color, Color::Alpha);
    assert_eq!(
        result.counter, 0,
        "non-KLV counter must not be affected by unknown keys"
    );
}