iter.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. // Copyright 2013-2014 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. //! External iterators for generic mathematics
  11. use {Integer, Zero, One, CheckedAdd, ToPrimitive};
  12. use std::ops::{Add, Sub};
  13. /// An iterator over the range [start, stop)
  14. #[derive(Clone)]
  15. pub struct Range<A> {
  16. state: A,
  17. stop: A,
  18. one: A
  19. }
  20. /// Returns an iterator over the given range [start, stop) (that is, starting
  21. /// at start (inclusive), and ending at stop (exclusive)).
  22. ///
  23. /// # Example
  24. ///
  25. /// ```rust
  26. /// use num::iter;
  27. ///
  28. /// let array = [0, 1, 2, 3, 4];
  29. ///
  30. /// for i in iter::range(0, 5) {
  31. /// println!("{}", i);
  32. /// assert_eq!(i, array[i]);
  33. /// }
  34. /// ```
  35. #[inline]
  36. pub fn range<A>(start: A, stop: A) -> Range<A>
  37. where A: Add<A, Output = A> + PartialOrd + Clone + One
  38. {
  39. Range{state: start, stop: stop, one: One::one()}
  40. }
  41. // FIXME: rust-lang/rust#10414: Unfortunate type bound
  42. impl<A> Iterator for Range<A>
  43. where A: Add<A, Output = A> + PartialOrd + Clone + ToPrimitive
  44. {
  45. type Item = A;
  46. #[inline]
  47. fn next(&mut self) -> Option<A> {
  48. if self.state < self.stop {
  49. let result = self.state.clone();
  50. self.state = self.state.clone() + self.one.clone();
  51. Some(result)
  52. } else {
  53. None
  54. }
  55. }
  56. #[inline]
  57. fn size_hint(&self) -> (usize, Option<usize>) {
  58. // This first checks if the elements are representable as i64. If they aren't, try u64 (to
  59. // handle cases like range(huge, huger)). We don't use usize/int because the difference of
  60. // the i64/u64 might lie within their range.
  61. let bound = match self.state.to_i64() {
  62. Some(a) => {
  63. let sz = self.stop.to_i64().map(|b| b.checked_sub(a));
  64. match sz {
  65. Some(Some(bound)) => bound.to_usize(),
  66. _ => None,
  67. }
  68. },
  69. None => match self.state.to_u64() {
  70. Some(a) => {
  71. let sz = self.stop.to_u64().map(|b| b.checked_sub(a));
  72. match sz {
  73. Some(Some(bound)) => bound.to_usize(),
  74. _ => None
  75. }
  76. },
  77. None => None
  78. }
  79. };
  80. match bound {
  81. Some(b) => (b, Some(b)),
  82. // Standard fallback for unbounded/unrepresentable bounds
  83. None => (0, None)
  84. }
  85. }
  86. }
  87. /// `Integer` is required to ensure the range will be the same regardless of
  88. /// the direction it is consumed.
  89. impl<A> DoubleEndedIterator for Range<A>
  90. where A: Integer + PartialOrd + Clone + ToPrimitive
  91. {
  92. #[inline]
  93. fn next_back(&mut self) -> Option<A> {
  94. if self.stop > self.state {
  95. self.stop = self.stop.clone() - self.one.clone();
  96. Some(self.stop.clone())
  97. } else {
  98. None
  99. }
  100. }
  101. }
  102. /// An iterator over the range [start, stop]
  103. #[derive(Clone)]
  104. pub struct RangeInclusive<A> {
  105. range: Range<A>,
  106. done: bool,
  107. }
  108. /// Return an iterator over the range [start, stop]
  109. #[inline]
  110. pub fn range_inclusive<A>(start: A, stop: A) -> RangeInclusive<A>
  111. where A: Add<A, Output = A> + PartialOrd + Clone + One
  112. {
  113. RangeInclusive{range: range(start, stop), done: false}
  114. }
  115. impl<A> Iterator for RangeInclusive<A>
  116. where A: Add<A, Output = A> + PartialOrd + Clone + ToPrimitive
  117. {
  118. type Item = A;
  119. #[inline]
  120. fn next(&mut self) -> Option<A> {
  121. match self.range.next() {
  122. Some(x) => Some(x),
  123. None => {
  124. if !self.done && self.range.state == self.range.stop {
  125. self.done = true;
  126. Some(self.range.stop.clone())
  127. } else {
  128. None
  129. }
  130. }
  131. }
  132. }
  133. #[inline]
  134. fn size_hint(&self) -> (usize, Option<usize>) {
  135. let (lo, hi) = self.range.size_hint();
  136. if self.done {
  137. (lo, hi)
  138. } else {
  139. let lo = lo.saturating_add(1);
  140. let hi = match hi {
  141. Some(x) => x.checked_add(1),
  142. None => None
  143. };
  144. (lo, hi)
  145. }
  146. }
  147. }
  148. impl<A> DoubleEndedIterator for RangeInclusive<A>
  149. where A: Sub<A, Output = A> + Integer + PartialOrd + Clone + ToPrimitive
  150. {
  151. #[inline]
  152. fn next_back(&mut self) -> Option<A> {
  153. if self.range.stop > self.range.state {
  154. let result = self.range.stop.clone();
  155. self.range.stop = self.range.stop.clone() - self.range.one.clone();
  156. Some(result)
  157. } else if !self.done && self.range.state == self.range.stop {
  158. self.done = true;
  159. Some(self.range.stop.clone())
  160. } else {
  161. None
  162. }
  163. }
  164. }
  165. /// An iterator over the range [start, stop) by `step`. It handles overflow by stopping.
  166. #[derive(Clone)]
  167. pub struct RangeStep<A> {
  168. state: A,
  169. stop: A,
  170. step: A,
  171. rev: bool,
  172. }
  173. /// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping.
  174. #[inline]
  175. pub fn range_step<A>(start: A, stop: A, step: A) -> RangeStep<A>
  176. where A: CheckedAdd + PartialOrd + Clone + Zero
  177. {
  178. let rev = step < Zero::zero();
  179. RangeStep{state: start, stop: stop, step: step, rev: rev}
  180. }
  181. impl<A> Iterator for RangeStep<A>
  182. where A: CheckedAdd + PartialOrd + Clone
  183. {
  184. type Item = A;
  185. #[inline]
  186. fn next(&mut self) -> Option<A> {
  187. if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) {
  188. let result = self.state.clone();
  189. match self.state.checked_add(&self.step) {
  190. Some(x) => self.state = x,
  191. None => self.state = self.stop.clone()
  192. }
  193. Some(result)
  194. } else {
  195. None
  196. }
  197. }
  198. }
  199. /// An iterator over the range [start, stop] by `step`. It handles overflow by stopping.
  200. #[derive(Clone)]
  201. pub struct RangeStepInclusive<A> {
  202. state: A,
  203. stop: A,
  204. step: A,
  205. rev: bool,
  206. done: bool,
  207. }
  208. /// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping.
  209. #[inline]
  210. pub fn range_step_inclusive<A>(start: A, stop: A, step: A) -> RangeStepInclusive<A>
  211. where A: CheckedAdd + PartialOrd + Clone + Zero
  212. {
  213. let rev = step < Zero::zero();
  214. RangeStepInclusive{state: start, stop: stop, step: step, rev: rev, done: false}
  215. }
  216. impl<A> Iterator for RangeStepInclusive<A>
  217. where A: CheckedAdd + PartialOrd + Clone + PartialEq
  218. {
  219. type Item = A;
  220. #[inline]
  221. fn next(&mut self) -> Option<A> {
  222. if !self.done && ((self.rev && self.state >= self.stop) ||
  223. (!self.rev && self.state <= self.stop)) {
  224. let result = self.state.clone();
  225. match self.state.checked_add(&self.step) {
  226. Some(x) => self.state = x,
  227. None => self.done = true
  228. }
  229. Some(result)
  230. } else {
  231. None
  232. }
  233. }
  234. }
  235. #[cfg(test)]
  236. mod tests {
  237. use std::usize;
  238. use std::ops::{Add, Mul};
  239. use std::cmp::Ordering;
  240. use {One, ToPrimitive};
  241. #[test]
  242. fn test_range() {
  243. /// A mock type to check Range when ToPrimitive returns None
  244. struct Foo;
  245. impl ToPrimitive for Foo {
  246. fn to_i64(&self) -> Option<i64> { None }
  247. fn to_u64(&self) -> Option<u64> { None }
  248. }
  249. impl Add<Foo> for Foo {
  250. type Output = Foo;
  251. fn add(self, _: Foo) -> Foo {
  252. Foo
  253. }
  254. }
  255. impl PartialEq for Foo {
  256. fn eq(&self, _: &Foo) -> bool {
  257. true
  258. }
  259. }
  260. impl PartialOrd for Foo {
  261. fn partial_cmp(&self, _: &Foo) -> Option<Ordering> {
  262. None
  263. }
  264. }
  265. impl Clone for Foo {
  266. fn clone(&self) -> Foo {
  267. Foo
  268. }
  269. }
  270. impl Mul<Foo> for Foo {
  271. type Output = Foo;
  272. fn mul(self, _: Foo) -> Foo {
  273. Foo
  274. }
  275. }
  276. impl One for Foo {
  277. fn one() -> Foo {
  278. Foo
  279. }
  280. }
  281. assert!(super::range(0, 5).collect::<Vec<isize>>() == vec![0, 1, 2, 3, 4]);
  282. assert!(super::range(-10, -1).collect::<Vec<isize>>() ==
  283. vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]);
  284. assert!(super::range(0, 5).rev().collect::<Vec<isize>>() == vec![4, 3, 2, 1, 0]);
  285. assert_eq!(super::range(200, -5).count(), 0);
  286. assert_eq!(super::range(200, -5).rev().count(), 0);
  287. assert_eq!(super::range(200, 200).count(), 0);
  288. assert_eq!(super::range(200, 200).rev().count(), 0);
  289. assert_eq!(super::range(0, 100).size_hint(), (100, Some(100)));
  290. // this test is only meaningful when sizeof usize < sizeof u64
  291. assert_eq!(super::range(usize::MAX - 1, usize::MAX).size_hint(), (1, Some(1)));
  292. assert_eq!(super::range(-10, -1).size_hint(), (9, Some(9)));
  293. }
  294. #[test]
  295. fn test_range_inclusive() {
  296. assert!(super::range_inclusive(0, 5).collect::<Vec<isize>>() ==
  297. vec![0, 1, 2, 3, 4, 5]);
  298. assert!(super::range_inclusive(0, 5).rev().collect::<Vec<isize>>() ==
  299. vec![5, 4, 3, 2, 1, 0]);
  300. assert_eq!(super::range_inclusive(200, -5).count(), 0);
  301. assert_eq!(super::range_inclusive(200, -5).rev().count(), 0);
  302. assert!(super::range_inclusive(200, 200).collect::<Vec<isize>>() == vec![200]);
  303. assert!(super::range_inclusive(200, 200).rev().collect::<Vec<isize>>() == vec![200]);
  304. }
  305. #[test]
  306. fn test_range_step() {
  307. assert!(super::range_step(0, 20, 5).collect::<Vec<isize>>() ==
  308. vec![0, 5, 10, 15]);
  309. assert!(super::range_step(20, 0, -5).collect::<Vec<isize>>() ==
  310. vec![20, 15, 10, 5]);
  311. assert!(super::range_step(20, 0, -6).collect::<Vec<isize>>() ==
  312. vec![20, 14, 8, 2]);
  313. assert!(super::range_step(200u8, 255, 50).collect::<Vec<u8>>() ==
  314. vec![200u8, 250]);
  315. assert!(super::range_step(200, -5, 1).collect::<Vec<isize>>() == vec![]);
  316. assert!(super::range_step(200, 200, 1).collect::<Vec<isize>>() == vec![]);
  317. }
  318. #[test]
  319. fn test_range_step_inclusive() {
  320. assert!(super::range_step_inclusive(0, 20, 5).collect::<Vec<isize>>() ==
  321. vec![0, 5, 10, 15, 20]);
  322. assert!(super::range_step_inclusive(20, 0, -5).collect::<Vec<isize>>() ==
  323. vec![20, 15, 10, 5, 0]);
  324. assert!(super::range_step_inclusive(20, 0, -6).collect::<Vec<isize>>() ==
  325. vec![20, 14, 8, 2]);
  326. assert!(super::range_step_inclusive(200u8, 255, 50).collect::<Vec<u8>>() ==
  327. vec![200u8, 250]);
  328. assert!(super::range_step_inclusive(200, -5, 1).collect::<Vec<isize>>() ==
  329. vec![]);
  330. assert!(super::range_step_inclusive(200, 200, 1).collect::<Vec<isize>>() ==
  331. vec![200]);
  332. }
  333. }