[][src]Crate az

Numeric casts

This crate provides checked, overflowing and static casts.

Quick examples

use core::num::Wrapping;

// Panics on overflow with `debug_assertions`, otherwise wraps.
let a: u32 = az::cast(12i32);
assert_eq!(a, 12);

// Always wraps.
let b: u32 = az::wrapping_cast(-1i32);
assert_eq!(b, u32::max_value());
let c = az::overflowing_cast::<i32, u32>(-1i32);
assert_eq!(c, (u32::max_value(), true));

// Wrapping can also be obtained using `Wrapping`
let d: Wrapping<u32> = az::cast(-1);
assert_eq!(d.0, u32::max_value());

Conversions from floating-point to integers are also supported. Numbers are rounded towards zero, but the Round wrapper can be used to convert floating-point numbers to integers with rounding to the nearest, with ties rounded to even.

use az::Round;
use core::f32;

assert_eq!(az::cast::<_, i32>(15.7), 15);
assert_eq!(az::cast::<_, i32>(Round(15.5)), 16);
assert_eq!(az::saturating_cast::<_, i32>(1.5e20), i32::max_value());
assert_eq!(az::checked_cast::<_, i32>(f32::NAN), None);

Using the az crate

The az crate is available on crates.io. To use it in your crate, add it as a dependency inside Cargo.toml:

[dependencies]
az = "0.1.0"

License

This crate is free software: you can redistribute it and/or modify it under the terms of either

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache License, Version 2.0, shall be dual licensed as above, without any additional terms or conditions.

Structs

Round

Used to convert floating-point numbers to integers with rounding to the nearest, with ties rounded to even.

Traits

Az

Used to cast values.

CheckedAs

Used for checked casts.

OverflowingAs

Used for overflowing casts.

SaturatingAs

Used to cast into the destination type, saturating if the value does not fit.

StaticAs

Casts into the destination type, returning () if the destination type cannot hold all values of the source type.

WrappingAs

Wrapping cast.

Functions

cast

Casts the value.

checked_cast

Casts the value, returning None if the value does not fit.

overflowing_cast

Overflowing cast.

saturating_cast

Casts the value, saturating if the value does not fit.

static_cast

Casts the value.

wrapping_cast

Casts the value, wrapping on overflow.