in_place_drop.rs - source
Description: Source of the Rust file `library/alloc/src/vec/in_place_drop.rs`.

#
alloc/vec/
in_place_drop.rs

    1use core::marker::PhantomData;
    2use core::ptr::{self, NonNull, drop_in_place};
    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        unsafe { self.dst.offset_from_unsigned(self.inner) }
    17    }
    18}
    19
    20impl<T> Drop for InPlaceDrop<T> {
    21    #[inline]
    22    fn drop(&mut self) {
    23        unsafe {
    24            ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.inner, self.len()));
    25        }
    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        unsafe {
    43            let _drop_allocation =
    44                RawVec::<Src>::from_nonnull_in(self.ptr.cast::<Src>(), self.src_cap, Global);
    45            drop_in_place(core::ptr::slice_from_raw_parts_mut::<Dest>(self.ptr.as_ptr(), self.len));
    46        };
    47    }
    48}