1use core::num::Wrapping;
2use core::{f32, f64};
3#[cfg(has_i128)]
4use core::{i128, u128};
5use core::{i16, i32, i64, i8, isize};
6use core::{u16, u32, u64, u8, usize};
7
8pub trait Bounded {
10 fn min_value() -> Self;
13 fn max_value() -> Self;
15}
16
17macro_rules! bounded_impl {
18 ($t:ty, $min:expr, $max:expr) => {
19 impl Bounded for $t {
20 #[inline]
21 fn min_value() -> $t {
22 $min
23 }
24
25 #[inline]
26 fn max_value() -> $t {
27 $max
28 }
29 }
30 };
31}
32
33bounded_impl!(usize, usize::MIN, usize::MAX);
34bounded_impl!(u8, u8::MIN, u8::MAX);
35bounded_impl!(u16, u16::MIN, u16::MAX);
36bounded_impl!(u32, u32::MIN, u32::MAX);
37bounded_impl!(u64, u64::MIN, u64::MAX);
38#[cfg(has_i128)]
39bounded_impl!(u128, u128::MIN, u128::MAX);
40
41bounded_impl!(isize, isize::MIN, isize::MAX);
42bounded_impl!(i8, i8::MIN, i8::MAX);
43bounded_impl!(i16, i16::MIN, i16::MAX);
44bounded_impl!(i32, i32::MIN, i32::MAX);
45bounded_impl!(i64, i64::MIN, i64::MAX);
46#[cfg(has_i128)]
47bounded_impl!(i128, i128::MIN, i128::MAX);
48
49impl<T: Bounded> Bounded for Wrapping<T> {
50 fn min_value() -> Self {
51 Wrapping(T::min_value())
52 }
53 fn max_value() -> Self {
54 Wrapping(T::max_value())
55 }
56}
57
58bounded_impl!(f32, f32::MIN, f32::MAX);
59
60macro_rules! for_each_tuple_ {
61 ( $m:ident !! ) => (
62 $m! { }
63 );
64 ( $m:ident !! $h:ident, $($t:ident,)* ) => (
65 $m! { $h $($t)* }
66 for_each_tuple_! { $m !! $($t,)* }
67 );
68}
69macro_rules! for_each_tuple {
70 ($m:ident) => {
71 for_each_tuple_! { $m !! A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, }
72 };
73}
74
75macro_rules! bounded_tuple {
76 ( $($name:ident)* ) => (
77 impl<$($name: Bounded,)*> Bounded for ($($name,)*) {
78 #[inline]
79 fn min_value() -> Self {
80 ($($name::min_value(),)*)
81 }
82 #[inline]
83 fn max_value() -> Self {
84 ($($name::max_value(),)*)
85 }
86 }
87 );
88}
89
90for_each_tuple!(bounded_tuple);
91bounded_impl!(f64, f64::MIN, f64::MAX);
92
93#[test]
94fn wrapping_bounded() {
95 macro_rules! test_wrapping_bounded {
96 ($($t:ty)+) => {
97 $(
98 assert_eq!(<Wrapping<$t> as Bounded>::min_value().0, <$t>::min_value());
99 assert_eq!(<Wrapping<$t> as Bounded>::max_value().0, <$t>::max_value());
100 )+
101 };
102 }
103
104 test_wrapping_bounded!(usize u8 u16 u32 u64 isize i8 i16 i32 i64);
105}
106
107#[cfg(has_i128)]
108#[test]
109fn wrapping_bounded_i128() {
110 macro_rules! test_wrapping_bounded {
111 ($($t:ty)+) => {
112 $(
113 assert_eq!(<Wrapping<$t> as Bounded>::min_value().0, <$t>::min_value());
114 assert_eq!(<Wrapping<$t> as Bounded>::max_value().0, <$t>::max_value());
115 )+
116 };
117 }
118
119 test_wrapping_bounded!(u128 i128);
120}
121
122#[test]
123fn wrapping_is_bounded() {
124 fn require_bounded<T: Bounded>(_: &T) {}
125 require_bounded(&Wrapping(42_u32));
126 require_bounded(&Wrapping(-42));
127}