world-id-primitives 0.16.0

Contains the raw base primitives (without implementations) for the World ID Protocol.
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
//! Serde helpers shared across the protocol.
//!
//! The `hex_*` modules encode numeric API values as strings:
//! - serialization always emits `0x`-prefixed hex strings;
//! - deserialization accepts either decimal (no prefix) or hex (`0x`/`0X` prefix).
//!
//! [`deserialize_present`] tells an absent field apart from an explicit null, and [`cbor`] holds
//! strict deserializers for fields of CBOR messages.

#![allow(clippy::missing_errors_doc)]

use ruint::aliases::U256;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};

fn parse_radix_and_digits(input: &str) -> Result<(u64, &str), String> {
    let s = input.trim();
    if s.is_empty() {
        return Err("empty numeric string".to_string());
    }

    if let Some(rest) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
        if rest.is_empty() {
            return Err("missing digits after 0x prefix".to_string());
        }
        Ok((16, rest))
    } else {
        Ok((10, s))
    }
}

/// Serialize as `0x`-prefixed hex and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u256 {
    use super::*;

    /// Serialize a `U256` as a `0x`-prefixed hex string.
    pub fn serialize<S>(value: &U256, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&format!("{value:#x}"))
    }

    /// Deserialize a `U256` from a numeric string.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<U256, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
        U256::from_str_radix(digits, radix)
            .map_err(|e| D::Error::custom(format!("invalid numeric U256: {e}")))
    }
}

/// Serialize as optional `0x`-prefixed hex and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u256_opt {
    use super::*;

    /// Serialize an `Option<U256>` as an optional `0x`-prefixed hex string.
    pub fn serialize<S>(value: &Option<U256>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Some(v) => serializer.serialize_some(&format!("{v:#x}")),
            None => serializer.serialize_none(),
        }
    }

    /// Deserialize an `Option<U256>` from an optional numeric string.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<U256>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let opt: Option<String> = Option::deserialize(deserializer)?;
        match opt {
            Some(s) => {
                let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
                let v = U256::from_str_radix(digits, radix)
                    .map_err(|e| D::Error::custom(format!("invalid numeric U256: {e}")))?;
                Ok(Some(v))
            }
            None => Ok(None),
        }
    }
}

/// Serialize as `0x`-prefixed hex strings and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u256_vec {
    use super::*;

    /// Serialize a `Vec<U256>` as a vector of `0x`-prefixed hex strings.
    pub fn serialize<S>(values: &[U256], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let hex_strings: Vec<String> = values.iter().map(|v| format!("{v:#x}")).collect();
        hex_strings.serialize(serializer)
    }

    /// Deserialize a `Vec<U256>` from a vector of numeric strings.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<U256>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let strings: Vec<String> = Vec::deserialize(deserializer)?;
        strings
            .into_iter()
            .map(|s| {
                let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
                U256::from_str_radix(digits, radix)
                    .map_err(|e| D::Error::custom(format!("invalid numeric U256: {e}")))
            })
            .collect()
    }
}

/// Serialize as optional `0x`-prefixed hex strings and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u256_opt_vec {
    use super::*;

    /// Serialize a `Vec<Option<U256>>` as a vector of optional `0x`-prefixed hex strings.
    pub fn serialize<S>(values: &[Option<U256>], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let hex_strings: Vec<Option<String>> = values
            .iter()
            .map(|value| value.as_ref().map(|v| format!("{v:#x}")))
            .collect();
        hex_strings.serialize(serializer)
    }

    /// Deserialize a `Vec<Option<U256>>` from a vector of optional numeric strings.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<Option<U256>>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let strings: Vec<Option<String>> = Vec::deserialize(deserializer)?;
        strings
            .into_iter()
            .map(|value| match value {
                Some(s) => {
                    let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
                    U256::from_str_radix(digits, radix)
                        .map(Some)
                        .map_err(|e| D::Error::custom(format!("invalid numeric U256: {e}")))
                }
                None => Ok(None),
            })
            .collect()
    }
}

/// Serialize as `0x`-prefixed hex and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u64 {
    use super::*;

    /// Serialize a `u64` as a `0x`-prefixed hex string.
    pub fn serialize<S>(value: &u64, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&format!("{value:#x}"))
    }

    /// Deserialize a `u64` from a numeric string.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<u64, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
        u64::from_str_radix(digits, radix as u32)
            .map_err(|e| D::Error::custom(format!("invalid numeric u64: {e}")))
    }
}

/// Serialize as `0x`-prefixed hex and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u32 {
    use super::*;

    /// Serialize a `u32` as a `0x`-prefixed hex string.
    pub fn serialize<S>(value: &u32, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&format!("{value:#x}"))
    }

    /// Deserialize a `u32` from a numeric string.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<u32, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
        u32::from_str_radix(digits, radix as u32)
            .map_err(|e| D::Error::custom(format!("invalid numeric u32: {e}")))
    }
}

/// Serialize as optional `0x`-prefixed hex and deserialize from decimal or `0x`/`0X` hex.
pub mod hex_u32_opt {
    use super::*;

    /// Serialize an `Option<u32>` as an optional `0x`-prefixed hex string.
    pub fn serialize<S>(value: &Option<u32>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Some(v) => serializer.serialize_some(&format!("{v:#x}")),
            None => serializer.serialize_none(),
        }
    }

    /// Deserialize an `Option<u32>` from an optional numeric string.
    ///
    /// `0x`/`0X`-prefixed values are parsed as hex, while unprefixed values are parsed as decimal.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let opt: Option<String> = Option::deserialize(deserializer)?;
        match opt {
            Some(s) => {
                let (radix, digits) = parse_radix_and_digits(&s).map_err(D::Error::custom)?;
                let v = u32::from_str_radix(digits, radix as u32)
                    .map_err(|e| D::Error::custom(format!("invalid numeric u32: {e}")))?;
                Ok(Some(v))
            }
            None => Ok(None),
        }
    }
}

/// Serialize an `alloy_primitives::Signature` as a `0x`-prefixed hex string (65 bytes: `r || s || v`).
pub mod hex_signature {
    use alloy_primitives::Signature;
    use serde::{Deserialize, Deserializer, Serializer, de::Error as _};
    use std::str::FromStr;

    /// Serialize a `Signature` as a `0x`-prefixed hex string.
    pub fn serialize<S>(sig: &Signature, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&sig.to_string())
    }

    /// Deserialize a `Signature` from a `0x`-prefixed hex string.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Signature, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Signature::from_str(&s).map_err(D::Error::custom)
    }
}

/// Serializes an optional byte array as a `0x`-prefixed hex string if using a human-readable serializer
pub mod hex_bytes_opt {
    use serde::{Deserialize, Deserializer, Serializer, de::Error as _};

    /// Serialize a byte array.
    ///
    /// - For human-readable serializers, this is emitted as a `0x`-prefixed hex string.
    /// - For non-human-readable serializers, this is emitted as raw bytes.
    pub fn serialize<S>(v: &Option<Vec<u8>>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match v {
            Some(v) => {
                if serializer.is_human_readable() {
                    serializer.serialize_some(&format!("0x{}", hex::encode(v)))
                } else {
                    serializer.serialize_some(v)
                }
            }
            None => serializer.serialize_none(),
        }
    }

    /// Deserialize a byte array.
    ///
    /// - For human-readable serializers, this is expected as a `0x`-prefixed hex string.
    /// - For non-human-readable serializers, this is expected as raw bytes.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Vec<u8>>, D::Error>
    where
        D: Deserializer<'de>,
    {
        if deserializer.is_human_readable() {
            let s = Option::<String>::deserialize(deserializer)?;
            s.map(|s| {
                let s = s
                    .strip_prefix("0x")
                    .or_else(|| s.strip_prefix("0X"))
                    .unwrap_or(&s);
                hex::decode(s).map_err(D::Error::custom)
            })
            .transpose()
        } else {
            Option::<Vec<u8>>::deserialize(deserializer)
        }
    }
}

/// Deserializes an optional field that, when present, must hold a `T`.
///
/// Use it on an `Option<T>` field together with `#[serde(default)]`: an absent field becomes
/// `None`, and a present value is parsed as `T` and wrapped in `Some`. Unlike the plain
/// `Option<T>` impl, an explicit null is not read as `None`; it is passed to `T`, which rejects it
/// unless `T` itself accepts null, as a dynamic value type does.
///
/// # Examples
///
/// ```
/// use serde::Deserialize;
/// use world_id_primitives::serde_utils::deserialize_present;
///
/// #[derive(Debug, PartialEq, Deserialize)]
/// struct Params {
///     #[serde(default, deserialize_with = "deserialize_present")]
///     name: Option<String>,
/// }
///
/// let absent: Params = serde_json::from_str("{}").unwrap();
/// assert_eq!(absent.name, None);
/// let present: Params = serde_json::from_str(r#"{"name": "phone"}"#).unwrap();
/// assert_eq!(present.name.as_deref(), Some("phone"));
/// assert!(serde_json::from_str::<Params>(r#"{"name": null}"#).is_err());
/// ```
pub fn deserialize_present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    T::deserialize(deserializer).map(Some)
}

/// Strict deserializers for CBOR fields that a protocol defines by their major type.
///
/// Serde's own impls accept other CBOR encodings of the same value: `Vec<u8>` and byte arrays also
/// read an array of integers, integers also read bignums (tags 2 and 3), and most impls skip CBOR
/// tags. These deserializers accept only the defined major type, without a tag.
///
/// # Examples
///
/// ```
/// use serde::Deserialize;
/// use world_id_primitives::{authenticator_message::Value, serde_utils::cbor};
///
/// #[derive(Debug, Deserialize)]
/// struct Slot {
///     #[serde(deserialize_with = "cbor::deserialize_byte_array")]
///     key: [u8; 2],
///     #[serde(deserialize_with = "cbor::deserialize_unsigned")]
///     index: u32,
/// }
///
/// let slot = |key: Value, index: Value| {
///     let value = Value::Map(vec![("key".into(), key), ("index".into(), index)]);
///     let mut bytes = Vec::new();
///     ciborium::into_writer(&value, &mut bytes).unwrap();
///     bytes
/// };
///
/// let bytes = slot(Value::Bytes(vec![1, 2]), 7.into());
/// let valid: Slot = ciborium::from_reader(bytes.as_slice()).unwrap();
/// assert_eq!((valid.key, valid.index), ([1, 2], 7));
///
/// let integers = Value::Array(vec![1.into(), 2.into()]);
/// let bytes = slot(integers, 7.into());
/// assert!(ciborium::from_reader::<Slot, _>(bytes.as_slice()).is_err());
/// let tagged = Value::Tag(0, Box::new(7.into()));
/// let bytes = slot(Value::Bytes(vec![1, 2]), tagged);
/// assert!(ciborium::from_reader::<Slot, _>(bytes.as_slice()).is_err());
/// ```
pub mod cbor {
    use std::fmt;

    use serde::{
        Deserializer,
        de::{Error as _, Visitor},
    };

    /// Deserializes a CBOR byte string.
    ///
    /// A rejected data item is never collected into a buffer of this function, so a caller that
    /// moves the result straight into a zeroizing container keeps no other copy of a secret.
    /// The deserializer's own read buffers are outside its control.
    ///
    /// # Errors
    ///
    /// Fails for any other CBOR data item, including an array of integers and a tagged byte
    /// string.
    pub fn deserialize_byte_string<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Vec<u8>, D::Error> {
        struct ByteStringVisitor;

        impl Visitor<'_> for ByteStringVisitor {
            type Value = Vec<u8>;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a CBOR byte string")
            }

            fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Vec<u8>, E> {
                Ok(bytes.to_vec())
            }

            fn visit_byte_buf<E>(self, bytes: Vec<u8>) -> Result<Vec<u8>, E> {
                Ok(bytes)
            }
        }

        // Ciborium skips tags when asked for bytes, but `deserialize_any` passes a tag to
        // `visit_enum`, which rejects it.
        deserializer.deserialize_any(ByteStringVisitor)
    }

    /// Deserializes a CBOR byte string of exactly `N` bytes.
    ///
    /// # Errors
    ///
    /// Fails like [`deserialize_byte_string`], and if the byte string has another length.
    pub fn deserialize_byte_array<'de, D: Deserializer<'de>, const N: usize>(
        deserializer: D,
    ) -> Result<[u8; N], D::Error> {
        deserialize_byte_string(deserializer)?
            .try_into()
            .map_err(|bytes: Vec<u8>| {
                D::Error::custom(format!(
                    "expected a CBOR byte string of {N} bytes, got {}",
                    bytes.len()
                ))
            })
    }

    /// Deserializes a CBOR unsigned integer that fits in `T`.
    ///
    /// # Errors
    ///
    /// Fails for any other CBOR data item, including negative integers, floats, bignums and
    /// other tagged integers, and if the integer does not fit in `T`.
    pub fn deserialize_unsigned<'de, D, T>(deserializer: D) -> Result<T, D::Error>
    where
        D: Deserializer<'de>,
        T: TryFrom<u64>,
    {
        // A `Value` would hide bignums as plain integers. Visited directly, a bignum arrives as a
        // `u128`, which this visitor rejects.
        struct UnsignedVisitor;

        impl Visitor<'_> for UnsignedVisitor {
            type Value = u64;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a CBOR unsigned integer")
            }

            fn visit_u64<E>(self, value: u64) -> Result<u64, E> {
                Ok(value)
            }
        }

        let value = deserializer.deserialize_any(UnsignedVisitor)?;
        T::try_from(value).map_err(|_| D::Error::custom("unsigned integer exceeds the field width"))
    }
}

#[cfg(test)]
mod tests {
    use ciborium::Value;
    use serde::{Deserialize, Serialize};
    use test_case::test_case;

    use super::*;

    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    struct Test {
        #[serde(with = "hex_u256")]
        u256_val: U256,
        #[serde(with = "hex_u64")]
        u64_val: u64,
    }

    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    struct TestOptVec {
        #[serde(with = "hex_u256_opt_vec")]
        values: Vec<Option<U256>>,
    }

    #[test]
    fn test_hex_roundtrip() {
        let original = Test {
            u256_val: U256::from(0xdead_beef_u64),
            u64_val: 42,
        };
        let json = serde_json::to_string(&original).unwrap();
        assert!(json.contains("0xdeadbeef"));
        assert!(json.contains("0x2a"));

        let parsed: Test = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, original);
    }

    #[test]
    fn test_deserialize_decimal_without_prefix() {
        let parsed: Test = serde_json::from_str(r#"{"u256_val":"42","u64_val":"42"}"#).unwrap();
        assert_eq!(parsed.u256_val, U256::from(42));
        assert_eq!(parsed.u64_val, 42);
    }

    #[test]
    fn test_deserialize_hex_with_prefix() {
        let parsed: Test = serde_json::from_str(r#"{"u256_val":"0x2a","u64_val":"0x2a"}"#).unwrap();
        assert_eq!(parsed.u256_val, U256::from(42));
        assert_eq!(parsed.u64_val, 42);
    }

    #[test]
    fn test_unprefixed_hex_like_value_is_rejected() {
        let err = serde_json::from_str::<Test>(r#"{"u256_val":"ff","u64_val":"255"}"#).unwrap_err();
        assert!(err.to_string().contains("invalid numeric U256"));
    }

    #[test]
    fn test_u256_opt_vec_roundtrip() {
        let original = TestOptVec {
            values: vec![Some(U256::from(1)), None, Some(U256::from(255))],
        };
        let json = serde_json::to_string(&original).unwrap();
        assert_eq!(json, r#"{"values":["0x1",null,"0xff"]}"#);

        let parsed: TestOptVec = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, original);
    }

    #[test]
    fn test_u256_opt_vec_deserialize_decimal_and_null() {
        let parsed: TestOptVec = serde_json::from_str(r#"{"values":["42",null,"0x2a"]}"#).unwrap();
        assert_eq!(
            parsed.values,
            vec![Some(U256::from(42)), None, Some(U256::from(42))]
        );
    }

    #[test]
    fn test_hex_signature_roundtrip() {
        use alloy_primitives::Signature;

        #[derive(Debug, PartialEq, Serialize, Deserialize)]
        struct S {
            #[serde(with = "hex_signature")]
            sig: Signature,
        }

        let sig = Signature::new(U256::from(1), U256::from(2), false);
        let s = S { sig };

        let json = serde_json::to_string(&s).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let hex_str = value["sig"].as_str().expect("signature should be a string");
        assert!(hex_str.starts_with("0x"), "should be 0x-prefixed");
        assert_eq!(hex_str.len(), 132, "0x + 130 hex chars (65 bytes)");

        let parsed: S = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, s);
    }

    /// Decodes `T` from the CBOR encoding of `value`.
    fn from_cbor<T: serde::de::DeserializeOwned>(
        value: &Value,
    ) -> Result<T, ciborium::de::Error<std::io::Error>> {
        let mut encoded = Vec::new();
        ciborium::into_writer(value, &mut encoded).unwrap();
        ciborium::from_reader(encoded.as_slice())
    }

    #[derive(Debug, Deserialize)]
    struct ByteString(#[serde(deserialize_with = "cbor::deserialize_byte_string")] Vec<u8>);

    #[derive(Debug, Deserialize)]
    struct ByteArray(#[serde(deserialize_with = "cbor::deserialize_byte_array")] [u8; 2]);

    #[derive(Debug, Deserialize)]
    struct Unsigned(#[serde(deserialize_with = "cbor::deserialize_unsigned")] u8);

    #[test]
    fn cbor_byte_strings_accept_a_byte_string() {
        let bytes = Value::Bytes(vec![1, 2]);
        assert_eq!(from_cbor::<ByteString>(&bytes).unwrap().0, [1, 2]);
        assert_eq!(from_cbor::<ByteArray>(&bytes).unwrap().0, [1, 2]);
    }

    #[test_case(Value::Array(vec![1.into(), 2.into()]); "array of integers")]
    #[test_case(Value::Tag(64, Box::new(Value::Bytes(vec![1, 2]))); "tagged byte string")]
    #[test_case(Value::Text("0102".into()); "text")]
    #[test_case(Value::Null; "null")]
    fn cbor_byte_strings_reject_other_data_items(invalid: Value) {
        assert!(from_cbor::<ByteString>(&invalid).is_err());
        assert!(from_cbor::<ByteArray>(&invalid).is_err());
    }

    #[test]
    fn cbor_byte_array_rejects_another_length() {
        let error = from_cbor::<ByteArray>(&Value::Bytes(vec![1, 2, 3])).unwrap_err();
        assert!(error.to_string().contains("of 2 bytes, got 3"), "{error}");
    }

    #[test]
    fn cbor_unsigned_accepts_an_unsigned_integer_that_fits() {
        let value = Value::Integer(255.into());
        assert_eq!(from_cbor::<Unsigned>(&value).unwrap().0, 255);
    }

    #[test_case(Value::Integer(256.into()); "too wide")]
    #[test_case(Value::Integer((-1).into()); "negative")]
    #[test_case(Value::Float(1.0); "float")]
    #[test_case(Value::Text("1".into()); "text")]
    #[test_case(Value::Tag(0, Box::new(Value::Integer(1.into()))); "tagged")]
    #[test_case(Value::Tag(2, Box::new(Value::Bytes(vec![1]))); "bignum")]
    fn cbor_unsigned_rejects_other_data_items(invalid: Value) {
        assert!(from_cbor::<Unsigned>(&invalid).is_err());
    }
}