]> git.lizzy.rs Git - rust.git/blob - src/librustc_const_math/is.rs
Auto merge of #44060 - taleks:issue-43205, r=arielb1
[rust.git] / src / librustc_const_math / is.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 ConstIsize {
18     Is16(i16),
19     Is32(i32),
20     Is64(i64),
21 }
22 pub use self::ConstIsize::*;
23
24 impl ConstIsize {
25     pub fn as_i64(self, target_int_ty: ast::IntTy) -> i64 {
26         match (self, target_int_ty) {
27             (Is16(i), ast::IntTy::I16) => i as i64,
28             (Is32(i), ast::IntTy::I32) => i as i64,
29             (Is64(i), ast::IntTy::I64) => i,
30             _ => panic!("unable to convert self ({:?}) to target isize ({:?})",
31                         self, target_int_ty),
32         }
33     }
34     pub fn new(i: i64, target_int_ty: ast::IntTy) -> Result<Self, ConstMathErr> {
35         match target_int_ty {
36             ast::IntTy::I16 if i as i16 as i64 == i => Ok(Is16(i as i16)),
37             ast::IntTy::I16 => Err(LitOutOfRange(ast::IntTy::Is)),
38             ast::IntTy::I32 if i as i32 as i64 == i => Ok(Is32(i as i32)),
39             ast::IntTy::I32 => Err(LitOutOfRange(ast::IntTy::Is)),
40             ast::IntTy::I64 => Ok(Is64(i)),
41             _ => unreachable!(),
42         }
43     }
44     pub fn new_truncating(i: i128, target_int_ty: ast::IntTy) -> Self {
45         match target_int_ty {
46             ast::IntTy::I16 => Is16(i as i16),
47             ast::IntTy::I32 => Is32(i as i32),
48             ast::IntTy::I64 => Is64(i as i64),
49             _ => unreachable!(),
50         }
51     }
52 }