shadow_rs/utility/
units.rs

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
/*!
Types for parsing/deserializing unit values.

```
# use shadow_rs::utility::units::*;
# use std::str::FromStr;
let time = Time::from_str("10 min").unwrap();
assert_eq!(time, Time::new(10, TimePrefix::Min));

assert_eq!(
    time.convert(TimePrefix::Sec).unwrap(),
    Time::from_str("600 sec").unwrap()
);
```
*/

use std::fmt::{self, Debug, Display};
use std::str::FromStr;

use once_cell::sync::Lazy;
use regex::Regex;
use schemars::JsonSchema;
use serde::de::{Deserialize, Deserializer, Visitor};
use serde::ser::{Serialize, Serializer};

/// The prefix of a unit value denoting magnitude. Common prefixes are
/// SI prefixes (nano, micro, milli, etc).
pub trait Prefix: Clone + Copy + Default + PartialEq + FromStr + Display + Debug {
    /// The magnitude of this prefix relative to other prefixes of this type.
    fn relative_magnitude(&self) -> u128;

    /// An integer conversion factor.
    fn conversion_factor(&self, to: Self) -> Result<u128, String> {
        let from_mag = self.relative_magnitude();
        let to_mag = to.relative_magnitude();
        if from_mag % to_mag != 0 {
            return Err("Conversion would lose precision".to_string());
        }
        Ok(from_mag / to_mag)
    }

    /// A floating point conversion factor.
    fn conversion_factor_lossy(&self, to: Self) -> f64 {
        let from_mag = self.relative_magnitude();
        let to_mag = to.relative_magnitude();
        from_mag as f64 / to_mag as f64
    }
}

/// Common SI prefixes (including base-2 prefixes since they're similar).
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SiPrefix {
    Nano,
    Micro,
    Milli,
    Base,
    Kilo,
    Kibi,
    Mega,
    Mebi,
    Giga,
    Gibi,
    Tera,
    Tebi,
}

impl Default for SiPrefix {
    fn default() -> Self {
        Self::Base
    }
}

impl FromStr for SiPrefix {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "n" | "nano" => Ok(Self::Nano),
            "u" | "μ" | "micro" => Ok(Self::Micro),
            "m" | "milli" => Ok(Self::Milli),
            "K" | "kilo" => Ok(Self::Kilo),
            "Ki" | "kibi" => Ok(Self::Kibi),
            "M" | "mega" => Ok(Self::Mega),
            "Mi" | "mebi" => Ok(Self::Mebi),
            "G" | "giga" => Ok(Self::Giga),
            "Gi" | "gibi" => Ok(Self::Gibi),
            "T" | "tera" => Ok(Self::Tera),
            "Ti" | "tebi" => Ok(Self::Tebi),
            _ => Err(
                "Unit prefix was not one of (n|nano|u|μ|micro|m|milli|K|kilo\
                |Ki|kibi|M|mega|Mi|mebi|G|giga|Gi|gibi|T|tera|Ti|tebi)"
                    .to_string(),
            ),
        }
    }
}

impl fmt::Display for SiPrefix {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Nano => write!(f, "n"),
            Self::Micro => write!(f, "μ"),
            Self::Milli => write!(f, "m"),
            Self::Kilo => write!(f, "K"),
            Self::Kibi => write!(f, "Ki"),
            Self::Mega => write!(f, "M"),
            Self::Mebi => write!(f, "Mi"),
            Self::Giga => write!(f, "G"),
            Self::Gibi => write!(f, "Gi"),
            Self::Tera => write!(f, "T"),
            Self::Tebi => write!(f, "Ti"),
            Self::Base => Ok(()),
        }
    }
}

impl Prefix for SiPrefix {
    fn relative_magnitude(&self) -> u128 {
        const TEN: u128 = 10;
        const TWO: u128 = 2;
        const BASE: u128 = TEN.pow(9);
        match self {
            Self::Nano => BASE / TEN.pow(9),
            Self::Micro => BASE / TEN.pow(6),
            Self::Milli => BASE / TEN.pow(3),
            Self::Base => BASE,
            Self::Kilo => BASE * TEN.pow(3),
            Self::Kibi => BASE * TWO.pow(10),
            Self::Mega => BASE * TEN.pow(6),
            Self::Mebi => BASE * TWO.pow(20),
            Self::Giga => BASE * TEN.pow(9),
            Self::Gibi => BASE * TWO.pow(30),
            Self::Tera => BASE * TEN.pow(12),
            Self::Tebi => BASE * TWO.pow(40),
        }
    }
}

/// Common SI prefixes larger than the base unit (including base-2 prefixes
/// since they're similar).
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SiPrefixUpper {
    Base,
    Kilo,
    Kibi,
    Mega,
    Mebi,
    Giga,
    Gibi,
    Tera,
    Tebi,
}

impl Default for SiPrefixUpper {
    fn default() -> Self {
        Self::Base
    }
}

impl FromStr for SiPrefixUpper {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "K" | "kilo" => Ok(Self::Kilo),
            "Ki" | "kibi" => Ok(Self::Kibi),
            "M" | "mega" => Ok(Self::Mega),
            "Mi" | "mebi" => Ok(Self::Mebi),
            "G" | "giga" => Ok(Self::Giga),
            "Gi" | "gibi" => Ok(Self::Gibi),
            "T" | "tera" => Ok(Self::Tera),
            "Ti" | "tebi" => Ok(Self::Tebi),
            _ => Err("Unit prefix was not one of (K|kilo|Ki|kibi|M|mega|Mi|mebi\
                |G|giga|Gi|gibi|T|tera|Ti|tebi)"
                .to_string()),
        }
    }
}

impl fmt::Display for SiPrefixUpper {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Kilo => write!(f, "K"),
            Self::Kibi => write!(f, "Ki"),
            Self::Mega => write!(f, "M"),
            Self::Mebi => write!(f, "Mi"),
            Self::Giga => write!(f, "G"),
            Self::Gibi => write!(f, "Gi"),
            Self::Tera => write!(f, "T"),
            Self::Tebi => write!(f, "Ti"),
            Self::Base => Ok(()),
        }
    }
}

impl Prefix for SiPrefixUpper {
    fn relative_magnitude(&self) -> u128 {
        const TEN: u128 = 10;
        const TWO: u128 = 2;
        match self {
            Self::Base => 1,
            Self::Kilo => TEN.pow(3),
            Self::Kibi => TWO.pow(10),
            Self::Mega => TEN.pow(6),
            Self::Mebi => TWO.pow(20),
            Self::Giga => TEN.pow(9),
            Self::Gibi => TWO.pow(30),
            Self::Tera => TEN.pow(12),
            Self::Tebi => TWO.pow(40),
        }
    }
}

/// Time units, which we pretend are prefixes for implementation simplicity. These
/// contain both the prefix ("n", "u", "m") and the suffix ("sec", "min", "hr")
/// and should be used with the [`Time`] unit.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum TimePrefix {
    Nano,
    Micro,
    Milli,
    Sec,
    Min,
    Hour,
}

impl Default for TimePrefix {
    fn default() -> Self {
        Self::Sec
    }
}

impl FromStr for TimePrefix {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "ns" | "nanosecond" | "nanoseconds" => Ok(Self::Nano),
            "us" | "μs" | "microsecond" | "microseconds" => Ok(Self::Micro),
            "ms" | "millisecond" | "milliseconds" => Ok(Self::Milli),
            "s" | "sec" | "secs" | "second" | "seconds" => Ok(Self::Sec),
            "m" | "min" | "mins" | "minute" | "minutes" => Ok(Self::Min),
            "h" | "hr" | "hrs" | "hour" | "hours" => Ok(Self::Hour),
            _ => Err(
                "Unit was not one of (ns|nanosecond|nanoseconds|us|μs|microsecond|microseconds\
                |ms|millisecond|milliseconds|s|sec|secs|second|seconds|m|min|mins|minute|minutes\
                |h|hr|hrs|hour|hours)"
                    .to_string(),
            ),
        }
    }
}

impl fmt::Display for TimePrefix {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Nano => write!(f, "ns"),
            Self::Micro => write!(f, "μs"),
            Self::Milli => write!(f, "ms"),
            Self::Sec => write!(f, "sec"),
            Self::Min => write!(f, "min"),
            Self::Hour => write!(f, "hour"),
        }
    }
}

impl Prefix for TimePrefix {
    fn relative_magnitude(&self) -> u128 {
        const TEN: u128 = 10;
        const BASE: u128 = TEN.pow(9);
        match self {
            Self::Nano => BASE / TEN.pow(9),
            Self::Micro => BASE / TEN.pow(6),
            Self::Milli => BASE / TEN.pow(3),
            Self::Sec => BASE,
            Self::Min => BASE * 60,
            Self::Hour => BASE * 60 * 60,
        }
    }
}

/// Time units larger than the base unit, which we pretend are prefixes for
/// implementation simplicity. These really contain the unit suffix ("sec",
/// "min", "hr") and should be used with the [`Time`] unit.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum TimePrefixUpper {
    Sec,
    Min,
    Hour,
}

impl Default for TimePrefixUpper {
    fn default() -> Self {
        Self::Sec
    }
}

impl FromStr for TimePrefixUpper {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "s" | "sec" | "secs" | "second" | "seconds" => Ok(Self::Sec),
            "m" | "min" | "mins" | "minute" | "minutes" => Ok(Self::Min),
            "h" | "hr" | "hrs" | "hour" | "hours" => Ok(Self::Hour),
            _ => Err("Unit prefix was not one of (s|sec|secs|second|seconds\
                |m|min|mins|minute|minutes|h|hr|hrs|hour|hours)"
                .to_string()),
        }
    }
}

impl fmt::Display for TimePrefixUpper {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Sec => write!(f, "sec"),
            Self::Min => write!(f, "min"),
            Self::Hour => write!(f, "hour"),
        }
    }
}

impl Prefix for TimePrefixUpper {
    fn relative_magnitude(&self) -> u128 {
        match self {
            Self::Sec => 1,
            Self::Min => 60,
            Self::Hour => 60 * 60,
        }
    }
}

macro_rules! visit_fn {
    ($fn_name:ident, $type:ty) => {
        fn $fn_name<E>(self, x: $type) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(Self::Value::new(
                x.try_into().map_err(serde::de::Error::custom)?,
                T::default(),
            ))
        }
    };
}

macro_rules! unit_impl {
    ($name:ident, $type:ident, $suffixes:tt) => {
        impl<T: Prefix> $name<T> {
            pub fn new(value: $type, prefix: T) -> Self {
                Self { value, prefix }
            }
        }

        impl<T: Prefix> Default for $name<T> {
            fn default() -> Self {
                Self::new(0, T::default())
            }
        }

        impl<T: Prefix> Unit for $name<T> {
            type U = $type;
            type T = T;

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

            fn prefix(&self) -> Self::T {
                self.prefix
            }

            fn suffixes() -> &'static [&'static str] {
                &$suffixes
            }

            fn convert(&self, prefix: Self::T) -> Result<Self, String> {
                let factor = self.prefix.conversion_factor(prefix)?;
                let factor = factor.try_into().unwrap();
                Ok(Self::new(
                    Self::U::checked_mul(self.value, factor).ok_or(format!(
                        "The resulting value is outside of the bounds [{}, {}]",
                        Self::U::MIN,
                        Self::U::MAX,
                    ))?,
                    prefix,
                ))
            }

            fn convert_lossy(&self, prefix: Self::T) -> Self {
                let factor = self.prefix.conversion_factor_lossy(prefix);
                Self::new(
                    (self.value as f64 * factor).round() as Self::U,
                    prefix,
                )
            }
        }

        impl<T: Prefix> Display for $name<T> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{} {}{}", self.value(), self.prefix(), Self::suffixes()[0])
            }
        }

        impl<T: Prefix> FromStr for $name<T>
        where
            <T as FromStr>::Err: std::fmt::Debug + std::fmt::Display,
        {
            type Err = Box<dyn std::error::Error + Send + Sync>;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^([+-]?[0-9\.]*)\s*(.*)$").unwrap());

                let captures = RE.captures(s).ok_or("Unable to identify value and unit")?;
                let (value, unit) = (
                    captures.get(1).unwrap().as_str().trim(),
                    captures.get(2).unwrap().as_str().trim(),
                );

                // try removing all suffixes
                let prefix = $name::<T>::suffixes()
                    .iter()
                    .map(|suffix| unit.strip_suffix(suffix))
                    .find(|x| x.is_some())
                    .flatten()
                    .or(Some(unit))
                    .unwrap();

                let prefix = match prefix {
                    "" => T::default(),
                    _ => T::from_str(prefix).map_err(|x| x.to_string())?,
                };

                Ok($name::new(
                    value.parse()?,
                    prefix,
                ))
            }
        }

        impl<'de, T: Prefix> Deserialize<'de> for $name<T>
        where
            <T as FromStr>::Err: std::fmt::Debug + std::fmt::Display,
        {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                struct ValueVisitor<T> {
                    marker: std::marker::PhantomData<T>,
                }

                impl<'de, T: Prefix> Visitor<'de> for ValueVisitor<T>
                where
                    <T as FromStr>::Err: std::fmt::Debug + std::fmt::Display,
                {
                    type Value = $name<T>;

                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                        formatter.write_str(stringify!(struct $name<T>))
                    }

                    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
                    where
                        E: serde::de::Error,
                    {
                        Self::Value::from_str(s).map_err(serde::de::Error::custom)
                    }

                    visit_fn!(visit_u64, u64);
                    visit_fn!(visit_u32, u32);
                    visit_fn!(visit_u8, u8);
                    visit_fn!(visit_i64, i64);
                    visit_fn!(visit_i32, i32);
                    visit_fn!(visit_i8, i8);
                }

                deserializer.deserialize_any(ValueVisitor {
                    marker: std::marker::PhantomData,
                })
            }
        }

        impl<T: Prefix> Serialize for $name<T> {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                serializer.serialize_str(&self.to_string())
            }
        }

        impl<T: Prefix> JsonSchema for $name<T> {
            fn is_referenceable() -> bool { false }

            fn schema_name() -> String {
                stringify!($name).to_owned()
            }

            fn json_schema(_: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
                schemars::schema::SchemaObject {
                    instance_type: Some(schemars::schema::InstanceType::String.into()),
                    format: Some(stringify!($name).to_owned()),
                    ..Default::default()
                }
                .into()
            }
        }
    };
}

/// A unit containing a value (ex: an integer), a prefix (ex: an enum), and
/// allowed constant suffix strings.
pub trait Unit: Sized {
    type U;
    type T: Prefix;

    /// The value of the unit in the size of its current prefix.
    fn value(&self) -> Self::U;

    /// The current prefix.
    fn prefix(&self) -> Self::T;

    fn suffixes() -> &'static [&'static str];

    /// Convert value to a different prefix, but return an error if the conversion
    /// cannot be done without possibly losing precision.
    fn convert(&self, prefix: Self::T) -> Result<Self, String>
    where
        Self: Sized;

    /// Convert value to a different prefix, even if it loses precision.
    fn convert_lossy(&self, prefix: Self::T) -> Self
    where
        Self: Sized;
}

/// An amount of time. Should only use the time prefix types ([`TimePrefix`] and
/// [`TimePrefixUpper`]) with this type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Time<T: Prefix> {
    value: u64,
    prefix: T,
}

// Since our time prefix types ([TimePrefix] and [TimePrefixUpper]) aren't
// really prefixes, time units don't have a suffix.
unit_impl!(Time, u64, [""]);

impl From<Time<TimePrefix>> for std::time::Duration {
    fn from(time: Time<TimePrefix>) -> Self {
        std::time::Duration::from_nanos(time.convert(TimePrefix::Nano).unwrap().value())
    }
}

impl From<Time<TimePrefixUpper>> for std::time::Duration {
    fn from(time: Time<TimePrefixUpper>) -> Self {
        std::time::Duration::from_secs(time.convert(TimePrefixUpper::Sec).unwrap().value())
    }
}

/// A number of bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Bytes<T: Prefix> {
    pub value: u64,
    pub prefix: T,
}

unit_impl!(Bytes, u64, ["B", "byte", "bytes"]);

/// A throughput in bits-per-second.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BitsPerSec<T: Prefix> {
    pub value: u64,
    pub prefix: T,
}

unit_impl!(BitsPerSec, u64, ["bit", "bits"]);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_string() {
        assert_eq!(
            Time::from_str("10").unwrap(),
            Time::new(10, TimePrefix::Sec)
        );
        assert_eq!(
            Time::from_str("10 s").unwrap(),
            Time::new(10, TimePrefix::Sec)
        );
        assert_eq!(
            Time::from_str("10s").unwrap(),
            Time::new(10, TimePrefix::Sec)
        );
        assert_eq!(
            Time::from_str("10   s").unwrap(),
            Time::new(10, TimePrefix::Sec)
        );
        assert_eq!(
            Time::from_str("10sec").unwrap(),
            Time::new(10, TimePrefix::Sec)
        );
        assert_eq!(
            Time::from_str("10  m").unwrap(),
            Time::new(10, TimePrefix::Min)
        );
        assert_eq!(
            Time::from_str("10  min").unwrap(),
            Time::new(10, TimePrefix::Min)
        );
        assert_eq!(
            Time::from_str("10 ms").unwrap(),
            Time::new(10, TimePrefix::Milli)
        );
        assert_eq!(
            Time::from_str("10 μs").unwrap(),
            Time::new(10, TimePrefix::Micro)
        );
        assert_eq!(
            Time::from_str("10 millisecond").unwrap(),
            Time::new(10, TimePrefix::Milli)
        );
        assert_eq!(
            Time::from_str("10 milliseconds").unwrap(),
            Time::new(10, TimePrefix::Milli)
        );

        assert!(Time::<TimePrefix>::from_str("-10 ms").is_err());
        assert!(Time::<TimePrefix>::from_str("abc 10 ms").is_err());
        assert!(Time::<TimePrefix>::from_str("10.5 ms").is_err());
        assert!(Time::<TimePrefix>::from_str("10 abc").is_err());
        assert!(Time::<TimePrefixUpper>::from_str("10 ms").is_err());

        assert_eq!(
            Bytes::from_str("10").unwrap(),
            Bytes::new(10, SiPrefixUpper::Base)
        );
        assert_eq!(
            Bytes::from_str("10 B").unwrap(),
            Bytes::new(10, SiPrefixUpper::Base)
        );
        assert_eq!(
            Bytes::from_str("10B").unwrap(),
            Bytes::new(10, SiPrefixUpper::Base)
        );
        assert_eq!(
            Bytes::from_str("10   B").unwrap(),
            Bytes::new(10, SiPrefixUpper::Base)
        );
        assert_eq!(
            Bytes::from_str("10  KB").unwrap(),
            Bytes::new(10, SiPrefixUpper::Kilo)
        );
        assert_eq!(
            Bytes::from_str("10 KiB").unwrap(),
            Bytes::new(10, SiPrefixUpper::Kibi)
        );
        assert_eq!(
            Bytes::from_str("10 MB").unwrap(),
            Bytes::new(10, SiPrefixUpper::Mega)
        );
        assert_eq!(
            Bytes::from_str("10 megabyte").unwrap(),
            Bytes::new(10, SiPrefixUpper::Mega)
        );
        assert_eq!(
            Bytes::from_str("10 megabytes").unwrap(),
            Bytes::new(10, SiPrefixUpper::Mega)
        );

        assert!(Bytes::<SiPrefixUpper>::from_str("-10 KB").is_err());
        assert!(Bytes::<SiPrefixUpper>::from_str("abc 10 KB").is_err());
        assert!(Bytes::<SiPrefixUpper>::from_str("10.5 KB").is_err());
        assert!(Bytes::<SiPrefixUpper>::from_str("10 abc").is_err());
        assert!(Bytes::<SiPrefixUpper>::from_str("10 mB").is_err());
        assert!(Bytes::<SiPrefixUpper>::from_str("10 Megabyte").is_err());

        assert_eq!(
            BitsPerSec::from_str("10").unwrap(),
            BitsPerSec::new(10, SiPrefixUpper::Base)
        );
        assert_eq!(
            BitsPerSec::from_str("10 bit").unwrap(),
            BitsPerSec::new(10, SiPrefixUpper::Base)
        );
        assert_eq!(
            BitsPerSec::from_str("10bit").unwrap(),
            BitsPerSec::new(10, SiPrefixUpper::Base)
        );
        assert_eq!(
            BitsPerSec::from_str("10   bit").unwrap(),
            BitsPerSec::new(10, SiPrefixUpper::Base)
        );
        assert_eq!(
            BitsPerSec::from_str("10  Kbit").unwrap(),
            BitsPerSec::new(10, SiPrefixUpper::Kilo)
        );
        assert_eq!(
            BitsPerSec::from_str("10 Kibit").unwrap(),
            BitsPerSec::new(10, SiPrefixUpper::Kibi)
        );
        assert_eq!(
            BitsPerSec::from_str("10 Mbit").unwrap(),
            BitsPerSec::new(10, SiPrefixUpper::Mega)
        );
        assert_eq!(
            BitsPerSec::from_str("10 megabit").unwrap(),
            BitsPerSec::new(10, SiPrefixUpper::Mega)
        );
        assert_eq!(
            BitsPerSec::from_str("10 megabits").unwrap(),
            BitsPerSec::new(10, SiPrefixUpper::Mega)
        );

        assert!(BitsPerSec::<SiPrefixUpper>::from_str("-10 Kbit").is_err());
        assert!(BitsPerSec::<SiPrefixUpper>::from_str("abc 10 Kbit").is_err());
        assert!(BitsPerSec::<SiPrefixUpper>::from_str("10.5 Kbit").is_err());
        assert!(BitsPerSec::<SiPrefixUpper>::from_str("10 abc").is_err());
        assert!(BitsPerSec::<SiPrefixUpper>::from_str("10 mbit").is_err());
    }

    #[test]
    fn test_conversion() {
        let time = Time::from_str("70 min").unwrap();

        assert_eq!(
            time.convert(TimePrefix::Sec).unwrap(),
            Time::from_str("4200 sec").unwrap()
        );
        assert!(time.convert(TimePrefix::Hour).is_err());

        assert_eq!(
            time.convert_lossy(TimePrefix::Sec),
            Time::from_str("4200 sec").unwrap()
        );
        assert_eq!(
            time.convert_lossy(TimePrefix::Hour),
            Time::from_str("1 hour").unwrap()
        );

        let bw = BitsPerSec::from_str("1024 Kbit").unwrap();

        assert_eq!(
            bw.convert(SiPrefixUpper::Base).unwrap(),
            BitsPerSec::from_str("1024000 bit").unwrap()
        );
        assert!(bw.convert(SiPrefixUpper::Kibi).is_err());

        assert_eq!(
            bw.convert_lossy(SiPrefixUpper::Base),
            BitsPerSec::from_str("1024000 bit").unwrap()
        );
        assert_eq!(
            bw.convert_lossy(SiPrefixUpper::Kibi),
            BitsPerSec::from_str("1000 Kibit").unwrap()
        );
    }

    #[test]
    fn test_time_conversion() {
        let time = Time::<TimePrefixUpper>::from_str("70 min").unwrap();
        assert_eq!(
            std::time::Duration::from_secs(70 * 60),
            std::time::Duration::from(time)
        );

        let time = Time::new(1_000_000_123, TimePrefix::Nano);
        assert_eq!(
            std::time::Duration::new(1, 123),
            std::time::Duration::from(time)
        );
    }
}