icann-rdap-common 0.0.29

Common RDAP data structures.
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
//! Types for more lenient processing of invalid RDAP

use std::{borrow::Borrow, fmt::Display, marker::PhantomData, ops::Deref, str::FromStr};

use {
    serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer},
    serde_json::Number,
};

use crate::check::StringListCheck;

/// A type that is suppose to be a vector of strings.
///
/// Provides a choice between a string or a vector of strings for deserialization.
///
/// This type is provided to be lenient with misbehaving RDAP servers that
/// serve a string when they are suppose to be serving an array of
/// strings.
///
/// Use one of the From methods for construction.
/// ```rust
/// use icann_rdap_common::prelude::*;
///
/// let v = VectorStringish::from(vec!["one".to_string(), "two".to_string()]);
///
/// // or
///
/// let v = VectorStringish::from("one".to_string());
/// ````
#[derive(Serialize, Clone, Debug, PartialEq, Eq)]
#[serde(transparent)]
pub struct VectorStringish {
    vec: Vec<String>,
    #[serde(skip)]
    is_string: bool,
}

impl<'de> Deserialize<'de> for VectorStringish {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_any(VectorStringishVisitor)
    }
}

struct VectorStringishVisitor;

impl<'de> Visitor<'de> for VectorStringishVisitor {
    type Value = VectorStringish;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("expected an array of strings")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(VectorStringish {
            vec: vec![v.to_owned()],
            is_string: true,
        })
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::SeqAccess<'de>,
    {
        let mut v = vec![];
        loop {
            let n = seq.next_element()?;
            if let Some(s) = n {
                v.push(s);
            } else {
                break;
            }
        }
        Ok(VectorStringish {
            vec: v,
            is_string: false,
        })
    }
}

impl From<String> for VectorStringish {
    fn from(value: String) -> Self {
        Self {
            vec: vec![value],
            is_string: false,
        }
    }
}

impl From<&str> for VectorStringish {
    fn from(value: &str) -> Self {
        Self {
            vec: vec![value.to_owned()],
            is_string: false,
        }
    }
}

impl From<Vec<String>> for VectorStringish {
    fn from(value: Vec<String>) -> Self {
        Self {
            vec: value,
            is_string: false,
        }
    }
}

impl From<VectorStringish> for Vec<String> {
    fn from(value: VectorStringish) -> Self {
        value.vec
    }
}

impl From<&VectorStringish> for Vec<String> {
    fn from(value: &VectorStringish) -> Self {
        value.vec.to_owned()
    }
}

impl VectorStringish {
    /// Consumes and converts it to a `Vec<String>`.
    pub fn into_vec(self) -> Vec<String> {
        self.vec
    }

    /// Gets a reference to the underlying `Vec<String>`.
    pub fn vec(&self) -> &Vec<String> {
        &self.vec
    }

    /// Returns true if the deserialization was as a string.
    pub fn is_string(&self) -> bool {
        self.is_string
    }
}

impl StringListCheck for VectorStringish {
    fn is_empty_or_any_empty_or_whitespace(&self) -> bool {
        self.vec().is_empty_or_any_empty_or_whitespace()
    }

    fn is_ldh_string_list(&self) -> bool {
        self.vec().is_ldh_string_list()
    }
}

/// Returns `Some(VectorStringish)` if the vector is not empty; otherwise, `None`.
pub fn to_opt_vectorstringish(vec: Vec<String>) -> Option<VectorStringish> {
    (!vec.is_empty()).then_some(VectorStringish::from(vec))
}

#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(untagged)]
enum StringishInner {
    /// Valid RDAP.
    String(String),

    /// Invalid RDAP.
    Bool(bool),

    /// Invalid RDAP.
    Number(Number),
}

/// A type that is suppose to be a string.
///
/// This type is provided to be lenient with misbehaving RDAP servers that
/// serve a boolean or number when they are suppose to be serving a string.
///
/// Use one of the From methods for construction.
/// ```rust
/// use icann_rdap_common::prelude::*;
///
/// let v = Stringish::from("one");
/// ````
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Stringish {
    value: String,
    is_number: bool,
    is_bool: bool,
}

impl Serialize for Stringish {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.value)
    }
}

impl<'de> Deserialize<'de> for Stringish {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let inner = StringishInner::deserialize(deserializer)?;
        let (value, is_number, is_bool) = match inner {
            StringishInner::String(s) => (s, false, false),
            StringishInner::Bool(b) => (b.to_string(), false, true),
            StringishInner::Number(n) => (n.to_string(), true, false),
        };
        Ok(Stringish {
            value,
            is_number,
            is_bool,
        })
    }
}

impl From<String> for Stringish {
    fn from(value: String) -> Self {
        Self {
            value,
            is_number: false,
            is_bool: false,
        }
    }
}

impl From<&str> for Stringish {
    fn from(value: &str) -> Self {
        Self {
            value: value.to_owned(),
            is_number: false,
            is_bool: false,
        }
    }
}

impl From<Stringish> for String {
    fn from(value: Stringish) -> Self {
        value.value
    }
}

impl Display for Stringish {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.value)
    }
}

impl Deref for Stringish {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl AsRef<str> for Stringish {
    fn as_ref(&self) -> &str {
        &self.value
    }
}

impl Borrow<str> for Stringish {
    fn borrow(&self) -> &str {
        &self.value
    }
}

impl PartialEq<str> for Stringish {
    fn eq(&self, other: &str) -> bool {
        self.value == other
    }
}

impl PartialEq<&str> for Stringish {
    fn eq(&self, other: &&str) -> bool {
        self.value == *other
    }
}

impl PartialEq<String> for Stringish {
    fn eq(&self, other: &String) -> bool {
        self.value == *other
    }
}

impl Stringish {
    /// Returns true if the deserialization was as a number.
    pub fn is_number(&self) -> bool {
        self.is_number
    }

    /// Returns true if the deserialization was as a boolean.
    pub fn is_bool(&self) -> bool {
        self.is_bool
    }
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(untagged)]
enum BoolishInner {
    /// Valid RDAP.
    Bool(bool),

    /// Invalid RDAP.
    String(String),
}

/// A type that is suppose to be a boolean.
///
/// Provides a choice between a boolean or a string representation of a boolean for deserialization.
///
/// This type is provided to be lenient with misbehaving RDAP servers that
/// serve a string representation of a boolean when they are suppose to be serving a boolean
///
/// Use one of the From methods for construction.
/// ```rust
/// use icann_rdap_common::prelude::*;
///
/// let v = Boolish::from(true);
/// ````
///
/// When converting from a string (as would happen with deserialization),
/// the values "true", "t", "yes", and "y" (case-insensitive with whitespace trimmed)
/// will be true, all other values will be false.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(transparent)]
pub struct Boolish {
    inner: BoolishInner,
}

impl From<bool> for Boolish {
    fn from(value: bool) -> Self {
        Self {
            inner: BoolishInner::Bool(value),
        }
    }
}

impl Display for Boolish {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.into_bool())
    }
}

impl Boolish {
    /// Converts to a bool.
    pub fn into_bool(&self) -> bool {
        match &self.inner {
            BoolishInner::Bool(value) => *value,
            BoolishInner::String(value) => Boolish::is_true(value),
        }
    }

    /// Returns true if the deserialization was as a string.
    pub fn is_string(&self) -> bool {
        match &self.inner {
            BoolishInner::Bool(_) => false,
            BoolishInner::String(_) => true,
        }
    }

    fn is_true(value: &str) -> bool {
        let s = value.trim().to_lowercase();
        s == "true" || s == "t" || s == "yes" || s == "y"
    }
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(untagged)]
enum NumberishInner {
    /// Valid RDAP.
    Number(Number),

    /// Invalid RDAP.
    String(String),
}

/// A type that is suppose to be a number.
///
/// Provides a choice between a number or a string representation of a number for deserialization.
///
/// This type is provided to be lenient with misbehaving RDAP servers that
/// serve a string representation of a number when they are suppose to be serving a number.
///
/// Use the From methods for construction.
/// ```rust
/// use icann_rdap_common::prelude::*;
///
/// let v = Numberish::from(123);
/// ````
///
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(transparent)]
pub struct Numberish<T> {
    inner: NumberishInner,
    phantom: PhantomData<T>,
}

impl<T> From<T> for Numberish<T>
where
    Number: From<T>,
{
    fn from(value: T) -> Self {
        Self {
            inner: NumberishInner::Number(Number::from(value)),
            phantom: PhantomData,
        }
    }
}

impl<T> Display for Numberish<T>
where
    Number: From<T>,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            self.as_u64()
                .map_or("RANGE_ERROR".to_string(), |u| u.to_string())
        )
    }
}

impl<T> Numberish<T>
where
    Number: From<T>,
{
    /// Returns true if the deserialization was as a string.
    pub fn is_string(&self) -> bool {
        match &self.inner {
            NumberishInner::Number(_) => false,
            NumberishInner::String(_) => true,
        }
    }

    /// If the `Number` is an integer, represent it as u64 if possible. Returns None otherwise.
    pub fn as_u64(&self) -> Option<u64> {
        match &self.inner {
            NumberishInner::Number(n) => n.as_u64(),
            NumberishInner::String(s) => Number::from_str(s).ok()?.as_u64(),
        }
    }

    /// If the `Number` is an integer, represent it as u32 if possible. Returns None otherwise.
    pub fn as_u32(&self) -> Option<u32> {
        match &self.inner {
            NumberishInner::Number(n) => n.as_u64()?.try_into().ok(),
            NumberishInner::String(s) => Number::from_str(s).ok()?.as_u64()?.try_into().ok(),
        }
    }

    /// If the `Number` is an integer, represent it as u16 if possible. Returns None otherwise.
    pub fn as_u16(&self) -> Option<u16> {
        match &self.inner {
            NumberishInner::Number(n) => n.as_u64()?.try_into().ok(),
            NumberishInner::String(s) => Number::from_str(s).ok()?.as_u64()?.try_into().ok(),
        }
    }

    /// If the `Number` is an integer, represent it as u8 if possible. Returns None otherwise.
    pub fn as_u8(&self) -> Option<u8> {
        match &self.inner {
            NumberishInner::Number(n) => n.as_u64()?.try_into().ok(),
            NumberishInner::String(s) => Number::from_str(s).ok()?.as_u64()?.try_into().ok(),
        }
    }
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        serde_json::{from_str, to_string},
    };

    //
    // VectorStringish tests
    //

    #[test]
    fn test_vectorstringish_serialize_many() {
        // GIVEN
        let many = VectorStringish::from(vec!["one".to_string(), "two".to_string()]);

        // WHEN
        let serialized = to_string(&many).unwrap();

        // THEN
        assert_eq!(serialized, r#"["one","two"]"#);
    }

    #[test]
    fn test_vectorstringish_serialize_one() {
        // GIVEN
        let one = VectorStringish::from("one".to_string());

        // WHEN
        let serialized = to_string(&one).unwrap();

        // THEN
        assert_eq!(serialized, r#"["one"]"#);
    }

    #[test]
    fn test_vectorstringish_deserialize_many() {
        // GIVEN
        let json_str = r#"["one","two"]"#;

        // WHEN
        let deserialized: VectorStringish = from_str(json_str).unwrap();

        // THEN
        assert_eq!(
            deserialized.vec(),
            &vec!["one".to_string(), "two".to_string()]
        );

        // and THEN is not string
        assert!(!deserialized.is_string())
    }

    #[test]
    fn test_vectorstringish_deserialize_one() {
        // GIVEN
        let json_str = r#""one""#;

        // WHEN
        let deserialized: VectorStringish = from_str(json_str).unwrap();

        // THEN
        assert_eq!(deserialized.vec(), &vec!["one".to_string()]);

        // and THEN is string
        assert!(deserialized.is_string())
    }

    //
    // Stringish tests
    //

    #[test]
    fn test_stringish_serialize() {
        // GIVEN
        let a_string = Stringish::from("one");

        // WHEN
        let serialized = to_string(&a_string).unwrap();

        // THEN
        assert_eq!(serialized, r#""one""#);
    }

    #[test]
    fn test_string_from_stringish() {
        // GIVEN
        let stringish = Stringish::from("hello");

        // WHEN
        let s = String::from(stringish);

        // THEN
        assert_eq!(s, "hello");
    }

    #[test]
    fn test_stringish_deref() {
        // GIVEN
        let stringish = Stringish::from("hello");

        // WHEN
        let s: &str = &stringish;

        // THEN
        assert_eq!(s, "hello");
        assert_eq!(stringish.len(), 5);
    }

    #[test]
    fn test_stringish_more_traits() {
        // GIVEN
        let stringish = Stringish::from("hello");

        // THEN AsRef
        assert_eq!(stringish.as_ref(), "hello");

        // THEN Borrow
        assert_eq!(stringish.borrow() as &str, "hello");

        // THEN PartialEq
        assert!(stringish == "hello");
        assert!(stringish == *"hello");
        assert!(stringish == *"hello");
    }

    #[test]
    fn test_stringish_serialize_number() {
        // GIVEN
        let deserialized: Stringish = from_str("123").unwrap();

        // WHEN
        let serialized = to_string(&deserialized).unwrap();

        // THEN
        assert_eq!(serialized, r#""123""#);
    }

    #[test]
    fn test_stringish_serialize_bool() {
        // GIVEN
        let deserialized: Stringish = from_str("true").unwrap();

        // WHEN
        let serialized = to_string(&deserialized).unwrap();

        // THEN
        assert_eq!(serialized, r#""true""#);
    }

    #[test]
    fn test_stringish_deserialize_string() {
        // GIVEN
        let json_str = r#""one""#;

        // WHEN
        let deserialized: Stringish = from_str(json_str).unwrap();

        // THEN
        assert_eq!(deserialized, Stringish::from("one"));

        // and THEN is not bool
        assert!(!deserialized.is_bool());

        // and THEN is not number
        assert!(!deserialized.is_number());
    }

    #[test]
    fn test_stringish_deserialize_bool() {
        // GIVEN
        let json_str = r#"true"#;

        // WHEN
        let deserialized: Stringish = from_str(json_str).unwrap();

        // THEN
        assert_eq!(deserialized.to_string(), "true");

        // and THEN is bool
        assert!(deserialized.is_bool());

        // and THEN is not number
        assert!(!deserialized.is_number());
    }

    #[test]
    fn test_stringish_deserialize_number() {
        // GIVEN
        let json_str = r#"1234"#;

        // WHEN
        let deserialized: Stringish = from_str(json_str).unwrap();

        // THEN
        assert_eq!(deserialized.to_string(), "1234");

        // and THEN is not bool
        assert!(!deserialized.is_bool());

        // and THEN is number
        assert!(deserialized.is_number());
    }

    //
    // Boolish tests
    //

    #[test]
    fn test_boolish_serialize_bool() {
        // GIVEN
        let b = Boolish::from(true);

        // WHEN
        let serialized = to_string(&b).unwrap();

        // THEN
        assert_eq!(serialized, "true");
    }

    #[test]
    fn test_boolish_deserialize_bool_true() {
        // GIVEN
        let json_str = "true";

        // WHEN
        let deserialized: Boolish = from_str(json_str).unwrap();

        // THEN
        assert!(deserialized.into_bool());
        assert!(!deserialized.is_string());
    }

    #[test]
    fn test_boolish_deserialize_bool_false() {
        // GIVEN
        let json_str = "false";

        // WHEN
        let deserialized: Boolish = from_str(json_str).unwrap();

        // THEN
        assert!(!deserialized.into_bool());
        assert!(!deserialized.is_string());
    }

    #[test]
    fn test_boolish_deserialize_string_true() {
        // GIVEN
        let json_str = r#""true""#;

        // WHEN
        let deserialized: Boolish = from_str(json_str).unwrap();

        // THEN
        assert!(deserialized.into_bool());
        assert!(deserialized.is_string());
    }

    #[test]
    fn test_boolish_deserialize_string_false() {
        // GIVEN
        let json_str = r#""false""#;

        // WHEN
        let deserialized: Boolish = from_str(json_str).unwrap();

        // THEN
        assert!(!deserialized.into_bool());
        assert!(deserialized.is_string());
    }

    #[test]
    fn test_boolish_is_true() {
        // GIVEN various true values
        let true_values = ["true", "t", "yes", "y", " True ", " T ", " Yes ", " Y "];

        // THEN all are true
        for value in true_values {
            assert!(Boolish::is_true(value));
        }
    }

    #[test]
    fn test_boolish_is_false() {
        // GIVEN various false values
        let false_values = ["false", "f", "no", "n", "False", "blah", "1", "0", ""];

        // THEN all are false
        for value in false_values {
            assert!(!Boolish::is_true(value));
        }
    }

    #[test]
    fn test_boolish_from_bool() {
        assert!(Boolish::from(true).into_bool());
        assert!(!Boolish::from(false).into_bool());
    }

    //
    // Numberish Tests
    //

    #[test]
    fn test_numberish_serialize_number() {
        // GIVEN a Numberish from a number
        let n = Numberish::<u32>::from(123);

        // WHEN serialized
        let serialized = to_string(&n).unwrap();

        // THEN it is the correct string
        assert_eq!(serialized, "123");
    }

    #[test]
    fn test_numberish_deserialize_number() {
        // GIVEN a JSON string representing a number
        let json_str = "123";

        // WHEN deserialized
        let deserialized: Numberish<u32> = from_str(json_str).unwrap();

        // THEN the value is correct and it's not a string
        assert_eq!(deserialized.as_u32(), Some(123));
        assert!(!deserialized.is_string());
    }

    #[test]
    fn test_numberish_deserialize_string() {
        // GIVEN a JSON string representing a number as a string
        let json_str = r#""123""#;

        // WHEN deserialized
        let deserialized: Numberish<u32> = from_str(json_str).unwrap();

        // THEN the value is correct and it's a string
        assert_eq!(deserialized.as_u32(), Some(123));
        assert!(deserialized.is_string());
    }

    #[test]
    fn test_numberish_as_u64_number() {
        // GIVEN a Numberish from a u64
        let n = Numberish::from(123u64);

        // WHEN as_u64 is called
        let result = n.as_u64();

        // THEN the result is Some(123)
        assert_eq!(result, Some(123));
    }

    #[test]
    fn test_numberish_as_u64_string_invalid() {
        // GIVEN a Numberish from a string that does not represent a u64
        let n = Numberish {
            inner: NumberishInner::String("abc".to_string()),
            phantom: PhantomData::<u64>,
        };

        // WHEN as_u64 is called
        let result = n.as_u64();

        // THEN the result is None
        assert_eq!(result, None);
    }

    #[test]
    fn test_numberish_as_smaller_types() {
        // GIVEN a valid number
        let n = Numberish::from(123u64);

        // THEN smaller type conversions work
        assert_eq!(n.as_u32(), Some(123));
        assert_eq!(n.as_u16(), Some(123));
        assert_eq!(n.as_u8(), Some(123));

        // GIVEN a number too large
        let n = Numberish::from(u32::MAX as u64 + 1);

        // THEN smaller type conversions fail
        assert_eq!(n.as_u32(), None);
        assert_eq!(n.as_u16(), None);
        assert_eq!(n.as_u8(), None);

        // GIVEN a valid number string
        let n = Numberish {
            inner: NumberishInner::String("123".to_string()),
            phantom: PhantomData::<u64>,
        };

        // THEN smaller type conversions work
        assert_eq!(n.as_u32(), Some(123));
        assert_eq!(n.as_u16(), Some(123));
        assert_eq!(n.as_u8(), Some(123));

        // GIVEN a number string too large
        let n = Numberish {
            inner: NumberishInner::String((u32::MAX as u64 + 1).to_string()),
            phantom: PhantomData::<u64>,
        };

        // THEN smaller type conversions fail
        assert_eq!(n.as_u32(), None);
    }

    #[test]
    fn test_numberish_display_number() {
        let n = Numberish::<u32>::from(123);
        assert_eq!(format!("{}", n), "123");
    }

    #[test]
    fn test_numberish_display_string_valid() {
        let n = Numberish {
            inner: NumberishInner::String("123".to_string()),
            phantom: PhantomData::<u32>,
        };
        assert_eq!(format!("{}", n), "123");
    }

    #[test]
    fn test_numberish_display_string_invalid() {
        let n = Numberish {
            inner: NumberishInner::String("abc".to_string()),
            phantom: PhantomData::<u32>,
        };
        assert_eq!(format!("{}", n), "RANGE_ERROR");
    }
}