1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![allow(clippy::cognitive_complexity)] // See arti#2556
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![warn(clippy::or_fun_call)]
28
#![deny(clippy::print_stderr)]
29
#![deny(clippy::print_stdout)]
30
#![warn(clippy::rc_buffer)]
31
#![deny(clippy::ref_option_ref)]
32
#![warn(clippy::semicolon_if_nothing_returned)]
33
#![warn(clippy::trait_duplication_in_bounds)]
34
#![deny(clippy::unchecked_time_subtraction)]
35
#![deny(clippy::unnecessary_wraps)]
36
#![warn(clippy::unseparated_literal_suffix)]
37
#![deny(clippy::unwrap_used)]
38
#![deny(clippy::mod_module_files)]
39
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40
#![allow(clippy::uninlined_format_args)]
41
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44
#![allow(clippy::needless_lifetimes)] // See arti#1765
45
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46
#![allow(clippy::collapsible_if)] // See arti#2342
47
#![deny(clippy::unused_async)]
48
#![deny(clippy::string_slice)] // See arti#2571
49
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51

            
52
// TODO: add to the list maintained by maint/add_warning once it's available on all crates
53
#![warn(unnameable_types)]
54

            
55
use derive_more::{Add, Display, Div, From, FromStr, Mul};
56

            
57
use serde::{Deserialize, Serialize};
58
use std::time::Duration;
59
use thiserror::Error;
60

            
61
#[cfg(feature = "memquota-memcost")]
62
use {derive_deftly::Deftly, tor_memquota::derive_deftly_template_HasMemoryCost};
63

            
64
/// Conversion errors from converting a value into a [`BoundedInt32`].
65
#[derive(Debug, Clone, PartialEq, Eq, Error)]
66
#[non_exhaustive]
67
pub enum Error {
68
    /// A passed value was below the lower bound for the type.
69
    #[error("Value {0} was below the lower bound {1} for this type")]
70
    BelowLowerBound(i32, i32),
71
    /// A passed value was above the upper bound for the type.
72
    #[error("Value {0} was above the lower bound {1} for this type")]
73
    AboveUpperBound(i32, i32),
74
    /// Tried to convert a negative value to an unsigned type.
75
    #[error("Tried to convert a negative value to an unsigned type")]
76
    Negative,
77
    /// Tried to parse a value that was not representable as the
78
    /// underlying type.
79
    #[error("Value could not be represented as an i32")]
80
    Unrepresentable,
81
    /// We encountered some kind of integer overflow when converting a number.
82
    #[error("Integer overflow")]
83
    Overflow,
84
}
85

            
86
/// A 32-bit signed integer with a restricted range.
87
///
88
/// This type holds an i32 value such that `LOWER` <= value <= `UPPER`
89
///
90
/// # Limitations
91
///
92
/// If you were to try to instantiate this type with LOWER > UPPER,
93
/// you would get an uninhabitable type.
94
/// Attempting to construct a value with a type with LOWER > UPPER
95
/// will result in a compile-time error;
96
/// though there may not be a compiler error if the code that constructs the value is
97
/// dead code and is optimized away.
98
/// It would be better if we could prevent such types from being named.
99
//
100
// [TODO: If you need a Bounded* for some type other than i32, ask nickm:
101
// he has an implementation kicking around.]
102
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
103
#[cfg_attr(
104
    feature = "memquota-memcost",
105
    derive(Deftly),
106
    derive_deftly(HasMemoryCost)
107
)]
108
pub struct BoundedInt32<const LOWER: i32, const UPPER: i32> {
109
    /// Interior Value
110
    value: i32,
111
}
112

            
113
impl<const LOWER: i32, const UPPER: i32> BoundedInt32<LOWER, UPPER> {
114
    /// Lower bound
115
    pub const LOWER: i32 = LOWER;
116
    /// Upper bound
117
    pub const UPPER: i32 = UPPER;
118

            
119
    /// Private constructor function for this type.
120
1735475
    fn unchecked_new(value: i32) -> Self {
121
        // If there is a code path leading to this function that remains after dead code elimination,
122
        // this will ensures LOWER <= UPPER at build time.
123
        const { assert!(LOWER <= UPPER) };
124

            
125
1735475
        BoundedInt32 { value }
126
1735475
    }
127

            
128
    /// Return the lower bound value of this bounded i32.
129
    ///
130
    /// This always return [`Self::LOWER`].
131
97
    pub const fn lower(&self) -> i32 {
132
97
        LOWER
133
97
    }
134

            
135
    /// Return the lower bound value of this bounded i32.
136
    ///
137
    /// This always return [`Self::LOWER`].
138
97
    pub const fn upper(&self) -> i32 {
139
97
        UPPER
140
97
    }
141

            
142
    /// Return the underlying i32 value.
143
    ///
144
    /// This value will always be between [`Self::LOWER`] and [`Self::UPPER`],
145
    /// inclusive.
146
45804
    pub fn get(&self) -> i32 {
147
45804
        self.value
148
45804
    }
149

            
150
    /// Return the underlying u32 value, if [`Self::LOWER`] is non-negative.
151
    ///
152
    /// If [`Self::LOWER`] is negative, this will panic at build-time.
153
    ///
154
    /// This value will always be between [`Self::LOWER`] and [`Self::UPPER`],
155
    /// inclusive.
156
19581
    pub fn get_u32(&self) -> u32 {
157
        const { assert!(LOWER >= 0) };
158
19581
        self.value as u32
159
19581
    }
160

            
161
    /// If `val` is within range, return a new `BoundedInt32` wrapping
162
    /// it; otherwise, clamp it to the upper or lower bound as
163
    /// appropriate.
164
52
    pub fn saturating_new(val: i32) -> Self {
165
52
        Self::unchecked_new(Self::clamp(val))
166
52
    }
167

            
168
    /// If `val` is an acceptable value inside the range for this type,
169
    /// return a new [`BoundedInt32`].  Otherwise return an error.
170
1735461
    pub fn checked_new(val: i32) -> Result<Self, Error> {
171
1735461
        if val > UPPER {
172
55
            Err(Error::AboveUpperBound(val, UPPER))
173
1735406
        } else if val < LOWER {
174
2
            Err(Error::BelowLowerBound(val, LOWER))
175
        } else {
176
1735404
            Ok(BoundedInt32::unchecked_new(val))
177
        }
178
1735461
    }
179

            
180
    /// This private function clamps an input to the acceptable range.
181
71
    fn clamp(val: i32) -> i32 {
182
71
        Ord::clamp(val, LOWER, UPPER)
183
71
    }
184

            
185
    /// Convert from the underlying type, clamping to the upper or
186
    /// lower bound if needed.
187
    ///
188
    /// # Panics
189
    ///
190
    /// This function will panic if UPPER < LOWER.
191
19
    pub fn saturating_from(val: i32) -> Self {
192
19
        Self::unchecked_new(Self::clamp(val))
193
19
    }
194

            
195
    /// Convert from a string, clamping to the upper or lower bound if needed.
196
    ///
197
    /// # Limitations
198
    ///
199
    /// If the input is a number that cannot be represented as an i32,
200
    /// then we return an error instead of clamping it.
201
2
    pub fn saturating_from_str(s: &str) -> Result<Self, Error> {
202
2
        let val: i32 = s.parse().map_err(|_| Error::Unrepresentable)?;
203
2
        Ok(Self::saturating_from(val))
204
2
    }
205
}
206

            
207
impl<const L: i32, const U: i32> std::fmt::Display for BoundedInt32<L, U> {
208
1
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
209
1
        write!(f, "{}", self.value)
210
1
    }
211
}
212

            
213
impl<const L: i32, const U: i32> From<BoundedInt32<L, U>> for i32 {
214
5
    fn from(val: BoundedInt32<L, U>) -> i32 {
215
5
        val.value
216
5
    }
217
}
218

            
219
impl<const L: i32, const U: i32> From<BoundedInt32<L, U>> for f64 {
220
15504
    fn from(val: BoundedInt32<L, U>) -> f64 {
221
15504
        val.value.into()
222
15504
    }
223
}
224

            
225
impl<const L: i32, const H: i32> TryFrom<i32> for BoundedInt32<L, H> {
226
    type Error = Error;
227
1629311
    fn try_from(val: i32) -> Result<Self, Self::Error> {
228
1629311
        Self::checked_new(val)
229
1629311
    }
230
}
231

            
232
impl<const L: i32, const H: i32> std::str::FromStr for BoundedInt32<L, H> {
233
    type Err = Error;
234
10
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
235
10
        Self::checked_new(s.parse().map_err(|_| Error::Unrepresentable)?)
236
10
    }
237
}
238

            
239
impl From<BoundedInt32<0, 1>> for bool {
240
594146
    fn from(val: BoundedInt32<0, 1>) -> bool {
241
594146
        val.value == 1
242
594146
    }
243
}
244

            
245
impl From<BoundedInt32<0, 255>> for u8 {
246
4
    fn from(val: BoundedInt32<0, 255>) -> u8 {
247
4
        val.value as u8
248
4
    }
249
}
250

            
251
impl From<BoundedInt32<1, 254>> for u8 {
252
4800
    fn from(val: BoundedInt32<1, 254>) -> u8 {
253
4800
        val.value as u8
254
4800
    }
255
}
256

            
257
/// Convert to `u32`.
258
///
259
/// If `L` is negative, this will panic at build-time. See [`BoundedInt32::get_u32`].
260
impl<const L: i32, const H: i32> From<BoundedInt32<L, H>> for u32 {
261
19096
    fn from(val: BoundedInt32<L, H>) -> u32 {
262
19096
        val.get_u32()
263
19096
    }
264
}
265

            
266
impl<const L: i32, const H: i32> TryFrom<BoundedInt32<L, H>> for u64 {
267
    type Error = Error;
268
41998
    fn try_from(val: BoundedInt32<L, H>) -> Result<Self, Self::Error> {
269
41998
        if val.value < 0 {
270
1
            Err(Error::Negative)
271
        } else {
272
41997
            Ok(val.value as u64)
273
        }
274
41998
    }
275
}
276

            
277
impl<const L: i32, const H: i32> TryFrom<BoundedInt32<L, H>> for usize {
278
    type Error = Error;
279
14923
    fn try_from(val: BoundedInt32<L, H>) -> Result<Self, Self::Error> {
280
14923
        if val.value < 0 {
281
1
            Err(Error::Negative)
282
        } else {
283
14922
            Ok(val.value as usize)
284
        }
285
14923
    }
286
}
287

            
288
/// A percentage value represented as a number.
289
///
290
/// This type wraps an underlying numeric type, and ensures that callers
291
/// are clear whether they want a _fraction_, or a _percentage_.
292
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
293
pub struct Percentage<T: Copy + Into<f64>> {
294
    /// The underlying percentage value.
295
    value: T,
296
}
297

            
298
impl<T: Copy + Into<f64>> Percentage<T> {
299
    /// Create a new `IntPercentage` from the underlying percentage.
300
181712
    pub fn new(value: T) -> Self {
301
181712
        Self { value }
302
181712
    }
303

            
304
    /// Return this value as a (possibly improper) fraction.
305
    ///
306
    /// ```
307
    /// use tor_units::Percentage;
308
    /// let pct_200 = Percentage::<u8>::new(200);
309
    /// let pct_100 = Percentage::<u8>::new(100);
310
    /// let pct_50 = Percentage::<u8>::new(50);
311
    ///
312
    /// assert_eq!(pct_200.as_fraction(), 2.0);
313
    /// assert_eq!(pct_100.as_fraction(), 1.0);
314
    /// assert_eq!(pct_50.as_fraction(), 0.5);
315
    /// // Note: don't actually compare f64 with ==.
316
    /// ```
317
15506
    pub fn as_fraction(self) -> f64 {
318
15506
        self.value.into() / 100.0
319
15506
    }
320

            
321
    /// Return this value as a percentage.
322
    ///
323
    /// ```
324
    /// use tor_units::Percentage;
325
    /// let pct_200 = Percentage::<u8>::new(200);
326
    /// let pct_100 = Percentage::<u8>::new(100);
327
    /// let pct_50 = Percentage::<u8>::new(50);
328
    ///
329
    /// assert_eq!(pct_200.as_percent(), 200);
330
    /// assert_eq!(pct_100.as_percent(), 100);
331
    /// assert_eq!(pct_50.as_percent(), 50);
332
    /// ```
333
549
    pub fn as_percent(self) -> T {
334
549
        self.value
335
549
    }
336
}
337

            
338
impl<const H: i32, const L: i32> TryFrom<i32> for Percentage<BoundedInt32<H, L>> {
339
    type Error = Error;
340
179224
    fn try_from(v: i32) -> Result<Self, Error> {
341
179224
        Ok(Percentage::new(v.try_into()?))
342
179224
    }
343
}
344

            
345
// TODO: There is a bunch of code duplication among these "IntegerTimeUnits"
346
// section.
347

            
348
#[derive(
349
    Add, Copy, Clone, Mul, Div, From, FromStr, Display, Debug, PartialEq, Eq, Ord, PartialOrd, Hash,
350
)]
351
/// This type represents an integer number of milliseconds.
352
///
353
/// The underlying type should usually implement `TryInto<u64>`.
354
pub struct IntegerMilliseconds<T> {
355
    /// Interior Value. Should implement `TryInto<u64>` to be useful.
356
    value: T,
357
}
358

            
359
impl<T> IntegerMilliseconds<T> {
360
    /// Public Constructor
361
120383
    pub fn new(value: T) -> Self {
362
120383
        IntegerMilliseconds { value }
363
120383
    }
364

            
365
    /// Deconstructor
366
    ///
367
    /// Use only in contexts where it's no longer possible to
368
    /// use the Rust type system to ensure secs vs ms vs us correctness.
369
9956
    pub fn as_millis(self) -> T {
370
9956
        self.value
371
9956
    }
372

            
373
    /// Map the inner value (useful for conversion)
374
    ///
375
    /// # Example
376
    ///
377
    /// ```
378
    /// use tor_units::{BoundedInt32, IntegerMilliseconds};
379
    ///
380
    /// let value: IntegerMilliseconds<i32> = 42.into();
381
    /// let value: IntegerMilliseconds<BoundedInt32<0,1000>>
382
    ///     = value.try_map(TryInto::try_into).unwrap();
383
    /// ```
384
3466
    pub fn try_map<U, F, E>(self, f: F) -> Result<IntegerMilliseconds<U>, E>
385
3466
    where
386
3466
        F: FnOnce(T) -> Result<U, E>,
387
    {
388
3466
        Ok(IntegerMilliseconds::new(f(self.value)?))
389
3466
    }
390
}
391

            
392
impl<T: TryInto<u64>> TryFrom<IntegerMilliseconds<T>> for Duration {
393
    type Error = <T as TryInto<u64>>::Error;
394
16
    fn try_from(val: IntegerMilliseconds<T>) -> Result<Self, <T as TryInto<u64>>::Error> {
395
16
        Ok(Self::from_millis(val.value.try_into()?))
396
16
    }
397
}
398

            
399
impl<const H: i32, const L: i32> TryFrom<i32> for IntegerMilliseconds<BoundedInt32<H, L>> {
400
    type Error = Error;
401
114053
    fn try_from(v: i32) -> Result<Self, Error> {
402
114053
        Ok(IntegerMilliseconds::new(v.try_into()?))
403
114053
    }
404
}
405

            
406
#[derive(
407
    Add, Copy, Clone, Mul, Div, From, FromStr, Display, Debug, PartialEq, Eq, Ord, PartialOrd, Hash,
408
)]
409
/// This type represents an integer number of seconds.
410
///
411
/// The underlying type should usually implement `TryInto<u64>`.
412
pub struct IntegerSeconds<T> {
413
    /// Interior Value. Should implement `TryInto<u64>` to be useful.
414
    value: T,
415
}
416

            
417
impl<T> IntegerSeconds<T> {
418
    /// Public Constructor
419
211912
    pub fn new(value: T) -> Self {
420
211912
        IntegerSeconds { value }
421
211912
    }
422

            
423
    /// Deconstructor
424
    ///
425
    /// Use only in contexts where it's no longer possible to
426
    /// use the Rust type system to ensure secs vs ms vs us correctness.
427
    pub fn as_secs(self) -> T {
428
        self.value
429
    }
430

            
431
    /// Map the inner value (useful for conversion)
432
    ///
433
    /// ```
434
    /// use tor_units::{BoundedInt32, IntegerSeconds};
435
    ///
436
    /// let value: IntegerSeconds<i32> = 42.into();
437
    /// let value: IntegerSeconds<BoundedInt32<0,1000>>
438
    ///     = value.try_map(TryInto::try_into).unwrap();
439
    /// ```
440
    pub fn try_map<U, F, E>(self, f: F) -> Result<IntegerSeconds<U>, E>
441
    where
442
        F: FnOnce(T) -> Result<U, E>,
443
    {
444
        Ok(IntegerSeconds::new(f(self.value)?))
445
    }
446
}
447

            
448
impl<T: TryInto<u64>> TryFrom<IntegerSeconds<T>> for Duration {
449
    type Error = <T as TryInto<u64>>::Error;
450
16945
    fn try_from(val: IntegerSeconds<T>) -> Result<Self, <T as TryInto<u64>>::Error> {
451
16945
        Ok(Self::from_secs(val.value.try_into()?))
452
16945
    }
453
}
454

            
455
impl<const H: i32, const L: i32> TryFrom<i32> for IntegerSeconds<BoundedInt32<H, L>> {
456
    type Error = Error;
457
211811
    fn try_from(v: i32) -> Result<Self, Error> {
458
211811
        Ok(IntegerSeconds::new(v.try_into()?))
459
211811
    }
460
}
461

            
462
#[derive(Deserialize, Serialize)] //
463
#[derive(Copy, Clone, From, FromStr, Display, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
464
/// This type represents an integer number of minutes.
465
///
466
/// The underlying type should usually implement `TryInto<u64>`.
467
pub struct IntegerMinutes<T> {
468
    /// Interior Value. Should Implement `TryInto<u64>` to be useful.
469
    value: T,
470
}
471

            
472
impl<T> IntegerMinutes<T> {
473
    /// Public Constructor
474
46798
    pub fn new(value: T) -> Self {
475
46798
        IntegerMinutes { value }
476
46798
    }
477

            
478
    /// Deconstructor
479
    ///
480
    /// Use only in contexts where it's no longer possible to
481
    /// use the Rust type system to ensure secs vs ms vs us correctness.
482
292662
    pub fn as_minutes(self) -> T {
483
292662
        self.value
484
292662
    }
485

            
486
    /// Map the inner value (useful for conversion)
487
    ///
488
    /// ```
489
    /// use tor_units::{BoundedInt32, IntegerMinutes};
490
    ///
491
    /// let value: IntegerMinutes<i32> = 42.into();
492
    /// let value: IntegerMinutes<BoundedInt32<0,1000>>
493
    ///     = value.try_map(TryInto::try_into).unwrap();
494
    /// ```
495
    pub fn try_map<U, F, E>(self, f: F) -> Result<IntegerMinutes<U>, E>
496
    where
497
        F: FnOnce(T) -> Result<U, E>,
498
    {
499
        Ok(IntegerMinutes::new(f(self.value)?))
500
    }
501
}
502

            
503
impl<T: TryInto<u64>> TryFrom<IntegerMinutes<T>> for Duration {
504
    type Error = Error;
505
19404
    fn try_from(val: IntegerMinutes<T>) -> Result<Self, Error> {
506
        /// Number of seconds in a single minute.
507
        const SECONDS_PER_MINUTE: u64 = 60;
508
19404
        let minutes: u64 = val.value.try_into().map_err(|_| Error::Overflow)?;
509
19403
        let seconds = minutes
510
19403
            .checked_mul(SECONDS_PER_MINUTE)
511
19403
            .ok_or(Error::Overflow)?;
512
19402
        Ok(Self::from_secs(seconds))
513
19404
    }
514
}
515

            
516
impl<const H: i32, const L: i32> TryFrom<i32> for IntegerMinutes<BoundedInt32<H, L>> {
517
    type Error = Error;
518
16294
    fn try_from(v: i32) -> Result<Self, Error> {
519
16294
        Ok(IntegerMinutes::new(v.try_into()?))
520
16294
    }
521
}
522

            
523
#[derive(Copy, Clone, From, FromStr, Display, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
524
/// This type represents an integer number of days.
525
///
526
/// The underlying type should usually implement `TryInto<u64>`.
527
pub struct IntegerDays<T> {
528
    /// Interior Value. Should Implement `TryInto<u64>` to be useful.
529
    value: T,
530
}
531

            
532
impl<T> IntegerDays<T> {
533
    /// Public Constructor
534
48887
    pub fn new(value: T) -> Self {
535
48887
        IntegerDays { value }
536
48887
    }
537

            
538
    /// Deconstructor
539
    ///
540
    /// Use only in contexts where it's no longer possible to
541
    /// use the Rust type system to ensure secs vs ms vs us correctness.
542
    pub fn as_days(self) -> T {
543
        self.value
544
    }
545

            
546
    /// Map the inner value (useful for conversion)
547
    ///
548
    /// ```
549
    /// use tor_units::{BoundedInt32, IntegerDays};
550
    ///
551
    /// let value: IntegerDays<i32> = 42.into();
552
    /// let value: IntegerDays<BoundedInt32<0,1000>>
553
    ///     = value.try_map(TryInto::try_into).unwrap();
554
    /// ```
555
    pub fn try_map<U, F, E>(self, f: F) -> Result<IntegerDays<U>, E>
556
    where
557
        F: FnOnce(T) -> Result<U, E>,
558
    {
559
        Ok(IntegerDays::new(f(self.value)?))
560
    }
561
}
562

            
563
impl<T: TryInto<u64>> TryFrom<IntegerDays<T>> for Duration {
564
    type Error = Error;
565
5646
    fn try_from(val: IntegerDays<T>) -> Result<Self, Error> {
566
        /// Number of seconds in a single day.
567
        const SECONDS_PER_DAY: u64 = 86400;
568
5646
        let days: u64 = val.value.try_into().map_err(|_| Error::Overflow)?;
569
5645
        let seconds = days.checked_mul(SECONDS_PER_DAY).ok_or(Error::Overflow)?;
570
5644
        Ok(Self::from_secs(seconds))
571
5646
    }
572
}
573

            
574
impl<const H: i32, const L: i32> TryFrom<i32> for IntegerDays<BoundedInt32<H, L>> {
575
    type Error = Error;
576
48880
    fn try_from(v: i32) -> Result<Self, Error> {
577
48880
        Ok(IntegerDays::new(v.try_into()?))
578
48880
    }
579
}
580

            
581
/// A SendMe Version
582
///
583
/// DOCDOC: Explain why this needs to have its own type, or remove it.
584
#[derive(Clone, Copy, From, FromStr, Display, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
585
pub struct SendMeVersion(u8);
586

            
587
impl SendMeVersion {
588
    /// Public Constructor
589
36434
    pub fn new(value: u8) -> Self {
590
36434
        SendMeVersion(value)
591
36434
    }
592

            
593
    /// Helper
594
242
    pub fn get(&self) -> u8 {
595
242
        self.0
596
242
    }
597
}
598

            
599
impl TryFrom<i32> for SendMeVersion {
600
    type Error = Error;
601
36193
    fn try_from(v: i32) -> Result<Self, Error> {
602
36193
        let val_u8 = BoundedInt32::<0, 255>::checked_new(v)?;
603
36193
        Ok(SendMeVersion::new(val_u8.get() as u8))
604
36193
    }
605
}
606

            
607
/// Tests that check whether some code fails to compile as intended.
608
// Unfortunately we can't check the reason that it fails to compile,
609
// so these tests could become stale if the API is changed.
610
// In the future, we may be able to use the (currently nightly):
611
// https://doc.rust-lang.org/rustdoc/unstable-features.html?highlight=compile_fail#error-numbers-for-compile-fail-doctests
612
#[cfg(doc)]
613
#[doc(hidden)]
614
mod compile_fail_tests {
615
    /// ```compile_fail
616
    /// use tor_units::BoundedInt32;
617
    /// let _: BoundedInt32<10, 5> = BoundedInt32::saturating_new(7);
618
    /// ```
619
    fn uninhabited_saturating_new() {}
620

            
621
    /// ```compile_fail
622
    /// use tor_units::BoundedInt32;
623
    /// let _: Result<BoundedInt32<10, 5>, Error> = BoundedInt32::saturating_from_str("7");
624
    /// ```
625
    fn uninhabited_from_string() {}
626
}
627

            
628
#[cfg(test)]
629
mod tests {
630
    #![allow(clippy::unwrap_used)]
631
    use float_cmp::assert_approx_eq;
632

            
633
    use super::*;
634

            
635
    type TestFoo = BoundedInt32<1, 5>;
636
    type TestBar = BoundedInt32<-45, 17>;
637

            
638
    //make_parameter_type! {TestFoo(3,)}
639
    #[test]
640
    fn entire_range_parsed() {
641
        let x: TestFoo = "1".parse().unwrap();
642
        assert!(x.get() == 1);
643
        let x: TestFoo = "2".parse().unwrap();
644
        assert!(x.get() == 2);
645
        let x: TestFoo = "3".parse().unwrap();
646
        assert!(x.get() == 3);
647
        let x: TestFoo = "4".parse().unwrap();
648
        assert!(x.get() == 4);
649
        let x: TestFoo = "5".parse().unwrap();
650
        assert!(x.get() == 5);
651
    }
652

            
653
    #[test]
654
    fn saturating() {
655
        let x: TestFoo = TestFoo::saturating_new(1000);
656
        let x_val: i32 = x.into();
657
        assert!(x_val == TestFoo::UPPER);
658
        let x: TestFoo = TestFoo::saturating_new(0);
659
        let x_val: i32 = x.into();
660
        assert!(x_val == TestFoo::LOWER);
661
    }
662
    #[test]
663
    fn saturating_string() {
664
        let x: TestFoo = TestFoo::saturating_from_str("1000").unwrap();
665
        let x_val: i32 = x.into();
666
        assert!(x_val == TestFoo::UPPER);
667
        let x: TestFoo = TestFoo::saturating_from_str("0").unwrap();
668
        let x_val: i32 = x.into();
669
        assert!(x_val == TestFoo::LOWER);
670
    }
671

            
672
    #[test]
673
    fn errors_correct() {
674
        let x: Result<TestBar, Error> = "1000".parse();
675
        assert!(x.unwrap_err() == Error::AboveUpperBound(1000, TestBar::UPPER));
676
        let x: Result<TestBar, Error> = "-1000".parse();
677
        assert!(x.unwrap_err() == Error::BelowLowerBound(-1000, TestBar::LOWER));
678
        let x: Result<TestBar, Error> = "xyz".parse();
679
        assert!(x.unwrap_err() == Error::Unrepresentable);
680
    }
681

            
682
    #[test]
683
    fn display() {
684
        let v = BoundedInt32::<99, 1000>::checked_new(345).unwrap();
685
        assert_eq!(v.to_string(), "345".to_string());
686
    }
687

            
688
    #[test]
689
    #[should_panic]
690
    fn checked_too_high() {
691
        let _: TestBar = "1000".parse().unwrap();
692
    }
693

            
694
    #[test]
695
    #[should_panic]
696
    fn checked_too_low() {
697
        let _: TestBar = "-46".parse().unwrap();
698
    }
699

            
700
    #[test]
701
    fn bounded_to_u64() {
702
        let b: BoundedInt32<-100, 100> = BoundedInt32::checked_new(77).unwrap();
703
        let u: u64 = b.try_into().unwrap();
704
        assert_eq!(u, 77);
705

            
706
        let b: BoundedInt32<-100, 100> = BoundedInt32::checked_new(-77).unwrap();
707
        let u: Result<u64, Error> = b.try_into();
708
        assert!(u.is_err());
709
    }
710

            
711
    #[test]
712
    fn bounded_to_f64() {
713
        let x: BoundedInt32<-100, 100> = BoundedInt32::checked_new(77).unwrap();
714
        let f: f64 = x.into();
715
        assert_approx_eq!(f64, f, 77.0);
716
    }
717

            
718
    #[test]
719
    fn bounded_from_i32() {
720
        let x: Result<BoundedInt32<-100, 100>, _> = 50.try_into();
721
        let y: i32 = x.unwrap().into();
722
        assert_eq!(y, 50);
723

            
724
        let x: Result<BoundedInt32<-100, 100>, _> = 1000.try_into();
725
        assert!(x.is_err());
726
    }
727

            
728
    #[test]
729
    fn into_bool() {
730
        let zero: BoundedInt32<0, 1> = BoundedInt32::saturating_from(0);
731
        let one: BoundedInt32<0, 1> = BoundedInt32::saturating_from(1);
732

            
733
        let f: bool = zero.into();
734
        let t: bool = one.into();
735
        assert!(!f);
736
        assert!(t);
737
    }
738

            
739
    #[test]
740
    fn into_u8() {
741
        let zero: BoundedInt32<0, 255> = BoundedInt32::saturating_from(0);
742
        let one: BoundedInt32<0, 255> = BoundedInt32::saturating_from(1);
743
        let ninety: BoundedInt32<0, 255> = BoundedInt32::saturating_from(90);
744
        let max: BoundedInt32<0, 255> = BoundedInt32::saturating_from(1000);
745

            
746
        let a: u8 = zero.into();
747
        let b: u8 = one.into();
748
        let c: u8 = ninety.into();
749
        let d: u8 = max.into();
750

            
751
        assert_eq!(a, 0);
752
        assert_eq!(b, 1);
753
        assert_eq!(c, 90);
754
        assert_eq!(d, 255);
755
    }
756

            
757
    #[test]
758
    fn into_u32() {
759
        let zero: BoundedInt32<0, 1000> = BoundedInt32::saturating_from(0);
760
        let one: BoundedInt32<0, 1000> = BoundedInt32::saturating_from(1);
761
        let ninety: BoundedInt32<0, 1000> = BoundedInt32::saturating_from(90);
762
        let max: BoundedInt32<0, 1000> = BoundedInt32::saturating_from(1000);
763

            
764
        assert_eq!(u32::from(zero), 0);
765
        assert_eq!(u32::from(one), 1);
766
        assert_eq!(u32::from(ninety), 90);
767
        assert_eq!(u32::from(max), 1000);
768

            
769
        let zero: BoundedInt32<1, 1000> = BoundedInt32::saturating_from(0);
770
        let one: BoundedInt32<1, 1000> = BoundedInt32::saturating_from(1);
771
        let ninety: BoundedInt32<1, 1000> = BoundedInt32::saturating_from(90);
772
        let max: BoundedInt32<1, 1000> = BoundedInt32::saturating_from(1000);
773

            
774
        assert_eq!(u32::from(zero), 1);
775
        assert_eq!(u32::from(one), 1);
776
        assert_eq!(u32::from(ninety), 90);
777
        assert_eq!(u32::from(max), 1000);
778
    }
779

            
780
    #[test]
781
    fn try_into_usize() {
782
        let b0: BoundedInt32<-10, 300> = BoundedInt32::saturating_from(0);
783
        let b100: BoundedInt32<-10, 300> = BoundedInt32::saturating_from(100);
784
        let bn5: BoundedInt32<-10, 300> = BoundedInt32::saturating_from(-5);
785
        assert_eq!(usize::try_from(b0), Ok(0_usize));
786
        assert_eq!(usize::try_from(b100), Ok(100_usize));
787
        assert_eq!(usize::try_from(bn5), Err(Error::Negative));
788
    }
789

            
790
    #[test]
791
    fn percents() {
792
        type Pct = Percentage<u8>;
793
        let p = Pct::new(100);
794
        assert_eq!(p.as_percent(), 100);
795
        assert_approx_eq!(f64, p.as_fraction(), 1.0);
796

            
797
        let p = Pct::new(0);
798
        assert_eq!(p.as_percent(), 0);
799
        assert_approx_eq!(f64, p.as_fraction(), 0.0);
800

            
801
        let p = Pct::new(25);
802
        assert_eq!(p.as_percent(), 25);
803
        assert_eq!(p.clone(), p);
804
        assert_approx_eq!(f64, p.as_fraction(), 0.25);
805

            
806
        type BPct = Percentage<BoundedInt32<0, 100>>;
807
        assert_eq!(BPct::try_from(99).unwrap().as_percent().get(), 99);
808
    }
809

            
810
    #[test]
811
    fn milliseconds() {
812
        type Msec = IntegerMilliseconds<i32>;
813

            
814
        let ms = Msec::new(500);
815
        let d: Result<Duration, _> = ms.try_into();
816
        assert_eq!(d.unwrap(), Duration::from_millis(500));
817
        assert_eq!(Duration::try_from(ms * 2).unwrap(), Duration::from_secs(1));
818

            
819
        let ms = Msec::new(-100);
820
        let d: Result<Duration, _> = ms.try_into();
821
        assert!(d.is_err());
822

            
823
        type BMSec = IntegerMilliseconds<BoundedInt32<0, 1000>>;
824
        let half_sec = BMSec::try_from(500).unwrap();
825
        assert_eq!(
826
            Duration::try_from(half_sec).unwrap(),
827
            Duration::from_millis(500)
828
        );
829
        assert!(BMSec::try_from(1001).is_err());
830
    }
831

            
832
    #[test]
833
    fn seconds() {
834
        type Sec = IntegerSeconds<i32>;
835

            
836
        let ms = Sec::new(500);
837
        let d: Result<Duration, _> = ms.try_into();
838
        assert_eq!(d.unwrap(), Duration::from_secs(500));
839

            
840
        let ms = Sec::new(-100);
841
        let d: Result<Duration, _> = ms.try_into();
842
        assert!(d.is_err());
843

            
844
        type BSec = IntegerSeconds<BoundedInt32<0, 3600>>;
845
        let half_hour = BSec::try_from(1800).unwrap();
846
        assert_eq!(
847
            Duration::try_from(half_hour).unwrap(),
848
            Duration::from_secs(1800)
849
        );
850
        assert!(BSec::try_from(9999).is_err());
851
        assert_eq!(half_hour.clone(), half_hour);
852
    }
853

            
854
    #[test]
855
    fn minutes() {
856
        type Min = IntegerMinutes<i32>;
857

            
858
        let t = Min::new(500);
859
        let d: Duration = t.try_into().unwrap();
860
        assert_eq!(d, Duration::from_secs(500 * 60));
861

            
862
        let t = Min::new(-100);
863
        let d: Result<Duration, _> = t.try_into();
864
        assert_eq!(d, Err(Error::Overflow));
865

            
866
        let t = IntegerMinutes::<u64>::new(u64::MAX);
867
        let d: Result<Duration, _> = t.try_into();
868
        assert_eq!(d, Err(Error::Overflow));
869

            
870
        type BMin = IntegerMinutes<BoundedInt32<10, 30>>;
871
        assert_eq!(
872
            BMin::new(17_i32.try_into().unwrap()),
873
            BMin::try_from(17).unwrap()
874
        );
875
    }
876

            
877
    #[test]
878
    fn days() {
879
        type Days = IntegerDays<i32>;
880

            
881
        let t = Days::new(500);
882
        let d: Duration = t.try_into().unwrap();
883
        assert_eq!(d, Duration::from_secs(500 * 86400));
884

            
885
        let t = Days::new(-100);
886
        let d: Result<Duration, _> = t.try_into();
887
        assert_eq!(d, Err(Error::Overflow));
888

            
889
        let t = IntegerDays::<u64>::new(u64::MAX);
890
        let d: Result<Duration, _> = t.try_into();
891
        assert_eq!(d, Err(Error::Overflow));
892

            
893
        type BDays = IntegerDays<BoundedInt32<10, 30>>;
894
        assert_eq!(
895
            BDays::new(17_i32.try_into().unwrap()),
896
            BDays::try_from(17).unwrap()
897
        );
898
    }
899

            
900
    #[test]
901
    fn sendme() {
902
        let smv = SendMeVersion::new(5);
903
        assert_eq!(smv.get(), 5);
904
        assert_eq!(smv.clone().get(), 5);
905
        assert_eq!(smv, SendMeVersion::try_from(5).unwrap());
906
    }
907
}