Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License in the LICENSE-APACHE file or at:
4 // https://www.apache.org/licenses/LICENSE-2.0
5
6 //! Type conversion, success expected
7 //!
8 //! This library is written to make numeric type conversions easy. Such
9 //! conversions usually fall into one of the following cases:
10 //!
11 //! - the conversion must preserve values exactly (use [`From`] or [`Into`]
12 //! or [`Conv`] or [`Cast`])
13 //! - the conversion is expected to preserve values exactly, though this is
14 //! not ensured by the types in question (use [`Conv`] or [`Cast`])
15 //! - the conversion could fail and must be checked at run-time (use
16 //! [`TryFrom`] or [`TryInto`] or [`Conv::try_conv`] or [`Cast::try_cast`])
17 //! - the conversion is from floating point values to integers and should
18 //! round to the "nearest" integer (use [`ConvFloat`] or [`CastFloat`])
19 //! - the conversion is from `f32` to `f64` or vice-versa; in this case use of
20 //! `as f32` / `as f64` is likely acceptable since `f32` has special
21 //! representations for non-finite values and conversion to `f64` is exact
22 //! - truncating conversion (modular arithmetic) is desired; in this case `as`
23 //! probably does exactly what you want
24 //! - saturating conversion is desired (less common; not supported here)
25 //!
26 //! If you are wondering "why not just use `as`", there are a few reasons:
27 //!
28 //! - integer conversions may silently truncate
29 //! - integer conversions to/from signed types silently reinterpret
30 //! - prior to Rust 1.45.0 float-to-int conversions were not fully defined;
31 //! since this version they use saturating conversion (NaN converts to 0)
32 //! - you want some assurance (at least in debug builds) that the conversion
33 //! will preserve values correctly without having to proof-read code
34 //!
35 //! When should you *not* use this library?
36 //!
37 //! - Only numeric conversions are supported
38 //! - Conversions from floats do not provide fine control of rounding modes
39 //! - This library has not been thoroughly tested correctness
40 //!
41 //! ## Assertions
42 //!
43 //! All type conversions which are potentially fallible assert on failure in
44 //! debug builds. In release builds assertions may be omitted, thus making
45 //! incorrect conversions possible.
46 //!
47 //! If the `always_assert` feature flag is set, assertions will be turned on in
48 //! all builds. Some additional feature flags are available for finer-grained
49 //! control (see `Cargo.toml`).
50 //!
51 //! ## no_std support
52 //!
53 //! When the crate's default features are disabled (and `std` is not enabled)
54 //! then the library supports `no_std`. In this case, [`ConvFloat`] and
55 //! [`CastFloat`] are only available if the `libm` optional dependency is
56 //! enabled.
57 //!
58 //! [`TryFrom`]: core::convert::TryFrom
59 //! [`TryInto`]: core::convert::TryInto
60
61 #![deny(missing_docs)]
62 #![cfg_attr(not(feature = "std"), no_std)]
63 #![cfg_attr(doc_cfg, feature(doc_cfg))]
64
65 use core::mem::size_of;
66
67 /// Error types for conversions
68 #[derive(Clone, Debug, PartialEq, Eq)]
69 pub enum Error {
70 /// Source value lies outside of target type's range
71 Range,
72 /// Loss of precision and/or outside of target type's range
73 Inexact,
74 }
75
76 #[cfg(feature = "std")]
77 impl std::fmt::Display for Error {
78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79 write!(
80 f,
81 "cast conversion: {}",
82 match self {
83 Error::Range => "source value not in target range",
84 Error::Inexact => "loss of precision or range error",
85 }
86 )
87 }
88 }
89
90 #[cfg(feature = "std")]
91 impl std::error::Error for Error {}
92
93 /// Like [`From`], but supporting potentially-fallible conversions
94 ///
95 /// This trait is intended to replace *many* uses of the `as` keyword for
96 /// numeric conversions, though not all.
97 /// Conversions from floating-point types are excluded since it is very easy to
98 /// (accidentally) produce non-integer values; instead use [`ConvFloat`].
99 ///
100 /// Two methods are provided:
101 ///
102 /// - [`Conv::conv`] is for "success expected" conversions. In debug builds
103 /// and when using the `always_assert` feature flag, inexact conversions
104 /// will panic. In other cases, conversions may produce incorrect values
105 /// (according to the behaviour of `as`). This is similar to the behviour of
106 /// Rust's overflow checks on integer arithmetic, and intended for usage
107 /// when the user is "reasonably sure" that conversion will succeed.
108 /// - [`Conv::try_conv`] is for fallible conversions, and always produces an
109 /// error if the conversion would be inexact.
110 pub trait Conv<T>: Sized {
111 /// Convert from `T` to `Self`
112 fn conv(v: T) -> Self;
113
114 /// Try converting from `T` to `Self`
115 fn try_conv(v: T) -> Result<Self, Error>;
116 }
117
118 impl<T> Conv<T> for T {
119 #[inline]
120 fn conv(v: T) -> Self {
121 v
122 }
123 #[inline]
124 fn try_conv(v: T) -> Result<Self, Error> {
125 Ok(v)
126 }
127 }
128
129 macro_rules! impl_via_from {
130 ($x:ty: $y:ty) => {
131 impl Conv<$x> for $y {
132 #[inline]
133 fn conv(x: $x) -> $y {
134 <$y>::from(x)
135 }
136 #[inline]
137 fn try_conv(x: $x) -> Result<Self, Error> {
138 Ok(<$y>::from(x))
139 }
140 }
141 };
142 ($x:ty: $y:ty, $($yy:ty),+) => {
143 impl_via_from!($x: $y);
144 impl_via_from!($x: $($yy),+);
145 };
146 }
147
148 impl_via_from!(f32: f64);
149 impl_via_from!(i8: f32, f64, i16, i32, i64, i128);
150 impl_via_from!(i16: f32, f64, i32, i64, i128);
151 impl_via_from!(i32: f64, i64, i128);
152 impl_via_from!(i64: i128);
153 impl_via_from!(u8: f32, f64, i16, i32, i64, i128);
154 impl_via_from!(u8: u16, u32, u64, u128);
155 impl_via_from!(u16: f32, f64, i32, i64, i128, u32, u64, u128);
156 impl_via_from!(u32: f64, i64, i128, u64, u128);
157 impl_via_from!(u64: i128, u128);
158
159 macro_rules! impl_via_as_neg_check {
160 ($x:ty: $y:ty) => {
161 impl Conv<$x> for $y {
162 #[inline]
163 fn conv(x: $x) -> $y {
164 #[cfg(any(debug_assertions, feature = "assert_int"))]
165 assert!(
166 x >= 0,
167 "cast x: {} to {}: expected x >= 0, found x = {}",
168 stringify!($x), stringify!($y), x
169 );
170 x as $y
171 }
172 #[inline]
173 fn try_conv(x: $x) -> Result<Self, Error> {
174 if x >= 0 {
175 Ok(x as $y)
176 } else {
177 Err(Error::Range)
178 }
179 }
180 }
181 };
182 ($x:ty: $y:ty, $($yy:ty),+) => {
183 impl_via_as_neg_check!($x: $y);
184 impl_via_as_neg_check!($x: $($yy),+);
185 };
186 }
187
188 impl_via_as_neg_check!(i8: u8, u16, u32, u64, u128);
189 impl_via_as_neg_check!(i16: u16, u32, u64, u128);
190 impl_via_as_neg_check!(i32: u32, u64, u128);
191 impl_via_as_neg_check!(i64: u64, u128);
192 impl_via_as_neg_check!(i128: u128);
193
194 // Assumption: $y::MAX is representable as $x
195 macro_rules! impl_via_as_max_check {
196 ($x:ty: $y:tt) => {
197 impl Conv<$x> for $y {
198 #[inline]
199 fn conv(x: $x) -> $y {
200 #[cfg(any(debug_assertions, feature = "assert_int"))]
201 assert!(
202 x <= core::$y::MAX as $x,
203 "cast x: {} to {}: expected x <= {}, found x = {}",
204 stringify!($x), stringify!($y), core::$y::MAX, x
205 );
206 x as $y
207 }
208 #[inline]
209 fn try_conv(x: $x) -> Result<Self, Error> {
210 if x <= core::$y::MAX as $x {
211 Ok(x as $y)
212 } else {
213 Err(Error::Range)
214 }
215 }
216 }
217 };
218 ($x:ty: $y:tt, $($yy:tt),+) => {
219 impl_via_as_max_check!($x: $y);
220 impl_via_as_max_check!($x: $($yy),+);
221 };
222 }
223
224 impl_via_as_max_check!(u8: i8);
225 impl_via_as_max_check!(u16: i8, i16, u8);
226 impl_via_as_max_check!(u32: i8, i16, i32, u8, u16);
227 impl_via_as_max_check!(u64: i8, i16, i32, i64, u8, u16, u32);
228 impl_via_as_max_check!(u128: i8, i16, i32, i64, i128);
229 impl_via_as_max_check!(u128: u8, u16, u32, u64);
230
231 // Assumption: $y::MAX and $y::MIN are representable as $x
232 macro_rules! impl_via_as_range_check {
233 ($x:ty: $y:tt) => {
234 impl Conv<$x> for $y {
235 #[inline]
236 fn conv(x: $x) -> $y {
237 #[cfg(any(debug_assertions, feature = "assert_int"))]
238 assert!(
239 core::$y::MIN as $x <= x && x <= core::$y::MAX as $x,
240 "cast x: {} to {}: expected {} <= x <= {}, found x = {}",
241 stringify!($x), stringify!($y), core::$y::MIN, core::$y::MAX, x
242 );
243 x as $y
244 }
245 #[inline]
246 fn try_conv(x: $x) -> Result<Self, Error> {
247 if core::$y::MIN as $x <= x && x <= core::$y::MAX as $x {
248 Ok(x as $y)
249 } else {
250 Err(Error::Range)
251 }
252 }
253 }
254 };
255 ($x:ty: $y:tt, $($yy:tt),+) => {
256 impl_via_as_range_check!($x: $y);
257 impl_via_as_range_check!($x: $($yy),+);
258 };
259 }
260
261 impl_via_as_range_check!(i16: i8, u8);
262 impl_via_as_range_check!(i32: i8, i16, u8, u16);
263 impl_via_as_range_check!(i64: i8, i16, i32, u8, u16, u32);
264 impl_via_as_range_check!(i128: i8, i16, i32, i64, u8, u16, u32, u64);
265
266 macro_rules! impl_int_generic {
267 ($x:tt: $y:tt) => {
268 impl Conv<$x> for $y {
269 #[allow(unused_comparisons)]
270 #[inline]
271 fn conv(x: $x) -> $y {
272 let src_is_signed = core::$x::MIN != 0;
273 let dst_is_signed = core::$y::MIN != 0;
274 if size_of::<$x>() < size_of::<$y>() {
275 if !dst_is_signed {
276 #[cfg(any(debug_assertions, feature = "assert_int"))]
277 assert!(
278 x >= 0,
279 "cast x: {} to {}: expected x >= 0, found x = {}",
280 stringify!($x), stringify!($y), x
281 );
282 }
283 } else if size_of::<$x>() == size_of::<$y>() {
284 if dst_is_signed {
285 #[cfg(any(debug_assertions, feature = "assert_int"))]
286 assert!(
287 x <= core::$y::MAX as $x,
288 "cast x: {} to {}: expected x <= {}, found x = {}",
289 stringify!($x), stringify!($y), core::$y::MAX, x
290 );
291 } else if src_is_signed {
292 #[cfg(any(debug_assertions, feature = "assert_int"))]
293 assert!(
294 x >= 0,
295 "cast x: {} to {}: expected x >= 0, found x = {}",
296 stringify!($x), stringify!($y), x
297 );
298 }
299 } else {
300 // src size > dst size
301 if src_is_signed {
302 #[cfg(any(debug_assertions, feature = "assert_int"))]
303 assert!(
304 core::$y::MIN as $x <= x && x <= core::$y::MAX as $x,
305 "cast x: {} to {}: expected {} <= x <= {}, found x = {}",
306 stringify!($x), stringify!($y), core::$y::MIN, core::$y::MAX, x
307 );
308 } else {
309 #[cfg(any(debug_assertions, feature = "assert_int"))]
310 assert!(
311 x <= core::$y::MAX as $x,
312 "cast x: {} to {}: expected x <= {}, found x = {}",
313 stringify!($x), stringify!($y), core::$y::MAX, x
314 );
315 }
316 }
317 x as $y
318 }
319 #[allow(unused_comparisons)]
320 #[inline]
321 fn try_conv(x: $x) -> Result<Self, Error> {
322 let src_is_signed = core::$x::MIN != 0;
323 let dst_is_signed = core::$y::MIN != 0;
324 if size_of::<$x>() < size_of::<$y>() {
325 if dst_is_signed || x >= 0 {
326 return Ok(x as $y);
327 }
328 } else if size_of::<$x>() == size_of::<$y>() {
329 if dst_is_signed {
330 if x <= core::$y::MAX as $x {
331 return Ok(x as $y);
332 }
333 } else if src_is_signed {
334 if x >= 0 {
335 return Ok(x as $y);
336 }
337 } else {
338 // types are identical (e.g. usize == u64)
339 return Ok(x as $y);
340 }
341 } else {
342 // src size > dst size
343 if src_is_signed {
344 if core::$y::MIN as $x <= x && x <= core::$y::MAX as $x {
345 return Ok(x as $y);
346 }
347 } else {
348 if x <= core::$y::MAX as $x {
349 return Ok(x as $y);
350 }
351 }
352 }
353 Err(Error::Range)
354 }
355 }
356 };
357 ($x:tt: $y:tt, $($yy:tt),+) => {
358 impl_int_generic!($x: $y);
359 impl_int_generic!($x: $($yy),+);
360 };
361 }
362
363 impl_int_generic!(i8: isize, usize);
364 impl_int_generic!(i16: isize, usize);
365 impl_int_generic!(i32: isize, usize);
366 impl_int_generic!(i64: isize, usize);
367 impl_int_generic!(i128: isize, usize);
368 impl_int_generic!(u8: isize, usize);
369 impl_int_generic!(u16: isize, usize);
370 impl_int_generic!(u32: isize, usize);
371 impl_int_generic!(u64: isize, usize);
372 impl_int_generic!(u128: isize, usize);
373 impl_int_generic!(isize: i8, i16, i32, i64, i128);
374 impl_int_generic!(usize: i8, i16, i32, i64, i128, isize);
375 impl_int_generic!(isize: u8, u16, u32, u64, u128, usize);
376 impl_int_generic!(usize: u8, u16, u32, u64, u128);
377
378 macro_rules! impl_via_digits_check {
379 ($x:ty: $y:tt) => {
380 impl Conv<$x> for $y {
381 #[inline]
382 fn conv(x: $x) -> Self {
383 if cfg!(any(debug_assertions, feature = "assert_digits")) {
384 Self::try_conv(x).unwrap_or_else(|_| {
385 panic!(
386 "cast x: {} to {}: inexact for x = {}",
387 stringify!($x), stringify!($y), x
388 )
389 })
390 } else {
391 x as $y
392 }
393 }
394 #[inline]
395 fn try_conv(x: $x) -> Result<Self, Error> {
396 let src_ty_bits = (size_of::<$x>() * 8) as u32;
397 let src_digits = src_ty_bits.saturating_sub(x.leading_zeros() + x.trailing_zeros());
398 let dst_digits = core::$y::MANTISSA_DIGITS;
399 if src_digits <= dst_digits {
400 Ok(x as $y)
401 } else {
402 Err(Error::Inexact)
403 }
404 }
405 }
406 };
407 ($x:ty: $y:tt, $($yy:tt),+) => {
408 impl_via_digits_check!($x: $y);
409 impl_via_digits_check!($x: $($yy),+);
410 };
411 }
412
413 macro_rules! impl_via_digits_check_signed {
414 ($x:ty: $y:tt) => {
415 impl Conv<$x> for $y {
416 #[inline]
417 fn conv(x: $x) -> Self {
418 if cfg!(any(debug_assertions, feature = "assert_digits")) {
419 Self::try_conv(x).unwrap_or_else(|_| {
420 panic!(
421 "cast x: {} to {}: inexact for x = {}",
422 stringify!($x), stringify!($y), x
423 )
424 })
425 } else {
426 x as $y
427 }
428 }
429 #[inline]
430 fn try_conv(x: $x) -> Result<Self, Error> {
431 let src_ty_bits = (size_of::<$x>() * 8) as u32;
432 let src_digits = x.checked_abs()
433 .map(|y| src_ty_bits.saturating_sub(y.leading_zeros() + y.trailing_zeros()))
434 .unwrap_or(1 /*MIN has one binary digit in float repr*/);
435 let dst_digits = core::$y::MANTISSA_DIGITS;
436 if src_digits <= dst_digits {
437 Ok(x as $y)
438 } else {
439 Err(Error::Inexact)
440 }
441 }
442 }
443 };
444 ($x:ty: $y:tt, $($yy:tt),+) => {
445 impl_via_digits_check_signed!($x: $y);
446 impl_via_digits_check_signed!($x: $($yy),+);
447 };
448 }
449
450 impl_via_digits_check!(u32: f32);
451 impl_via_digits_check!(u64: f32, f64);
452 impl_via_digits_check!(u128: f32, f64);
453 impl_via_digits_check!(usize: f32, f64);
454
455 impl_via_digits_check_signed!(i32: f32);
456 impl_via_digits_check_signed!(i64: f32, f64);
457 impl_via_digits_check_signed!(i128: f32, f64);
458 impl_via_digits_check_signed!(isize: f32, f64);
459
460 #[cfg(all(not(feature = "std"), feature = "libm"))]
461 trait FloatRound {
462 fn round(self) -> Self;
463 fn floor(self) -> Self;
464 fn ceil(self) -> Self;
465 }
466 #[cfg(all(not(feature = "std"), feature = "libm"))]
467 impl FloatRound for f32 {
468 fn round(self) -> Self {
469 libm::roundf(self)
470 }
471 fn floor(self) -> Self {
472 libm::floorf(self)
473 }
474 fn ceil(self) -> Self {
475 libm::ceilf(self)
476 }
477 }
478 #[cfg(all(not(feature = "std"), feature = "libm"))]
479 impl FloatRound for f64 {
480 fn round(self) -> Self {
481 libm::round(self)
482 }
483 fn floor(self) -> Self {
484 libm::floor(self)
485 }
486 fn ceil(self) -> Self {
487 libm::ceil(self)
488 }
489 }
490
491 /// Nearest / floor / ceil conversions from floating point types
492 ///
493 /// This trait is explicitly for conversions from floating-point values to
494 /// integers, supporting four rounding modes for fallible and for
495 /// "success expected" conversions.
496 ///
497 /// Two sets of methods are provided:
498 ///
499 /// - `conv_*` methods are for "success expected" conversions. In debug builds
500 /// and when using the `always_assert` or the `assert_float` feature flag,
501 /// out-of-range conversions will panic. In other cases, conversions may
502 /// produce incorrect values (according to the behaviour of as, which is
503 /// saturating cast since Rust 1.45.0 and undefined for older compilers).
504 /// Non-finite source values (`inf` and `NaN`) are considered out-of-range.
505 /// - `try_conv_*` methods are for fallible conversions and always produce an
506 /// error if the conversion would be out of range.
507 ///
508 /// For `f64` to `f32` where loss-of-precision is allowable, it is probably
509 /// acceptable to use `as` (and if need be, check that the result is finite
510 /// with `x.is_finite()`). The reverse, `f32` to `f64`, is always exact.
511 #[cfg(any(feature = "std", feature = "libm"))]
512 #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "libm"))))]
513 pub trait ConvFloat<T>: Sized {
514 /// Convert to integer with truncatation
515 ///
516 /// Rounds towards zero (same as `as`).
517 fn conv_trunc(x: T) -> Self;
518 /// Convert to the nearest integer
519 ///
520 /// Half-way cases are rounded away from `0`.
521 fn conv_nearest(x: T) -> Self;
522 /// Convert the floor to an integer
523 ///
524 /// Returns the largest integer less than or equal to `x`.
525 fn conv_floor(x: T) -> Self;
526 /// Convert the ceiling to an integer
527 ///
528 /// Returns the smallest integer greater than or equal to `x`.
529 fn conv_ceil(x: T) -> Self;
530
531 /// Try converting to integer with truncation
532 ///
533 /// Rounds towards zero (same as `as`).
534 fn try_conv_trunc(x: T) -> Result<Self, Error>;
535 /// Try converting to the nearest integer
536 ///
537 /// Half-way cases are rounded away from `0`.
538 fn try_conv_nearest(x: T) -> Result<Self, Error>;
539 /// Try converting the floor to an integer
540 ///
541 /// Returns the largest integer less than or equal to `x`.
542 fn try_conv_floor(x: T) -> Result<Self, Error>;
543 /// Try convert the ceiling to an integer
544 ///
545 /// Returns the smallest integer greater than or equal to `x`.
546 fn try_conv_ceil(x: T) -> Result<Self, Error>;
547 }
548
549 #[cfg(any(feature = "std", feature = "libm"))]
550 #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "libm"))))]
551 macro_rules! impl_float {
552 ($x:ty: $y:tt) => {
553 impl ConvFloat<$x> for $y {
554 #[inline]
555 fn conv_trunc(x: $x) -> $y {
556 if cfg!(any(debug_assertions, feature = "assert_float")) {
557 Self::try_conv_trunc(x).unwrap_or_else(|_| {
558 panic!(
559 "cast x: {} to {} (trunc): range error for x = {}",
560 stringify!($x), stringify!($y), x
561 )
562 })
563 } else {
564 x as $y
565 }
566 }
567 #[inline]
568 fn conv_nearest(x: $x) -> $y {
569 if cfg!(any(debug_assertions, feature = "assert_float")) {
570 Self::try_conv_nearest(x).unwrap_or_else(|_| {
571 panic!(
572 "cast x: {} to {} (nearest): range error for x = {}",
573 stringify!($x), stringify!($y), x
574 )
575 })
576 } else {
577 x.round() as $y
578 }
579 }
580 #[inline]
581 fn conv_floor(x: $x) -> $y {
582 if cfg!(any(debug_assertions, feature = "assert_float")) {
583 Self::try_conv_floor(x).unwrap_or_else(|_| {
584 panic!(
585 "cast x: {} to {} (floor): range error for x = {}",
586 stringify!($x), stringify!($y), x
587 )
588 })
589 } else {
590 x.floor() as $y
591 }
592 }
593 #[inline]
594 fn conv_ceil(x: $x) -> $y {
595 if cfg!(any(debug_assertions, feature = "assert_float")) {
596 Self::try_conv_ceil(x).unwrap_or_else(|_| {
597 panic!(
598 "cast x: {} to {} (ceil): range error for x = {}",
599 stringify!($x), stringify!($y), x
600 )
601 })
602 } else {
603 x.ceil() as $y
604 }
605 }
606
607 #[inline]
608 fn try_conv_trunc(x: $x) -> Result<Self, Error> {
609 // Tested: these limits work for $x=f32 and all $y except u128
610 const LBOUND: $x = core::$y::MIN as $x - 1.0;
611 const UBOUND: $x = core::$y::MAX as $x + 1.0;
612 if x > LBOUND && x < UBOUND {
613 Ok(x as $y)
614 } else {
615 Err(Error::Range)
616 }
617 }
618 #[inline]
619 fn try_conv_nearest(x: $x) -> Result<Self, Error> {
620 // Tested: these limits work for $x=f32 and all $y except u128
621 const LBOUND: $x = core::$y::MIN as $x;
622 const UBOUND: $x = core::$y::MAX as $x + 1.0;
623 let x = x.round();
624 if x >= LBOUND && x < UBOUND {
625 Ok(x as $y)
626 } else {
627 Err(Error::Range)
628 }
629 }
630 #[inline]
631 fn try_conv_floor(x: $x) -> Result<Self, Error> {
632 // Tested: these limits work for $x=f32 and all $y except u128
633 const LBOUND: $x = core::$y::MIN as $x;
634 const UBOUND: $x = core::$y::MAX as $x + 1.0;
635 let x = x.floor();
636 if x >= LBOUND && x < UBOUND {
637 Ok(x as $y)
638 } else {
639 Err(Error::Range)
640 }
641 }
642 #[inline]
643 fn try_conv_ceil(x: $x) -> Result<Self, Error> {
644 // Tested: these limits work for $x=f32 and all $y except u128
645 const LBOUND: $x = core::$y::MIN as $x;
646 const UBOUND: $x = core::$y::MAX as $x + 1.0;
647 let x = x.ceil();
648 if x >= LBOUND && x < UBOUND {
649 Ok(x as $y)
650 } else {
651 Err(Error::Range)
652 }
653 }
654 }
655 };
656 ($x:ty: $y:tt, $($yy:tt),+) => {
657 impl_float!($x: $y);
658 impl_float!($x: $($yy),+);
659 };
660 }
661
662 // Assumption: usize < 128-bit
663 #[cfg(any(feature = "std", feature = "libm"))]
664 impl_float!(f32: i8, i16, i32, i64, i128, isize);
665 #[cfg(any(feature = "std", feature = "libm"))]
666 impl_float!(f32: u8, u16, u32, u64, usize);
667 #[cfg(any(feature = "std", feature = "libm"))]
668 impl_float!(f64: i8, i16, i32, i64, i128, isize);
669 #[cfg(any(feature = "std", feature = "libm"))]
670 impl_float!(f64: u8, u16, u32, u64, u128, usize);
671
672 #[cfg(any(feature = "std", feature = "libm"))]
673 impl ConvFloat<f32> for u128 {
674 #[inline]
675 fn conv_trunc(x: f32) -> u128 {
676 if cfg!(any(debug_assertions, feature = "assert_float")) {
677 Self::try_conv_trunc(x).unwrap_or_else(|_| {
678 panic!(
679 "cast x: f32 to u128 (trunc/floor): range error for x = {}",
680 x
681 )
682 })
683 } else {
684 x as u128
685 }
686 }
687 #[inline]
688 fn conv_nearest(x: f32) -> u128 {
689 if cfg!(any(debug_assertions, feature = "assert_float")) {
690 Self::try_conv_nearest(x).unwrap_or_else(|_| {
691 panic!("cast x: f32 to u128 (nearest): range error for x = {}", x)
692 })
693 } else {
694 x.round() as u128
695 }
696 }
697 #[inline]
698 fn conv_floor(x: f32) -> u128 {
699 ConvFloat::conv_trunc(x)
700 }
701 #[inline]
702 fn conv_ceil(x: f32) -> u128 {
703 if cfg!(any(debug_assertions, feature = "assert_float")) {
704 Self::try_conv_ceil(x)
705 .unwrap_or_else(|_| panic!("cast x: f32 to u128 (ceil): range error for x = {}", x))
706 } else {
707 x.ceil() as u128
708 }
709 }
710
711 #[inline]
712 fn try_conv_trunc(x: f32) -> Result<Self, Error> {
713 // Note: f32::MAX < u128::MAX
714 if x >= 0.0 && x.is_finite() {
715 Ok(x as u128)
716 } else {
717 Err(Error::Range)
718 }
719 }
720 #[inline]
721 fn try_conv_nearest(x: f32) -> Result<Self, Error> {
722 let x = x.round();
723 if x >= 0.0 && x.is_finite() {
724 Ok(x as u128)
725 } else {
726 Err(Error::Range)
727 }
728 }
729 #[inline]
730 fn try_conv_floor(x: f32) -> Result<Self, Error> {
731 Self::try_conv_trunc(x)
732 }
733 #[inline]
734 fn try_conv_ceil(x: f32) -> Result<Self, Error> {
735 let x = x.ceil();
736 if x >= 0.0 && x.is_finite() {
737 Ok(x as u128)
738 } else {
739 Err(Error::Range)
740 }
741 }
742 }
743
744 /// Like [`Into`], but for [`Conv`]
745 ///
746 /// Two methods are provided:
747 ///
748 /// - [`Cast::cast`] is for "success expected" conversions. In debug builds
749 /// and when using the `always_assert` feature flag, inexact conversions
750 /// will panic. In other cases, conversions may produce incorrect values
751 /// (according to the behaviour of `as`). This is similar to the behviour of
752 /// Rust's overflow checks on integer arithmetic, and intended for usage
753 /// when the user is "reasonably sure" that conversion will succeed.
754 /// - [`Cast::try_cast`] is for fallible conversions, and always produces an
755 /// error if the conversion would be inexact.
756 pub trait Cast<T> {
757 /// Cast from `Self` to `T`
758 fn cast(self) -> T;
759
760 /// Try converting from `Self` to `T`
761 fn try_cast(self) -> Result<T, Error>;
762 }
763
764 impl<S, T: Conv<S>> Cast<T> for S {
765 #[inline]
766 fn cast(self) -> T {
767 T::conv(self)
768 }
769 #[inline]
770 fn try_cast(self) -> Result<T, Error> {
771 T::try_conv(self)
772 }
773 }
774
775 /// Like [`Into`], but for [`ConvFloat`]
776 ///
777 /// Two sets of methods are provided:
778 ///
779 /// - `cast_*` methods are for "success expected" conversions. In debug builds
780 /// and when using the `always_assert` or the `assert_float` feature flag,
781 /// out-of-range conversions will panic. In other cases, conversions may
782 /// produce incorrect values (according to the behaviour of as, which is
783 /// saturating cast since Rust 1.45.0 and undefined for older compilers).
784 /// Non-finite source values (`inf` and `NaN`) are considered out-of-range.
785 /// - `try_cast_*` methods are for fallible conversions and always produce an
786 /// error if the conversion would be out of range.
787 #[cfg(any(feature = "std", feature = "libm"))]
788 #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "libm"))))]
789 pub trait CastFloat<T> {
790 /// Cast to integer, truncating
791 ///
792 /// Rounds towards zero (same as `as`).
793 fn cast_trunc(self) -> T;
794 /// Cast to the nearest integer
795 ///
796 /// Half-way cases are rounded away from `0`.
797 fn cast_nearest(self) -> T;
798 /// Cast the floor to an integer
799 ///
800 /// Returns the largest integer less than or equal to `self`.
801 fn cast_floor(self) -> T;
802 /// Cast the ceiling to an integer
803 ///
804 /// Returns the smallest integer greater than or equal to `self`.
805 fn cast_ceil(self) -> T;
806
807 /// Try converting to integer with truncation
808 ///
809 /// Rounds towards zero (same as `as`).
810 fn try_cast_trunc(self) -> Result<T, Error>;
811 /// Try converting to the nearest integer
812 ///
813 /// Half-way cases are rounded away from `0`.
814 fn try_cast_nearest(self) -> Result<T, Error>;
815 /// Try converting the floor to an integer
816 ///
817 /// Returns the largest integer less than or equal to `x`.
818 fn try_cast_floor(self) -> Result<T, Error>;
819 /// Try convert the ceiling to an integer
820 ///
821 /// Returns the smallest integer greater than or equal to `x`.
822 fn try_cast_ceil(self) -> Result<T, Error>;
823 }
824
825 #[cfg(any(feature = "std", feature = "libm"))]
826 impl<S, T: ConvFloat<S>> CastFloat<T> for S {
827 #[inline]
828 fn cast_trunc(self) -> T {
829 T::conv_trunc(self)
830 }
831 #[inline]
832 fn cast_nearest(self) -> T {
833 T::conv_nearest(self)
834 }
835 #[inline]
836 fn cast_floor(self) -> T {
837 T::conv_floor(self)
838 }
839 #[inline]
840 fn cast_ceil(self) -> T {
841 T::conv_ceil(self)
842 }
843
844 #[inline]
845 fn try_cast_trunc(self) -> Result<T, Error> {
846 T::try_conv_trunc(self)
847 }
848 #[inline]
849 fn try_cast_nearest(self) -> Result<T, Error> {
850 T::try_conv_nearest(self)
851 }
852 #[inline]
853 fn try_cast_floor(self) -> Result<T, Error> {
854 T::try_conv_floor(self)
855 }
856 #[inline]
857 fn try_cast_ceil(self) -> Result<T, Error> {
858 T::try_conv_ceil(self)
859 }
860 }