1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
use std::fmt; use std::iter; use std::mem; use std::ops; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash, Debug)] pub struct Vector { pub x: i32, pub y: i32, } impl Vector { pub const ORIGIN: Vector = Vector { x: 0, y: 0 }; pub fn new(x: i32, y: i32) -> Vector { Vector { x, y } } pub fn segment_pts(self, other: Vector) -> SegmentPts { let disp_x = (other.x - self.x) as f64; let disp_y = (other.y - self.y) as f64; let hypot = f64::hypot(disp_x, disp_y); SegmentPts { from: self, to: other, x: self.x as f64, y: self.y as f64, dx: disp_x / hypot, dy: disp_y / hypot, done: false, } } } impl ops::Add for Vector { type Output = Vector; fn add(self, other: Vector) -> Vector { Vector::new(self.x + other.x, self.y + other.y) } } impl ops::Sub for Vector { type Output = Vector; fn sub(self, other: Vector) -> Vector { Vector::new(self.x - other.x, self.y - other.y) } } impl ops::Neg for Vector { type Output = Vector; fn neg(self) -> Vector { Vector::new(-self.x, -self.y) } } impl fmt::Display for Vector { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) } } #[derive(Clone, PartialEq)] pub struct SegmentPts { from: Vector, to: Vector, x: f64, y: f64, dx: f64, dy: f64, done: bool, } impl Iterator for SegmentPts { type Item = Vector; fn next(&mut self) -> Option<Vector> { if self.done { None } else if self.from == self.to { self.done = true; Some(self.from) } else { self.x += self.dx; self.y += self.dy; Some(mem::replace( &mut self.from, Vector { x: f64::round(self.x) as i32, y: f64::round(self.y) as i32, }, )) } } fn size_hint(&self) -> (usize, Option<usize>) { if self.done { (0, Some(0)) } else { (1, None) } } } impl iter::FusedIterator for SegmentPts {} #[derive(Clone, PartialEq)] pub struct CirclePts { pos: Vector, radius: i32, end_y: i32, } pub fn circle_pts(radius: i32) -> CirclePts { let abs_rad = i32::abs(radius); CirclePts { radius: abs_rad, pos: Vector::new(-abs_rad, -1), end_y: 0, } } impl Iterator for CirclePts { type Item = Vector; fn next(&mut self) -> Option<Vector> { if self.pos.x > self.radius { None } else if self.pos.y < self.end_y { self.pos.y += 1; Some(self.pos) } else { self.pos.x += 1; if self.pos.x <= self.radius { let r = self.radius as f64; let x = self.pos.x as f64; let y = f64::sqrt(r * r - x * x); self.end_y = y as i32; self.pos.y = -self.end_y; Some(self.pos) } else { None } } } } impl iter::FusedIterator for CirclePts {}