Skip to content

Commit 37206a2

Browse files
committed
add tests for iter::Cloned optimizations
1 parent fe6ff67 commit 37206a2

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

library/core/tests/iter/adapters/cloned.rs

+36
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
use core::iter::*;
2+
use core::ops::Drop;
3+
use core::sync::atomic::{AtomicUsize, Ordering};
24

35
#[test]
46
fn test_cloned() {
@@ -34,6 +36,40 @@ fn test_cloned_side_effects() {
3436
assert_eq!(count, 2);
3537
}
3638

39+
#[test]
40+
fn test_cloned_clone_elision() {
41+
static CLONE_COUNTER: AtomicUsize = AtomicUsize::new(0);
42+
43+
struct CloneWitness;
44+
45+
impl Clone for CloneWitness {
46+
fn clone(&self) -> Self {
47+
CloneWitness
48+
}
49+
}
50+
51+
impl Drop for CloneWitness {
52+
fn drop(&mut self) {
53+
CLONE_COUNTER.fetch_add(1, Ordering::Relaxed);
54+
}
55+
}
56+
57+
let ary: [CloneWitness; 5] = core::array::from_fn(|_| CloneWitness);
58+
let iter = ary.iter();
59+
iter.clone().cloned().skip(4).next();
60+
assert_eq!(CLONE_COUNTER.swap(0, Ordering::Relaxed), 1);
61+
iter.clone().cloned().last();
62+
assert_eq!(CLONE_COUNTER.swap(0, Ordering::Relaxed), 1);
63+
iter.clone().cloned().nth(4);
64+
assert_eq!(CLONE_COUNTER.swap(0, Ordering::Relaxed), 1);
65+
iter.clone().cloned().take(2).next_back();
66+
assert_eq!(CLONE_COUNTER.swap(0, Ordering::Relaxed), 1);
67+
iter.clone().cloned().count();
68+
assert_eq!(CLONE_COUNTER.swap(0, Ordering::Relaxed), 0);
69+
let _ = iter.clone().cloned().advance_by(5);
70+
assert_eq!(CLONE_COUNTER.swap(0, Ordering::Relaxed), 0);
71+
}
72+
3773
#[test]
3874
fn test_cloned_try_folds() {
3975
let a = [1, 2, 3, 4, 5, 6, 7, 8, 9];

0 commit comments

Comments
 (0)