trivial.rs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. extern crate num;
  11. #[macro_use]
  12. extern crate num_derive;
  13. #[derive(Debug, PartialEq, FromPrimitive, ToPrimitive)]
  14. enum Color {
  15. Red,
  16. Blue,
  17. Green,
  18. }
  19. #[test]
  20. fn test_from_primitive_for_trivial_case() {
  21. let v: [Option<Color>; 4] = [num::FromPrimitive::from_u64(0),
  22. num::FromPrimitive::from_u64(1),
  23. num::FromPrimitive::from_u64(2),
  24. num::FromPrimitive::from_u64(3)];
  25. assert_eq!(v,
  26. [Some(Color::Red), Some(Color::Blue), Some(Color::Green), None]);
  27. }
  28. #[test]
  29. fn test_to_primitive_for_trivial_case() {
  30. let v: [Option<u64>; 3] = [num::ToPrimitive::to_u64(&Color::Red),
  31. num::ToPrimitive::to_u64(&Color::Blue),
  32. num::ToPrimitive::to_u64(&Color::Green)];
  33. assert_eq!(v, [Some(0), Some(1), Some(2)]);
  34. }
  35. #[test]
  36. fn test_reflexive_for_trivial_case() {
  37. let before: [u64; 3] = [0, 1, 2];
  38. let after: Vec<Option<u64>> = before.iter()
  39. .map(|&x| -> Option<Color> { num::FromPrimitive::from_u64(x) })
  40. .map(|x| x.and_then(|x| num::ToPrimitive::to_u64(&x)))
  41. .collect();
  42. let before = before.into_iter().cloned().map(Some).collect::<Vec<_>>();
  43. assert_eq!(before, after);
  44. }