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
use syntax::ast;
use super::err::*;
#[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, Hash, Eq, PartialEq)]
pub enum ConstUsize {
Us16(u16),
Us32(u32),
Us64(u64),
}
pub use self::ConstUsize::*;
impl ConstUsize {
pub fn as_u64(self, target_uint_ty: ast::UintTy) -> u64 {
match (self, target_uint_ty) {
(Us16(i), ast::UintTy::U16) => i as u64,
(Us32(i), ast::UintTy::U32) => i as u64,
(Us64(i), ast::UintTy::U64) => i,
_ => panic!("unable to convert self ({:?}) to target usize ({:?})",
self, target_uint_ty),
}
}
pub fn new(i: u64, target_uint_ty: ast::UintTy) -> Result<Self, ConstMathErr> {
match target_uint_ty {
ast::UintTy::U16 if i as u16 as u64 == i => Ok(Us16(i as u16)),
ast::UintTy::U16 => Err(ULitOutOfRange(ast::UintTy::Us)),
ast::UintTy::U32 if i as u32 as u64 == i => Ok(Us32(i as u32)),
ast::UintTy::U32 => Err(ULitOutOfRange(ast::UintTy::Us)),
ast::UintTy::U64 => Ok(Us64(i)),
_ => unreachable!(),
}
}
pub fn new_truncating(i: u128, target_uint_ty: ast::UintTy) -> Self {
match target_uint_ty {
ast::UintTy::U16 => Us16(i as u16),
ast::UintTy::U32 => Us32(i as u32),
ast::UintTy::U64 => Us64(i as u64),
_ => unreachable!(),
}
}
}