Last active
August 29, 2015 14:01
-
-
Save rtaycher/138f188ba9444e59f621 to your computer and use it in GitHub Desktop.
Create Ranged Int Types w/macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(macro_rules)] | |
//tested on: | |
//rustc 0.10 | |
//host: x86_64-unknown-linux-gnu | |
use std::to_str::ToStr; | |
macro_rules! make_range_int_type( | |
($RangedIntName:ident $RIN:ident $OORN:ident $l:expr $u:expr) => ( | |
#[deriving(Show)] | |
enum $RangedIntName { | |
$OORN, | |
$RIN(int) | |
} | |
impl Add<$RangedIntName, $RangedIntName> for $RangedIntName { | |
fn add(&self, _rhs: &$RangedIntName) -> $RangedIntName { | |
match (*self, *_rhs) { | |
($RIN(x),$RIN(y)) => { | |
let value = x + y; | |
if $RangedIntName::is_in_range(value) { $RIN(value) } else { $OORN } | |
}, | |
($OORN, _) => $OORN, | |
(_, $OORN) => $OORN | |
} | |
} | |
} | |
impl $RangedIntName { | |
fn from_int(i: int) -> $RangedIntName { | |
if $RangedIntName::is_in_range(i) { $RIN(i) } else { $OORN } | |
} | |
fn is_in_range(i: int) -> bool { | |
i>=$l && i <= $u | |
} | |
fn unwrap(self) -> int { | |
match self { | |
$RIN(x) => x, | |
$OORN => fail!("failed to unwrap $RangedIntName - OutOfRange!") | |
} | |
} | |
} | |
); | |
) | |
make_range_int_type!(RangedIntNFiveToFive RINFiveToFive OutOfRangeNFiveToFive -5 5) | |
fn main() { | |
let i = RangedIntNFiveToFive::from_int(1) + RangedIntNFiveToFive::from_int(-1) ; | |
let j = RangedIntNFiveToFive::from_int(20) + RangedIntNFiveToFive::from_int(-22) ; | |
let k = RangedIntNFiveToFive::from_int(1) + RangedIntNFiveToFive::from_int(-1); | |
let l = RangedIntNFiveToFive::from_int(1).unwrap(); | |
println!("i: {}", i.to_str()); //prints "i: RINFiveToFive(0)" | |
println!("j: {}", j.to_str()); //prints "j: OutOfRangeNFiveToFive" | |
println!("k: {}", k.to_str()); //prints "k: RINFiveToFive(0)" | |
println!("l: {}", l.to_str()); //prints "l: 1" | |
let m = RangedIntNFiveToFive::from_int(20).unwrap(); //causes exit:"task '<main>' failed at 'failed to unwrap $RangedIntName - OutOfRange!', ranged_num.rs:47" | |
println!("m: {}", m.to_str()); //never reached | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment