Guest User

Untitled

a guest
Feb 16th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. pub mod pos {
  2. use std::cmp::{Ordering, PartialEq};
  3.  
  4. #[derive(PartialOrd, PartialEq, Eq, Hash, Debug, Copy, Clone)]
  5. pub struct Pos {
  6. pub x: i32,
  7. pub y: i32,
  8. }
  9.  
  10. #[allow(dead_code)]
  11. impl Pos {
  12. pub fn of(x: i32, y: i32) -> Self {
  13. Self { x, y }
  14. }
  15.  
  16. pub fn offset(&mut self, pos: &Self) -> Self {
  17. self.x += pos.x;
  18. self.y += pos.y;
  19.  
  20. *self
  21. }
  22. }
  23.  
  24. impl Ord for Pos {
  25. fn cmp(&self, other: &Self) -> Ordering {
  26. if self.x < other.x {
  27. Ordering::Less
  28. } else if self.eq(other) {
  29. Ordering::Equal
  30. } else {
  31. Ordering::Greater
  32. }
  33. }
  34. }
  35. }
  36.  
  37. mod test {
  38. use crate::pos::Pos;
  39. use std::collections::BTreeSet;
  40.  
  41. #[test]
  42. fn test_iterators() {
  43. let mut data_in_some_strct: Vec<Pos> = Vec::new();
  44.  
  45. data_in_some_strct.push(Pos::of(1, 1));
  46. data_in_some_strct.push(Pos::of(2, 2));
  47. data_in_some_strct.push(Pos::of(3, 3));
  48. data_in_some_strct.push(Pos::of(4, 4));
  49.  
  50. // mimic getter call
  51. // ( get_data(&mut self) -> &BTreeSet<Pos> {...}
  52. // let set = data_in_some_strct; // works
  53. let set = &data_in_some_strct; // doesn't work, How to adjust code to make it work??
  54.  
  55. data_in_some_strct = data_in_some_strct
  56. .into_iter()
  57. .map(|mut p| p.offset(&Pos::of(1, 0)))
  58. .inspect(|p| println!("{:?}", *p))
  59. .collect();
  60.  
  61. assert_eq!(data_in_some_strct.contains(&Pos::of(2, 1)), true);
  62. assert_eq!(data_in_some_strct.contains(&Pos::of(3, 2)), true);
  63. assert_eq!(data_in_some_strct.contains(&Pos::of(4, 3)), true);
  64. assert_eq!(data_in_some_strct.contains(&Pos::of(5, 4)), true);
  65. }
  66. }
Add Comment
Please, Sign In to add comment