]> git.proxmox.com Git - rustc.git/blob - src/librustc_const_math/us.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / librustc_const_math / us.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 use syntax::ast;
12 use super::err::*;
13
14 /// Depending on the target only one variant is ever used in a compilation.
15 /// Anything else is an error. This invariant is checked at several locations
16 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, Hash, Eq, PartialEq)]
17 pub enum ConstUsize {
18 Us32(u32),
19 Us64(u64),
20 }
21 pub use self::ConstUsize::*;
22
23 impl ConstUsize {
24 pub fn as_u64(self, target_uint_ty: ast::UintTy) -> u64 {
25 match (self, target_uint_ty) {
26 (Us32(i), ast::UintTy::U32) => i as u64,
27 (Us64(i), ast::UintTy::U64) => i,
28 _ => panic!("got invalid usize size for target"),
29 }
30 }
31 pub fn new(i: u64, target_uint_ty: ast::UintTy) -> Result<Self, ConstMathErr> {
32 match target_uint_ty {
33 ast::UintTy::U32 if i as u32 as u64 == i => Ok(Us32(i as u32)),
34 ast::UintTy::U32 => Err(ULitOutOfRange(ast::UintTy::Us)),
35 ast::UintTy::U64 => Ok(Us64(i)),
36 _ => unreachable!(),
37 }
38 }
39 }