#cast

no-std numeric_cast

safe cast between numbers

1 unstable release

Uses new Rust 2021

0.1.2 May 15, 2022
0.1.1 May 15, 2022
0.1.0 May 15, 2022

#772 in Rust patterns

Download history 33/week @ 2022-05-09 53/week @ 2022-05-16 35/week @ 2022-05-23 67/week @ 2022-05-30 49/week @ 2022-06-06 138/week @ 2022-06-13 72/week @ 2022-06-20 91/week @ 2022-06-27 68/week @ 2022-07-04 48/week @ 2022-07-11 73/week @ 2022-07-18 104/week @ 2022-07-25 165/week @ 2022-08-01 108/week @ 2022-08-08

458 downloads per month
Used in 3 crates

MIT license

11KB
282 lines

numeric_cast

Latest Version Documentation License

Safe cast between numbers.

Documentation: https://docs.rs/numeric_cast


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