#cast #numbers #numeric #safely #cases #reduce #value

no-std numeric_cast

safe cast between numbers

3 unstable releases

0.2.1 Oct 28, 2022
0.2.0 Aug 21, 2022
0.1.2 May 15, 2022
0.1.1 May 15, 2022
0.1.0 May 15, 2022

#2430 in Rust patterns

Download history 1416/week @ 2024-03-14 1409/week @ 2024-03-21 1114/week @ 2024-03-28 1425/week @ 2024-04-04 1795/week @ 2024-04-11 1598/week @ 2024-04-18 1505/week @ 2024-04-25 1731/week @ 2024-05-02 1586/week @ 2024-05-09 1439/week @ 2024-05-16 1042/week @ 2024-05-23 1972/week @ 2024-05-30 1658/week @ 2024-06-06 1453/week @ 2024-06-13 1552/week @ 2024-06-20 1150/week @ 2024-06-27

6,240 downloads per month
Used in 10 crates (4 directly)

MIT license

22KB
679 lines

numeric_cast

Latest Version Documentation License Unsafe Forbidden

Safely 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