Crate cast [] [src]

Ergonomic, checked cast functions for primitive types

This crate provides one checked cast function for each numeric primitive. Use these functions to perform a cast from any other numeric primitive:

extern crate cast;

use cast::{u8, u16, Error};

// Infallible operations, like integer promotion, are equivalent to a normal
// cast with `as`
assert_eq!(u16(0u8), 0u16);

// Everything else will return a `Result` depending on the success of the
// operation
assert_eq!(u8(0u16), Ok(0u8));
assert_eq!(u8(256u16), Err(Error::Overflow));
assert_eq!(u8(-1i8), Err(Error::Underflow));
assert_eq!(u8(1. / 0.), Err(Error::Infinite));
assert_eq!(u8(0. / 0.), Err(Error::NaN));

There are no namespace problems between these functions, the "primitive modules" in core/std and the built-in primitive types, so all them can be in the same scope:

extern crate cast;

use std::u8;
use cast::{u8, u16};

// `u8` as a type
let x: u8 = 0;
// `u8` as a module
let y = u16(u8::MAX);
// `u8` as a function
let z = u8(y).unwrap();

The checked cast functionality is also usable with type aliases via the cast static method:

extern crate cast;

use std::os::raw::c_ulonglong;
// NOTE avoid shadowing `std::convert::From` - cf. rust-lang/rfcs#1311
use cast::From as _0;

assert_eq!(c_ulonglong::cast(0u8), 0u64);

This crate also provides a From trait that can be used, for example, to create a generic function that accepts any type that can be infallibly casted to u32.

extern crate cast;

fn to_u32<T>(x: T) -> u32
    // reads as: "where u32 can be casted from T with output u32"
    where u32: cast::From<T, Output=u32>,
{
    cast::u32(x)
}

assert_eq!(to_u32(0u8), 0u32);
assert_eq!(to_u32(1u16), 1u32);
assert_eq!(to_u32(2u32), 2u32);

// to_u32(-1i32);  // Compile error

Building without std

This crate can be used without Rust's std crate by declaring it as follows in your Cargo.toml:

cast = { version = "*", default-features = false }

Enums

Error

Cast errors

Traits

From

The "cast from" operation

Functions

f32

Checked cast function

f64

Checked cast function

i8

Checked cast function

i16

Checked cast function

i32

Checked cast function

i64

Checked cast function

isize

Checked cast function

u8

Checked cast function

u16

Checked cast function

u32

Checked cast function

u64

Checked cast function

usize

Checked cast function