checked_cast 0.0.3

A small macro to deal with the libc typedef hell.
Documentation
#![crate_name="checked_cast"]
#![crate_type="lib"]
#![allow(unstable)]

#![macro_use]

/// ```test_harness
/// // no idea how to get around the warnings :(
/// #![allow(unused_comparisons)]
///
/// // we use core directly, not everyone wants to depend on std
/// extern crate core;
///
/// // not required, the liblibc typedef hell is the primary use case
/// extern crate libc;
///
/// #[macro_use] extern crate checked_cast;
///
///
/// #[allow(unused_comparisons)]
/// #[test]
/// fn t1() {
///     // negative numbers don't fit into unsigned
///     let a: libc::c_short = -1;
///     let acast: Option<libc::c_ulong> = checked_cast!(a, libc::c_ulong);
///     assert_eq!(acast, None);
/// }
///
/// #[allow(unused_comparisons)]
/// #[test]
/// fn t2() {
///     // small enough to fit
///     let b: libc::c_longlong = 235234523;
///     let bcast: Option<libc::c_int> = checked_cast!(b, libc::c_int);
///     assert_eq!(bcast, Some(235234523i32));
/// }
///
/// #[allow(unused_comparisons)]
/// #[test]
/// fn t3() {
///     let c: libc::c_short = 0;
///     let ccast: Option<libc::c_uint> = checked_cast!(c, libc::c_uint);
///     assert_eq!(ccast, Some(0));
/// }
///
/// #[test]
/// fn t4() {
/// // too large to fit into u8
///     let d: int = 2314;
///     let dcast: Option<u8> = checked_cast!(d, u8);
///     assert_eq!(dcast, None);
/// }
///
/// #[allow(unused_comparisons)]
/// #[test]
/// #[should_fail]
/// fn t5() {
///     // you can just unwrap too
///     let e: u16 = 65535;
///     let ecast: i16 = checked_cast!(e, i16).unwrap();
/// }


extern crate core;

#[macro_export]
macro_rules! checked_cast(($n:expr, $u:ty) => ({
    let _min: $u = ::core::num::Int::min_value();
    let _max: $u = ::core::num::Int::max_value();
    if $n < 0 {
        if $n as i64 >= _min as i64 && $n as i64 <= _max as i64 {
            Some($n as $u)
        } else {
            None
        }
    } else {
        if $n as u64 <= _max as u64 {
            Some($n as $u)
        } else {
            None
        }
    }
}));