alloc: fix Debug implementation of ExtractIf

This commit is contained in:
joboet 2025-09-25 17:48:08 +02:00
parent caccb4d036
commit 09097128c3
No known key found for this signature in database
GPG key ID: 704E0149B0194B3C
2 changed files with 25 additions and 1 deletions

View file

@ -115,7 +115,20 @@ where
A: Allocator,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let peek = if self.idx < self.end { self.vec.get(self.idx) } else { None };
let peek = if self.idx < self.end {
// This has to use pointer arithmetic as `self.vec[self.idx]` or
// `self.vec.get_unchecked(self.idx)` wouldn't work since we
// temporarily set the length of `self.vec` to zero.
//
// SAFETY:
// Since `self.idx` is smaller than `self.end` and `self.end` is
// smaller than `self.old_len`, `idx` is valid for indexing the
// buffer. Also, per the invariant of `self.idx`, this element
// has not been inspected/moved out yet.
Some(unsafe { &*self.vec.as_ptr().add(self.idx) })
} else {
None
};
f.debug_struct("ExtractIf").field("peek", &peek).finish_non_exhaustive()
}
}

View file

@ -1635,6 +1635,17 @@ fn extract_if_unconsumed() {
assert_eq!(vec, [1, 2, 3, 4]);
}
#[test]
fn extract_if_debug() {
let mut vec = vec![1, 2];
let mut drain = vec.extract_if(.., |&mut x| x % 2 != 0);
assert!(format!("{drain:?}").contains("Some(1)"));
drain.next();
assert!(format!("{drain:?}").contains("Some(2)"));
drain.next();
assert!(format!("{drain:?}").contains("None"));
}
#[test]
fn test_reserve_exact() {
// This is all the same as test_reserve