diff options
| author | kennytm <kennytm@gmail.com> | 2018-02-01 02:34:15 +0800 |
|---|---|---|
| committer | kennytm <kennytm@gmail.com> | 2018-02-01 02:34:15 +0800 |
| commit | af95302d3cb2f5cd59eb38b88eab6a054d965e9f (patch) | |
| tree | f26b25cc9404a7af1260814d824a1c88f454fd57 /src/libcore/tests | |
| parent | 86eb7259539a5dd0763a5703fb948bae6c6b064d (diff) | |
| parent | 4a0da4cf2c7a2b5903fd1b8bc124f8963ce1b535 (diff) | |
| download | rust-af95302d3cb2f5cd59eb38b88eab6a054d965e9f.tar.gz rust-af95302d3cb2f5cd59eb38b88eab6a054d965e9f.zip | |
Rollup merge of #47552 - oberien:stepby-nth, r=dtolnay
Specialize StepBy::nth This allows optimizations of implementations of the inner iterator's `.nth` method.
Diffstat (limited to 'src/libcore/tests')
| -rw-r--r-- | src/libcore/tests/iter.rs | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/libcore/tests/iter.rs b/src/libcore/tests/iter.rs index 8997cf9c6bf..e52e119ff59 100644 --- a/src/libcore/tests/iter.rs +++ b/src/libcore/tests/iter.rs @@ -162,6 +162,68 @@ fn test_iterator_step_by() { } #[test] +fn test_iterator_step_by_nth() { + let mut it = (0..16).step_by(5); + assert_eq!(it.nth(0), Some(0)); + assert_eq!(it.nth(0), Some(5)); + assert_eq!(it.nth(0), Some(10)); + assert_eq!(it.nth(0), Some(15)); + assert_eq!(it.nth(0), None); + + let it = (0..18).step_by(5); + assert_eq!(it.clone().nth(0), Some(0)); + assert_eq!(it.clone().nth(1), Some(5)); + assert_eq!(it.clone().nth(2), Some(10)); + assert_eq!(it.clone().nth(3), Some(15)); + assert_eq!(it.clone().nth(4), None); + assert_eq!(it.clone().nth(42), None); +} + +#[test] +fn test_iterator_step_by_nth_overflow() { + #[cfg(target_pointer_width = "8")] + type Bigger = u16; + #[cfg(target_pointer_width = "16")] + type Bigger = u32; + #[cfg(target_pointer_width = "32")] + type Bigger = u64; + #[cfg(target_pointer_width = "64")] + type Bigger = u128; + + #[derive(Clone)] + struct Test(Bigger); + impl<'a> Iterator for &'a mut Test { + type Item = i32; + fn next(&mut self) -> Option<Self::Item> { Some(21) } + fn nth(&mut self, n: usize) -> Option<Self::Item> { + self.0 += n as Bigger + 1; + Some(42) + } + } + + let mut it = Test(0); + let root = usize::MAX >> (::std::mem::size_of::<usize>() * 8 / 2); + let n = root + 20; + (&mut it).step_by(n).nth(n); + assert_eq!(it.0, n as Bigger * n as Bigger); + + // large step + let mut it = Test(0); + (&mut it).step_by(usize::MAX).nth(5); + assert_eq!(it.0, (usize::MAX as Bigger) * 5); + + // n + 1 overflows + let mut it = Test(0); + (&mut it).step_by(2).nth(usize::MAX); + assert_eq!(it.0, (usize::MAX as Bigger) * 2); + + // n + 1 overflows + let mut it = Test(0); + (&mut it).step_by(1).nth(usize::MAX); + assert_eq!(it.0, (usize::MAX as Bigger) * 1); +} + +#[test] #[should_panic] fn test_iterator_step_by_zero() { let mut it = (0..).step_by(0); |
