integer_result/
lib.rs

1//! A Rust library for converting the primitive and non-zero integer types to a `Result` through comparison.
2
3#![no_std]
4
5/// `use` this trait to access `ok_less`, `ok_equal`, and `ok_greater` for all primitive and non-zero integer types.
6pub trait Ext
7where
8  Self: Sized + Eq + Ord,
9{
10  /// Returns an `Ok` holding the integer if less than the other integer `val`.
11  /// Otherwise, returns and `Err` holding the integer.
12  ///
13  /// # Examples
14  /// ```
15  /// use integer_result::Ext;
16  ///
17  /// assert_eq!(1.ok_less(2), Ok(1));
18  /// assert_eq!(1.ok_less(0), Err(1));
19  /// ```
20  #[inline]
21  fn ok_less(self, val: Self) -> Result<Self, Self> {
22    if self < val {
23      Ok(self)
24    } else {
25      Err(self)
26    }
27  }
28
29  /// Returns an `Ok` holding the integer if equal to the other integer `val`.
30  /// Otherwise, returns an `Err` holding the integer.
31  ///
32  /// # Examples
33  /// ```
34  /// use integer_result::Ext;
35  ///
36  /// assert_eq!(1.ok_equal(1), Ok(1));
37  /// assert_eq!(1.ok_equal(0), Err(1));
38  /// ```
39  #[inline]
40  fn ok_equal(self, val: Self) -> Result<Self, Self> {
41    if self == val {
42      Ok(self)
43    } else {
44      Err(self)
45    }
46  }
47
48  /// Returns an `Ok` holding the integer if greater than the other integer `val`.
49  /// Otherwise, returns and `Err` holding the integer.
50  ///
51  /// # Examples
52  /// ```
53  /// use integer_result::Ext;
54  ///
55  /// assert_eq!(1.ok_greater(-1), Ok(1));
56  /// assert_eq!(1.ok_greater(1), Err(1));
57  /// ```
58  #[inline]
59  fn ok_greater(self, val: Self) -> Result<Self, Self> {
60    if self > val {
61      Ok(self)
62    } else {
63      Err(self)
64    }
65  }
66}
67
68impl Ext for i8 {}
69impl Ext for i16 {}
70impl Ext for i32 {}
71impl Ext for i64 {}
72impl Ext for i128 {}
73impl Ext for isize {}
74impl Ext for u8 {}
75impl Ext for u16 {}
76impl Ext for u32 {}
77impl Ext for u64 {}
78impl Ext for u128 {}
79impl Ext for usize {}
80
81mod non_zero_impl {
82  use core::num::*;
83  use crate::Ext;
84
85  impl Ext for NonZeroI8 {}
86  impl Ext for NonZeroI16 {}
87  impl Ext for NonZeroI32 {}
88  impl Ext for NonZeroI64 {}
89  impl Ext for NonZeroI128 {}
90  impl Ext for NonZeroIsize {}
91  impl Ext for NonZeroU8 {}
92  impl Ext for NonZeroU16 {}
93  impl Ext for NonZeroU32 {}
94  impl Ext for NonZeroU64 {}
95  impl Ext for NonZeroU128 {}
96  impl Ext for NonZeroUsize {}
97}
98
99#[cfg(feature="non_zero_impl")]
100pub use non_zero_impl::*;
101