Skip to main content

alloc/vec/
in_place_drop.rs

1use core::marker::PhantomData;
2use core::ptr::NonNull;
3
4use crate::alloc::Global;
5use crate::raw_vec::RawVec;
6
7// A helper struct for in-place iteration that drops the destination slice of iteration,
8// i.e. the head. The source slice (the tail) is dropped by IntoIter.
9pub(super) struct InPlaceDrop<T> {
10    pub(super) inner: *mut T,
11    pub(super) dst: *mut T,
12}
13
14impl<T> InPlaceDrop<T> {
15    fn len(&self) -> usize {
16        // ignore-tidy-undocumented-unsafe
17        unsafe { self.dst.offset_from_unsigned(self.inner) }
18    }
19}
20
21impl<T> Drop for InPlaceDrop<T> {
22    #[inline]
23    fn drop(&mut self) {
24        // ignore-tidy-undocumented-unsafe
25        unsafe { self.inner.cast_slice(self.len()).drop_in_place() }
26    }
27}
28
29// A helper struct for in-place collection that drops the destination items together with
30// the source allocation - i.e. before the reallocation happened - to avoid leaking them
31// if some other destructor panics.
32pub(super) struct InPlaceDstDataSrcBufDrop<Src, Dest> {
33    pub(super) ptr: NonNull<Dest>,
34    pub(super) len: usize,
35    pub(super) src_cap: usize,
36    pub(super) src: PhantomData<Src>,
37}
38
39impl<Src, Dest> Drop for InPlaceDstDataSrcBufDrop<Src, Dest> {
40    #[inline]
41    fn drop(&mut self) {
42        // ignore-tidy-undocumented-unsafe
43        unsafe {
44            let _drop_allocation =
45                RawVec::<Src>::from_nonnull_in(self.ptr.cast::<Src>(), self.src_cap, Global);
46            self.ptr.as_ptr().cast_slice(self.len).drop_in_place();
47        };
48    }
49}