Skip to content

Commit 0909712

Browse files
committed
alloc: fix Debug implementation of ExtractIf
1 parent caccb4d commit 0909712

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

library/alloc/src/vec/extract_if.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,20 @@ where
115115
A: Allocator,
116116
{
117117
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118-
let peek = if self.idx < self.end { self.vec.get(self.idx) } else { None };
118+
let peek = if self.idx < self.end {
119+
// This has to use pointer arithmetic as `self.vec[self.idx]` or
120+
// `self.vec.get_unchecked(self.idx)` wouldn't work since we
121+
// temporarily set the length of `self.vec` to zero.
122+
//
123+
// SAFETY:
124+
// Since `self.idx` is smaller than `self.end` and `self.end` is
125+
// smaller than `self.old_len`, `idx` is valid for indexing the
126+
// buffer. Also, per the invariant of `self.idx`, this element
127+
// has not been inspected/moved out yet.
128+
Some(unsafe { &*self.vec.as_ptr().add(self.idx) })
129+
} else {
130+
None
131+
};
119132
f.debug_struct("ExtractIf").field("peek", &peek).finish_non_exhaustive()
120133
}
121134
}

library/alloctests/tests/vec.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1635,6 +1635,17 @@ fn extract_if_unconsumed() {
16351635
assert_eq!(vec, [1, 2, 3, 4]);
16361636
}
16371637

1638+
#[test]
1639+
fn extract_if_debug() {
1640+
let mut vec = vec![1, 2];
1641+
let mut drain = vec.extract_if(.., |&mut x| x % 2 != 0);
1642+
assert!(format!("{drain:?}").contains("Some(1)"));
1643+
drain.next();
1644+
assert!(format!("{drain:?}").contains("Some(2)"));
1645+
drain.next();
1646+
assert!(format!("{drain:?}").contains("None"));
1647+
}
1648+
16381649
#[test]
16391650
fn test_reserve_exact() {
16401651
// This is all the same as test_reserve

0 commit comments

Comments
 (0)