]> git.proxmox.com Git - rustc.git/blob - src/librustc/util/num.rs
Imported Upstream version 1.0.0~beta.3
[rustc.git] / src / librustc / util / num.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 pub trait ToPrimitive {
12 fn to_i8(&self) -> Option<i8>;
13 fn to_i16(&self) -> Option<i16>;
14 fn to_i32(&self) -> Option<i32>;
15 fn to_i64(&self) -> Option<i64>;
16 fn to_u8(&self) -> Option<u8>;
17 fn to_u16(&self) -> Option<u16>;
18 fn to_u32(&self) -> Option<u32>;
19 fn to_u64(&self) -> Option<u64>;
20 }
21
22 impl ToPrimitive for i64 {
23 fn to_i8(&self) -> Option<i8> {
24 if *self < i8::min_value() as i64 || *self > i8::max_value() as i64 {
25 None
26 } else {
27 Some(*self as i8)
28 }
29 }
30 fn to_i16(&self) -> Option<i16> {
31 if *self < i16::min_value() as i64 || *self > i16::max_value() as i64 {
32 None
33 } else {
34 Some(*self as i16)
35 }
36 }
37 fn to_i32(&self) -> Option<i32> {
38 if *self < i32::min_value() as i64 || *self > i32::max_value() as i64 {
39 None
40 } else {
41 Some(*self as i32)
42 }
43 }
44 fn to_i64(&self) -> Option<i64> {
45 Some(*self)
46 }
47 fn to_u8(&self) -> Option<u8> {
48 if *self < 0 || *self > u8::max_value() as i64 {
49 None
50 } else {
51 Some(*self as u8)
52 }
53 }
54 fn to_u16(&self) -> Option<u16> {
55 if *self < 0 || *self > u16::max_value() as i64 {
56 None
57 } else {
58 Some(*self as u16)
59 }
60 }
61 fn to_u32(&self) -> Option<u32> {
62 if *self < 0 || *self > u32::max_value() as i64 {
63 None
64 } else {
65 Some(*self as u32)
66 }
67 }
68 fn to_u64(&self) -> Option<u64> {
69 if *self < 0 {None} else {Some(*self as u64)}
70 }
71 }
72
73 impl ToPrimitive for u64 {
74 fn to_i8(&self) -> Option<i8> {
75 if *self > i8::max_value() as u64 {None} else {Some(*self as i8)}
76 }
77 fn to_i16(&self) -> Option<i16> {
78 if *self > i16::max_value() as u64 {None} else {Some(*self as i16)}
79 }
80 fn to_i32(&self) -> Option<i32> {
81 if *self > i32::max_value() as u64 {None} else {Some(*self as i32)}
82 }
83 fn to_i64(&self) -> Option<i64> {
84 if *self > i64::max_value() as u64 {None} else {Some(*self as i64)}
85 }
86 fn to_u8(&self) -> Option<u8> {
87 if *self > u8::max_value() as u64 {None} else {Some(*self as u8)}
88 }
89 fn to_u16(&self) -> Option<u16> {
90 if *self > u16::max_value() as u64 {None} else {Some(*self as u16)}
91 }
92 fn to_u32(&self) -> Option<u32> {
93 if *self > u32::max_value() as u64 {None} else {Some(*self as u32)}
94 }
95 fn to_u64(&self) -> Option<u64> {
96 Some(*self)
97 }
98 }