5 unstable releases

new 0.3.0 Jan 15, 2025
0.2.2 Jan 15, 2025
0.2.1 Oct 28, 2022
0.2.0 Aug 21, 2022
0.1.2 May 15, 2022

#896 in Rust patterns

Download history 1021/week @ 2024-09-27 1299/week @ 2024-10-04 1543/week @ 2024-10-11 1757/week @ 2024-10-18 1554/week @ 2024-10-25 1216/week @ 2024-11-01 776/week @ 2024-11-08 1216/week @ 2024-11-15 1084/week @ 2024-11-22 1130/week @ 2024-11-29 539/week @ 2024-12-06 793/week @ 2024-12-13 286/week @ 2024-12-20 526/week @ 2024-12-27 1199/week @ 2025-01-03 1145/week @ 2025-01-10

3,301 downloads per month
Used in 16 crates (5 directly)

MIT license

23KB
715 lines

numeric_cast

Latest Version Documentation License Unsafe Forbidden

Safely cast between numbers.

Documentation: https://docs.rs/numeric_cast

Contributing


lib.rs:

Safely cast between numbers.

The extension trait NumericCast adds a generic method numeric_cast for all number types. The method allows users to safely cast a number to another type without losing precision.

If the value can not be represented by the target type, the method will panic with a message which tells the value, the source type name and the target type name.

As numeric_cast is marked by track_caller, the panic location will be exactly where you call the method.

This library optimizes for code bloat. In most use cases, numeric cast always succeeds at runtime, so the panic function is split from normal control flow to reduce performance impact.

Examples

use numeric_cast::NumericCast;

let entries: u64 = 1024;

let capacity = entries.numeric_cast::<usize>();
let offset: isize = entries.numeric_cast(); // by inference
use numeric_cast::NumericCast;

let n: i32 = -1;
let len: usize = n.numeric_cast(); // panic here

No runtime deps