num_primitive/number.rs
1use crate::{PrimitiveBytes, PrimitiveError};
2
3trait Sealed {}
4struct SealedToken;
5
6/// Trait for all primitive [numeric types].
7///
8/// This encapsulates trait implementations and inherent methods that are common among all of the
9/// primitive numeric types: [`f32`], [`f64`], [`i8`], [`i16`], [`i32`], [`i64`], [`i128`],
10/// [`isize`], [`u8`], [`u16`], [`u32`], [`u64`], [`u128`], and [`usize`]. Unstable types like
11/// [`f16`] and [`f128`] will be added once they are stabilized.
12///
13/// See the corresponding items on the individual types for more documentation and examples.
14///
15/// This trait is sealed with a private trait to prevent downstream implementations, so we may
16/// continue to expand along with the standard library without worrying about breaking changes for
17/// implementors.
18///
19/// [numeric types]: https://doc.rust-lang.org/reference/types/numeric.html
20///
21/// # Examples
22///
23/// ```
24/// use num_primitive::{PrimitiveNumber, PrimitiveNumberRef};
25///
26/// fn dot_product<T: PrimitiveNumber>(a: &[T], b: &[T]) -> T {
27/// assert_eq!(a.len(), b.len());
28/// // Note that we have to dereference to use `T: Mul<&T>`
29/// core::iter::zip(a, b).map(|(a, b)| (*a) * b).sum()
30/// }
31///
32/// fn dot_product_ref<T>(a: &[T], b: &[T]) -> T
33/// where
34/// T: PrimitiveNumber,
35/// for<'a> &'a T: PrimitiveNumberRef<T>,
36/// {
37/// assert_eq!(a.len(), b.len());
38/// // In this case we can use `&T: Mul`
39/// core::iter::zip(a, b).map(|(a, b)| a * b).sum()
40/// }
41///
42/// assert_eq!(dot_product::<i32>(&[1, 3, -5], &[4, -2, -1]), 3);
43/// assert_eq!(dot_product_ref::<f64>(&[1., 3., -5.], &[4., -2., -1.]), 3.);
44/// ```
45#[expect(private_bounds)]
46pub trait PrimitiveNumber:
47 'static
48 + Sealed
49 + PrimitiveNumberAs<f32>
50 + PrimitiveNumberAs<f64>
51 + PrimitiveNumberAs<i8>
52 + PrimitiveNumberAs<i16>
53 + PrimitiveNumberAs<i32>
54 + PrimitiveNumberAs<i64>
55 + PrimitiveNumberAs<i128>
56 + PrimitiveNumberAs<isize>
57 + PrimitiveNumberAs<u8>
58 + PrimitiveNumberAs<u16>
59 + PrimitiveNumberAs<u32>
60 + PrimitiveNumberAs<u64>
61 + PrimitiveNumberAs<u128>
62 + PrimitiveNumberAs<usize>
63 + core::cmp::PartialEq
64 + core::cmp::PartialOrd
65 + core::convert::From<bool>
66 + core::default::Default
67 + core::fmt::Debug
68 + core::fmt::Display
69 + core::fmt::LowerExp
70 + core::fmt::UpperExp
71 + core::iter::Product<Self>
72 + core::iter::Sum<Self>
73 + core::marker::Copy
74 + core::marker::Send
75 + core::marker::Sync
76 + core::marker::Unpin
77 + core::ops::Add<Self, Output = Self>
78 + core::ops::AddAssign<Self>
79 + core::ops::Div<Self, Output = Self>
80 + core::ops::DivAssign<Self>
81 + core::ops::Mul<Self, Output = Self>
82 + core::ops::MulAssign<Self>
83 + core::ops::Rem<Self, Output = Self>
84 + core::ops::RemAssign<Self>
85 + core::ops::Sub<Self, Output = Self>
86 + core::ops::SubAssign<Self>
87 + core::panic::RefUnwindSafe
88 + core::panic::UnwindSafe
89 + core::str::FromStr<Err: PrimitiveError>
90 + for<'a> core::iter::Product<&'a Self>
91 + for<'a> core::iter::Sum<&'a Self>
92 + for<'a> core::ops::Add<&'a Self, Output = Self>
93 + for<'a> core::ops::AddAssign<&'a Self>
94 + for<'a> core::ops::Div<&'a Self, Output = Self>
95 + for<'a> core::ops::DivAssign<&'a Self>
96 + for<'a> core::ops::Mul<&'a Self, Output = Self>
97 + for<'a> core::ops::MulAssign<&'a Self>
98 + for<'a> core::ops::Rem<&'a Self, Output = Self>
99 + for<'a> core::ops::RemAssign<&'a Self>
100 + for<'a> core::ops::Sub<&'a Self, Output = Self>
101 + for<'a> core::ops::SubAssign<&'a Self>
102{
103 /// An array of bytes used by methods like [`from_be_bytes`][Self::from_be_bytes] and
104 /// [`to_be_bytes`][Self::to_be_bytes]. It is effectively `[u8; size_of::<Self>()]`.
105 type Bytes: PrimitiveBytes;
106
107 /// Creates a number from its representation as a byte array in big endian.
108 fn from_be_bytes(bytes: Self::Bytes) -> Self;
109
110 /// Creates a number from its representation as a byte array in little endian.
111 fn from_le_bytes(bytes: Self::Bytes) -> Self;
112
113 /// Creates a number from its representation as a byte array in native endian.
114 fn from_ne_bytes(bytes: Self::Bytes) -> Self;
115
116 /// Calculates the midpoint (average) between `self` and `other`.
117 fn midpoint(self, other: Self) -> Self;
118
119 /// Returns the memory representation of this number as a byte array in little-endian order.
120 fn to_be_bytes(self) -> Self::Bytes;
121
122 /// Returns the memory representation of this number as a byte array in big-endian order.
123 fn to_le_bytes(self) -> Self::Bytes;
124
125 /// Returns the memory representation of this number as a byte array in native-endian order.
126 fn to_ne_bytes(self) -> Self::Bytes;
127
128 /// Creates a number using a type cast, `value as Self`.
129 ///
130 /// Note: unlike other `num-primitive` methods, there is no inherent method by this name on the
131 /// actual types.
132 fn as_from<T>(value: T) -> Self
133 where
134 Self: PrimitiveNumberAs<T>,
135 {
136 <Self as PrimitiveNumberAs<T>>::__as_from(value, SealedToken)
137 }
138
139 /// Converts this number with a type cast, `self as T`.
140 ///
141 /// Note: unlike other `num-primitive` methods, there is no inherent method by this name on the
142 /// actual types.
143 fn as_to<T>(self) -> T
144 where
145 Self: PrimitiveNumberAs<T>,
146 {
147 <Self as PrimitiveNumberAs<T>>::__as_to(self, SealedToken)
148 }
149}
150
151/// Trait for references to primitive numbers ([`PrimitiveNumber`]).
152///
153/// This enables traits like the standard operators in generic code,
154/// e.g. `where &T: PrimitiveNumberRef<T>`.
155#[expect(private_bounds)]
156pub trait PrimitiveNumberRef<T>:
157 Sealed
158 + core::borrow::Borrow<T>
159 + core::cmp::PartialEq
160 + core::cmp::PartialOrd
161 + core::fmt::Debug
162 + core::fmt::Display
163 + core::fmt::LowerExp
164 + core::fmt::UpperExp
165 + core::marker::Copy
166 + core::marker::Send
167 + core::marker::Sync
168 + core::marker::Unpin
169 + core::ops::Add<T, Output = T>
170 + core::ops::Deref<Target = T>
171 + core::ops::Div<T, Output = T>
172 + core::ops::Mul<T, Output = T>
173 + core::ops::Rem<T, Output = T>
174 + core::ops::Sub<T, Output = T>
175 + core::panic::RefUnwindSafe
176 + core::panic::UnwindSafe
177 + for<'a> core::ops::Add<&'a T, Output = T>
178 + for<'a> core::ops::Div<&'a T, Output = T>
179 + for<'a> core::ops::Mul<&'a T, Output = T>
180 + for<'a> core::ops::Rem<&'a T, Output = T>
181 + for<'a> core::ops::Sub<&'a T, Output = T>
182{
183}
184
185/// Trait for numeric conversions supported by the [`as`] keyword.
186///
187/// This is effectively the same as the [type cast] expression `self as N`, implemented for all
188/// combinations of [`PrimitiveNumber`].
189///
190/// [`as`]: https://doc.rust-lang.org/std/keyword.as.html
191/// [type cast]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
192///
193/// # Examples
194///
195/// `PrimitiveNumberAs<{number}>` is a supertrait of [`PrimitiveNumber`] for all primitive floats
196/// and integers, so you do not need to use this trait directly when converting concrete types.
197///
198/// ```
199/// use num_primitive::PrimitiveNumber;
200///
201/// // Clamp any number to the interval 0..=100, unless it is NaN.
202/// fn clamp_percentage<Number: PrimitiveNumber>(x: Number) -> Number {
203/// let clamped = x.as_to::<f64>().clamp(0.0, 100.0);
204/// Number::as_from(clamped)
205/// }
206///
207/// assert_eq!(clamp_percentage(-42_i8), 0_i8);
208/// assert_eq!(clamp_percentage(42_u128), 42_u128);
209/// assert_eq!(clamp_percentage(1e100_f64), 100_f64);
210/// assert!(clamp_percentage(f32::NAN).is_nan());
211/// ```
212///
213/// However, if the other type is also generic, an explicit type constraint is needed.
214///
215/// ```
216/// use num_primitive::{PrimitiveNumber, PrimitiveNumberAs};
217///
218/// fn clamp_any<Number, Limit>(x: Number, min: Limit, max: Limit) -> Number
219/// where
220/// Number: PrimitiveNumber + PrimitiveNumberAs<Limit>,
221/// Limit: PartialOrd,
222/// {
223/// assert!(min <= max);
224/// let y = x.as_to::<Limit>();
225/// if y <= min {
226/// Number::as_from(min)
227/// } else if y >= max {
228/// Number::as_from(max)
229/// } else {
230/// x
231/// }
232/// }
233///
234/// assert_eq!(clamp_any(1.23, 0_i8, 10_i8), 1.23);
235/// assert_eq!(clamp_any(1.23, -1_i8, 1_i8), 1.0);
236/// assert_eq!(clamp_any(i128::MAX, 0.0, 1e100), i128::MAX);
237/// ```
238pub trait PrimitiveNumberAs<T> {
239 #[doc(hidden)]
240 #[expect(private_interfaces)]
241 fn __as_from(x: T, _: SealedToken) -> Self;
242
243 #[doc(hidden)]
244 #[expect(private_interfaces)]
245 fn __as_to(x: Self, _: SealedToken) -> T;
246}
247
248macro_rules! impl_primitive {
249 ($($Number:ident),+) => {$(
250 impl Sealed for $Number {}
251 impl Sealed for &$Number {}
252
253 impl PrimitiveNumber for $Number {
254 type Bytes = [u8; size_of::<Self>()];
255
256 forward! {
257 fn from_be_bytes(bytes: Self::Bytes) -> Self;
258 fn from_le_bytes(bytes: Self::Bytes) -> Self;
259 fn from_ne_bytes(bytes: Self::Bytes) -> Self;
260 }
261 forward! {
262 fn midpoint(self, other: Self) -> Self;
263 fn to_be_bytes(self) -> Self::Bytes;
264 fn to_le_bytes(self) -> Self::Bytes;
265 fn to_ne_bytes(self) -> Self::Bytes;
266 }
267 }
268
269 impl PrimitiveNumberRef<$Number> for &$Number {}
270
271 impl_primitive!($Number as f32, f64);
272 impl_primitive!($Number as i8, i16, i32, i64, i128, isize);
273 impl_primitive!($Number as u8, u16, u32, u64, u128, usize);
274 )+};
275
276 ($Number:ident as $($Other:ident),+) => {$(
277 impl PrimitiveNumberAs<$Other> for $Number {
278 #[inline]
279 #[expect(private_interfaces)]
280 fn __as_from(x: $Other, _: SealedToken) -> Self {
281 x as Self
282 }
283
284 #[inline]
285 #[expect(private_interfaces)]
286 fn __as_to(x: Self, _: SealedToken) -> $Other {
287 x as $Other
288 }
289 }
290 )+}
291}
292
293impl_primitive!(f32, f64);
294impl_primitive!(i8, i16, i32, i64, i128, isize);
295impl_primitive!(u8, u16, u32, u64, u128, usize);