numeric_cast/lib.rs
1//! Safely cast between numbers.
2//!
3//! The extension trait [`NumericCast`] adds a generic method [`numeric_cast`](NumericCast::numeric_cast) for all number types.
4//! The method allows users to safely cast a number to another type without losing precision.
5//!
6//! If the value can not be represented by the target type,
7//! the method will panic with a message which tells the value, the source type name and the target type name.
8//!
9//! As [`numeric_cast`](NumericCast::numeric_cast) is marked by `track_caller`, the panic location will be exactly where you call the method.
10//!
11//! This library optimizes for code bloat. In most use cases, numeric cast always succeeds at runtime,
12//! so the panic function is split from normal control flow to reduce performance impact.
13//!
14//! # Examples
15//!
16//! ```
17//! use numeric_cast::NumericCast;
18//!
19//! let entries: u64 = 1024;
20//!
21//! let capacity = entries.numeric_cast::<usize>();
22//! let offset: isize = entries.numeric_cast(); // by inference
23//! ```
24//!
25//! ```should_panic
26//! use numeric_cast::NumericCast;
27//!
28//! let n: i32 = -1;
29//! let len: usize = n.numeric_cast(); // panic here
30//! ```
31//!
32#![forbid(unsafe_code)]
33#![deny(
34 clippy::all,
35 clippy::missing_inline_in_public_items,
36 clippy::must_use_candidate //
37)]
38// ---
39#![cfg_attr(not(test), no_std)]
40
41mod lossless;
42pub use self::lossless::*;
43
44mod wrapping;
45pub use self::wrapping::*;
46
47mod extending;
48pub use self::extending::*;
49
50mod truncating;
51pub use self::truncating::*;
52
53mod rounding;
54pub use self::rounding::*;
55
56#[cold]
57#[track_caller]
58#[inline(never)]
59fn panic_failure(msg: &'static str, val: &dyn core::fmt::Display, lhs: &'static str, rhs: &'static str) -> ! {
60 panic!("{}: lhs: {}, rhs: {}, val: {}", msg, lhs, rhs, val)
61}