1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#![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
        }
    }
}));