1 // Copyright 2013-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 extern crate num as num_renamed;
12 #[macro_use]
13 extern crate num_derive;
14
15 #[derive(Debug, PartialEq, FromPrimitive, ToPrimitive)]
16 enum Color {
17 Red,
18 Blue = 5,
19 Green,
20 Alpha = (-3 - (-5isize)) - 10,
21 }
22
23 #[test]
test_from_primitive_for_enum_with_custom_value()24 fn test_from_primitive_for_enum_with_custom_value() {
25 let v: [Option<Color>; 5] = [
26 num_renamed::FromPrimitive::from_u64(0),
27 num_renamed::FromPrimitive::from_u64(5),
28 num_renamed::FromPrimitive::from_u64(6),
29 num_renamed::FromPrimitive::from_u64(-8isize as u64),
30 num_renamed::FromPrimitive::from_u64(3),
31 ];
32
33 assert_eq!(
34 v,
35 [
36 Some(Color::Red),
37 Some(Color::Blue),
38 Some(Color::Green),
39 Some(Color::Alpha),
40 None
41 ]
42 );
43 }
44
45 #[test]
test_to_primitive_for_enum_with_custom_value()46 fn test_to_primitive_for_enum_with_custom_value() {
47 let v: [Option<u64>; 4] = [
48 num_renamed::ToPrimitive::to_u64(&Color::Red),
49 num_renamed::ToPrimitive::to_u64(&Color::Blue),
50 num_renamed::ToPrimitive::to_u64(&Color::Green),
51 num_renamed::ToPrimitive::to_u64(&Color::Alpha),
52 ];
53
54 assert_eq!(v, [Some(0), Some(5), Some(6), Some(-8isize as u64)]);
55 }
56
57 #[test]
test_reflexive_for_enum_with_custom_value()58 fn test_reflexive_for_enum_with_custom_value() {
59 let before: [u64; 3] = [0, 5, 6];
60 let after: Vec<Option<u64>> = before
61 .iter()
62 .map(|&x| -> Option<Color> { num_renamed::FromPrimitive::from_u64(x) })
63 .map(|x| x.and_then(|x| num_renamed::ToPrimitive::to_u64(&x)))
64 .collect();
65 let before = before.iter().cloned().map(Some).collect::<Vec<_>>();
66
67 assert_eq!(before, after);
68 }
69