typwire 0.2.0

Typed data exchange for Typst plugins.
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
use serde::Deserializer;
use serde::de::{DeserializeSeed, EnumAccess, MapAccess, SeqAccess, VariantAccess, Visitor};

use crate::wire::{Error, Format, Typwire};

/// The default wire format: CBOR, via `cbor4ii`.
pub struct Cbor;

impl Format for Cbor {
    fn encode<T: Typwire>(value: &T) -> Result<Vec<u8>, Error> {
        cbor4ii::serde::to_vec(Vec::new(), value)
            .map_err(|error| Error::Serialization(error.to_string()))
    }

    fn decode<T: Typwire>(bytes: &[u8]) -> Result<T, Error> {
        // `T`'s derived `Deserialize` reads typed scalars (e.g. `deserialize_f64`),
        // which cbor4ii resolves strictly: a bare `f64` field rejects wire bytes
        // that used the narrower CBOR float widths Typst's encoder picks
        // canonically. `LenientDeserializer` redirects only the float-hinted
        // calls through cbor4ii's own width-tolerant `deserialize_any`, so this
        // stays a single parse pass.
        let reader = cbor4ii::core::utils::SliceReader::new(bytes);
        let mut inner = cbor4ii::serde::Deserializer::new(reader);
        T::deserialize(LenientDeserializer(&mut inner))
            .map_err(|error| Error::Deserialization(error.to_string()))
    }
}

/// A `Deserializer` wrapper that widens narrow CBOR floats.
///
/// cbor4ii's typed float decode (`deserialize_f32`/`deserialize_f64`) only
/// accepts the literal 4-/8-byte marker for the target width, rejecting the
/// narrower F16/F32 encodings Typst's `cbor.encode` (itself `ciborium`-based)
/// picks canonically. cbor4ii's own `deserialize_any` already handles every
/// width correctly, so this wrapper redirects just the float-hinted calls
/// there, passing the original visitor straight through unwrapped: serde's
/// built-in float visitors already implement both `visit_f32` and
/// `visit_f64` with widening, so no custom visitor is needed for that part.
///
/// Every other recursion point (`seq`, `map`, `enum`, `option`, ...) is
/// forwarded through a small local `Wrap` visitor that re-applies this same
/// wrapper to whatever nested `Deserializer`/`DeserializeSeed` cbor4ii's own
/// `SeqAccess`/`MapAccess`/`EnumAccess` hand back — those are cbor4ii's own
/// concrete types holding a direct reference to the inner deserializer, so
/// wrapping only the top-level call would not reach nested fields. Wrapping
/// the `DeserializeSeed` at each step (`LenientSeed`) is what makes the
/// leniency apply recursively.
struct LenientDeserializer<D>(D);

impl<'de, D: Deserializer<'de>> Deserializer<'de> for LenientDeserializer<D> {
    type Error = D::Error;

    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        // Wrapped like every other recursion point: a self-describing decode
        // (`Any`, `OneOfN`'s untagged buffering) can still reach a map or
        // seq whose nested fields are typed floats.
        self.0.deserialize_any(Wrap(visitor))
    }

    fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_any(visitor)
    }

    fn deserialize_f64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_any(visitor)
    }

    fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_option(Wrap(visitor))
    }

    fn deserialize_newtype_struct<V: Visitor<'de>>(
        self,
        name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        self.0.deserialize_newtype_struct(name, Wrap(visitor))
    }

    fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_seq(Wrap(visitor))
    }

    fn deserialize_tuple<V: Visitor<'de>>(
        self,
        len: usize,
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        self.0.deserialize_tuple(len, Wrap(visitor))
    }

    fn deserialize_tuple_struct<V: Visitor<'de>>(
        self,
        name: &'static str,
        len: usize,
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        self.0.deserialize_tuple_struct(name, len, Wrap(visitor))
    }

    fn deserialize_map<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_map(Wrap(visitor))
    }

    fn deserialize_struct<V: Visitor<'de>>(
        self,
        name: &'static str,
        fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        self.0.deserialize_struct(name, fields, Wrap(visitor))
    }

    fn deserialize_enum<V: Visitor<'de>>(
        self,
        name: &'static str,
        variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        self.0.deserialize_enum(name, variants, Wrap(visitor))
    }

    // Trivial forwards to cbor4ii's own type-hinted decode for everything
    // that isn't a float. Deliberately *not* `forward_to_deserialize_any!`:
    // that macro routes every one of these through `deserialize_any`, which
    // is wrong for `unit`/`unit_struct` specifically -- cbor4ii's
    // `deserialize_any` treats a CBOR null as an Option-shaped value (calls
    // `visit_none`), while the real `deserialize_unit` expects an empty-array
    // marker and calls `visit_unit`; these are different wire shapes that
    // happen to share a byte for other formats but not here.
    fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_bool(visitor)
    }

    fn deserialize_i8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_i8(visitor)
    }

    fn deserialize_i16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_i16(visitor)
    }

    fn deserialize_i32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_i32(visitor)
    }

    fn deserialize_i64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_i64(visitor)
    }

    fn deserialize_i128<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_i128(visitor)
    }

    fn deserialize_u8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_u8(visitor)
    }

    fn deserialize_u16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_u16(visitor)
    }

    fn deserialize_u32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_u32(visitor)
    }

    fn deserialize_u64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_u64(visitor)
    }

    fn deserialize_u128<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_u128(visitor)
    }

    fn deserialize_char<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_char(visitor)
    }

    fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_str(visitor)
    }

    fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_string(visitor)
    }

    fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_bytes(visitor)
    }

    fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_byte_buf(visitor)
    }

    fn deserialize_unit<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_unit(visitor)
    }

    fn deserialize_unit_struct<V: Visitor<'de>>(
        self,
        name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        self.0.deserialize_unit_struct(name, visitor)
    }

    fn deserialize_identifier<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_identifier(visitor)
    }

    fn deserialize_ignored_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.0.deserialize_ignored_any(visitor)
    }
}

/// A `Visitor` wrapper that re-applies [`LenientDeserializer`]/[`LenientSeed`]
/// to whatever nested deserializer, seq/map/enum access cbor4ii's own
/// visit_* callbacks hand back, then forwards to the real visitor.
///
/// Every scalar `visit_*` is forwarded explicitly too: `Visitor`'s defaults
/// would otherwise reject them (or route them through a different method
/// than the real visitor expects) once `deserialize_any` hands a `Wrap`
/// straight to one.
struct Wrap<V>(V);

impl<'de, V: Visitor<'de>> Visitor<'de> for Wrap<V> {
    type Value = V::Value;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.0.expecting(formatter)
    }

    fn visit_none<E: serde::de::Error>(self) -> Result<Self::Value, E> {
        self.0.visit_none()
    }

    fn visit_bool<E: serde::de::Error>(self, value: bool) -> Result<Self::Value, E> {
        self.0.visit_bool(value)
    }

    fn visit_i8<E: serde::de::Error>(self, value: i8) -> Result<Self::Value, E> {
        self.0.visit_i8(value)
    }

    fn visit_i16<E: serde::de::Error>(self, value: i16) -> Result<Self::Value, E> {
        self.0.visit_i16(value)
    }

    fn visit_i32<E: serde::de::Error>(self, value: i32) -> Result<Self::Value, E> {
        self.0.visit_i32(value)
    }

    fn visit_i64<E: serde::de::Error>(self, value: i64) -> Result<Self::Value, E> {
        self.0.visit_i64(value)
    }

    fn visit_i128<E: serde::de::Error>(self, value: i128) -> Result<Self::Value, E> {
        self.0.visit_i128(value)
    }

    fn visit_u8<E: serde::de::Error>(self, value: u8) -> Result<Self::Value, E> {
        self.0.visit_u8(value)
    }

    fn visit_u16<E: serde::de::Error>(self, value: u16) -> Result<Self::Value, E> {
        self.0.visit_u16(value)
    }

    fn visit_u32<E: serde::de::Error>(self, value: u32) -> Result<Self::Value, E> {
        self.0.visit_u32(value)
    }

    fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<Self::Value, E> {
        self.0.visit_u64(value)
    }

    fn visit_u128<E: serde::de::Error>(self, value: u128) -> Result<Self::Value, E> {
        self.0.visit_u128(value)
    }

    fn visit_f32<E: serde::de::Error>(self, value: f32) -> Result<Self::Value, E> {
        self.0.visit_f32(value)
    }

    fn visit_f64<E: serde::de::Error>(self, value: f64) -> Result<Self::Value, E> {
        self.0.visit_f64(value)
    }

    fn visit_char<E: serde::de::Error>(self, value: char) -> Result<Self::Value, E> {
        self.0.visit_char(value)
    }

    fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> {
        self.0.visit_str(value)
    }

    fn visit_borrowed_str<E: serde::de::Error>(self, value: &'de str) -> Result<Self::Value, E> {
        self.0.visit_borrowed_str(value)
    }

    fn visit_string<E: serde::de::Error>(self, value: String) -> Result<Self::Value, E> {
        self.0.visit_string(value)
    }

    fn visit_bytes<E: serde::de::Error>(self, value: &[u8]) -> Result<Self::Value, E> {
        self.0.visit_bytes(value)
    }

    fn visit_borrowed_bytes<E: serde::de::Error>(self, value: &'de [u8]) -> Result<Self::Value, E> {
        self.0.visit_borrowed_bytes(value)
    }

    fn visit_byte_buf<E: serde::de::Error>(self, value: Vec<u8>) -> Result<Self::Value, E> {
        self.0.visit_byte_buf(value)
    }

    fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
        self.0.visit_unit()
    }

    fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
        self.0.visit_some(LenientDeserializer(deserializer))
    }

    fn visit_newtype_struct<D: Deserializer<'de>>(
        self,
        deserializer: D,
    ) -> Result<Self::Value, D::Error> {
        self.0
            .visit_newtype_struct(LenientDeserializer(deserializer))
    }

    fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Self::Value, A::Error> {
        self.0.visit_seq(LenientSeqAccess(seq))
    }

    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
        self.0.visit_map(LenientMapAccess(map))
    }

    fn visit_enum<A: EnumAccess<'de>>(self, data: A) -> Result<Self::Value, A::Error> {
        self.0.visit_enum(LenientEnumAccess(data))
    }
}

/// A `DeserializeSeed` wrapper that wraps the deserializer it's given with
/// [`LenientDeserializer`] before delegating. This is what makes leniency
/// apply recursively through cbor4ii's own `SeqAccess`/`MapAccess`/
/// `EnumAccess`, which hold a direct reference to the concrete inner
/// deserializer rather than going back through any wrapper.
struct LenientSeed<S>(S);

impl<'de, S: DeserializeSeed<'de>> DeserializeSeed<'de> for LenientSeed<S> {
    type Value = S::Value;

    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
        self.0.deserialize(LenientDeserializer(deserializer))
    }
}

struct LenientSeqAccess<A>(A);

impl<'de, A: SeqAccess<'de>> SeqAccess<'de> for LenientSeqAccess<A> {
    type Error = A::Error;

    fn next_element_seed<S: DeserializeSeed<'de>>(
        &mut self,
        seed: S,
    ) -> Result<Option<S::Value>, Self::Error> {
        self.0.next_element_seed(LenientSeed(seed))
    }

    fn size_hint(&self) -> Option<usize> {
        self.0.size_hint()
    }
}

struct LenientMapAccess<A>(A);

impl<'de, A: MapAccess<'de>> MapAccess<'de> for LenientMapAccess<A> {
    fn next_key_seed<S: DeserializeSeed<'de>>(
        &mut self,
        seed: S,
    ) -> Result<Option<S::Value>, Self::Error> {
        self.0.next_key_seed(LenientSeed(seed))
    }

    fn next_value_seed<S: DeserializeSeed<'de>>(
        &mut self,
        seed: S,
    ) -> Result<S::Value, Self::Error> {
        self.0.next_value_seed(LenientSeed(seed))
    }

    fn size_hint(&self) -> Option<usize> {
        self.0.size_hint()
    }

    type Error = A::Error;
}

struct LenientEnumAccess<A>(A);

impl<'de, A: EnumAccess<'de>> EnumAccess<'de> for LenientEnumAccess<A> {
    type Error = A::Error;
    type Variant = LenientVariantAccess<A::Variant>;

    fn variant_seed<S: DeserializeSeed<'de>>(
        self,
        seed: S,
    ) -> Result<(S::Value, Self::Variant), Self::Error> {
        self.0
            .variant_seed(LenientSeed(seed))
            .map(|(value, variant)| (value, LenientVariantAccess(variant)))
    }
}

struct LenientVariantAccess<A>(A);

impl<'de, A: VariantAccess<'de>> VariantAccess<'de> for LenientVariantAccess<A> {
    type Error = A::Error;

    fn unit_variant(self) -> Result<(), Self::Error> {
        self.0.unit_variant()
    }

    fn newtype_variant_seed<S: DeserializeSeed<'de>>(
        self,
        seed: S,
    ) -> Result<S::Value, Self::Error> {
        self.0.newtype_variant_seed(LenientSeed(seed))
    }

    fn tuple_variant<V: Visitor<'de>>(
        self,
        len: usize,
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        self.0.tuple_variant(len, Wrap(visitor))
    }

    fn struct_variant<V: Visitor<'de>>(
        self,
        fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        self.0.struct_variant(fields, Wrap(visitor))
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use cbor4ii::core::Value;
    use serde::{Deserialize, Serialize};

    use super::*;
    use crate::wire::{decode, encode};

    #[test]
    fn bytes_use_a_byte_string_but_vec_uses_an_array() {
        let bytes = encode(&crate::Bytes::new(vec![1, 2])).unwrap();
        let vector = encode(&vec![1_u8, 2]).unwrap();

        assert!(matches!(
            cbor4ii::serde::from_slice::<Value>(&bytes).unwrap(),
            Value::Bytes(_)
        ));
        assert!(matches!(
            cbor4ii::serde::from_slice::<Value>(&vector).unwrap(),
            Value::Array(_)
        ));
    }

    // `wire::validate` was removed: its three checks (integer fits i64,
    // string-only map keys, no CBOR tags) were unreachable through any
    // type-safe path on either side of the boundary (Typst's own encoder
    // can't produce them; `Typwire` is only implemented for `i64` and
    // string-keyed maps). The following tests confirm cbor4ii's own decode
    // still fails closed on the same malformed inputs without that pass —
    // the safety argument for dropping it — just via a generic
    // `Error::Deserialization` rather than a dedicated variant.

    #[test]
    fn rejects_non_string_map_keys() {
        let value = BTreeMap::from([(1_i64, "value")]);
        let bytes = cbor4ii::serde::to_vec(Vec::new(), &value).unwrap();
        assert!(decode::<BTreeMap<String, String>>(&bytes).is_err());
    }

    #[test]
    fn rejects_out_of_range_integer() {
        // `u64` and `i128` aren't `Typwire` (Typst only has `i64`/`f64`), so
        // this goes through cbor4ii's serializer directly rather than the
        // public `encode`. cbor4ii's typed integer decode uses a checked
        // `TryFrom` internally, so it still fails closed without `validate`.
        let bytes = cbor4ii::serde::to_vec(Vec::new(), &(i64::MAX as u64 + 1)).unwrap();
        assert!(decode::<i64>(&bytes).is_err());
    }

    #[test]
    fn rejects_integer_too_large_for_any_supported_representation() {
        // Exceeds even i128 (cbor4ii encodes it as a CBOR bignum, tag 2, per
        // RFC 8949), so it fails while parsing rather than during a typed
        // integer conversion. Still rejected either way.
        let bytes = cbor4ii::serde::to_vec(Vec::new(), &u128::MAX).unwrap();
        assert!(decode::<i64>(&bytes).is_err());
    }

    #[test]
    fn rejects_cbor_tags() {
        use cbor4ii::core::enc::Encode;
        use cbor4ii::core::utils::BufWriter;

        // Tag 1 (epoch datetime) is not one of the bignum tags cbor4ii's
        // decode special-cases, so it hard-errors rather than silently
        // unwrapping to the tagged value.
        let mut writer = BufWriter::new(Vec::new());
        Value::Tag(1, Box::new(Value::Null))
            .encode(&mut writer)
            .unwrap();
        let bytes = writer.into_inner();

        assert!(decode::<()>(&bytes).is_err());
    }

    #[test]
    fn narrow_width_float_fields_round_trip() {
        // Regression test for the bug `LenientDeserializer` exists to fix:
        // cbor4ii's typed `deserialize_f64` rejects a narrower CBOR float
        // marker (F16/F32) even when the target is `f64`, which is exactly
        // what Typst's `cbor.encode` (itself `ciborium`-based) picks
        // canonically for a "round" value like `0.0`.
        #[derive(Debug, PartialEq, Serialize, Deserialize)]
        struct Struct {
            value: f64,
        }
        impl Typwire for Struct {}

        // Hand-crafted CBOR for `{"value": 0.0}` using a half-precision
        // (F16) float marker instead of the full 8-byte F64 marker.
        let bytes: &[u8] = &[
            0xA1, // map(1)
            0x65, b'v', b'a', b'l', b'u', b'e', // text(5) "value"
            0xF9, 0x00, 0x00, // float16(0.0)
        ];

        assert_eq!(decode::<Struct>(bytes).unwrap(), Struct { value: 0.0 });
    }

    #[test]
    fn narrow_width_float_inside_enum_variant_round_trips() {
        // `Color`/`Gradient` are internally tagged enums
        // (`#[serde(tag = "typwire-type")]`) with `f64`-backed fields inside
        // their variants (`Ratio`, here), so this exercises
        // `deserialize_enum`'s wrapping specifically, not just plain struct
        // fields.
        let black = crate::Color::Luma(crate::Luma::new(
            crate::Ratio::new(0.0),
            crate::Ratio::new(1.0),
        ));
        let bytes = encode(&black).unwrap();
        assert_eq!(decode::<crate::Color>(&bytes).unwrap(), black);
    }

    #[test]
    fn unit_round_trips() {
        // Regression test for a real bug caught while adding coverage: an
        // earlier version of `LenientDeserializer` routed `unit`/
        // `unit_struct` through `deserialize_any` (via
        // `forward_to_deserialize_any!`), but cbor4ii's `deserialize_any`
        // treats a CBOR null as Option-shaped (calls `visit_none`), while
        // `()`'s real wire shape is a zero-length array and needs the
        // strict `deserialize_unit` (calls `visit_unit`). Routing through
        // `deserialize_any` made every `()` decode fail with "invalid type:
        // Option value, expected unit".
        let bytes = encode(&()).unwrap();
        assert_eq!(decode::<()>(&bytes).unwrap(), ());
    }

    #[test]
    fn unit_is_not_the_same_wire_shape_as_a_cbor_null() {
        // `()` is a zero-length array, not `none`'s CBOR null -- pinning
        // down the distinction the previous test's regression was about.
        let bytes = cbor4ii::serde::to_vec(Vec::new(), &Option::<i64>::None).unwrap();
        assert!(decode::<()>(&bytes).is_err());
    }
}