Skip to main content

core/array/
drain.rs

1use crate::marker::{Destruct, PhantomData};
2use crate::mem::{ManuallyDrop, SizedTypeProperties, conjure_zst, transmute};
3use crate::ptr::{NonNull, drop_in_place, from_raw_parts_mut, without_provenance_mut};
4
5impl<'l, 'f, T, U, F: FnMut(T) -> U> Drain<'l, 'f, T, F> {
6    /// This function returns a function that lets you index the given array in const.
7    /// As implemented it can optimize better than iterators, and can be constified.
8    /// It acts like a sort of guard (owns the array) and iterator combined, which can be implemented
9    /// as it is a struct that implements const fn.
10    /// The only method you're really allowed to call is `next()`,
11    /// anything else is more or less UB, hence this function being unsafe.
12    /// Moved elements will not be dropped.
13    /// This will also not actually store the array.
14    ///
15    /// SAFETY: must only be called `N` times. Thou shalt not drop the array either.
16    #[ferrocene::prevalidated]
17    #[rustc_const_unstable(feature = "array_try_map", issue = "79711")]
18    pub(super) const unsafe fn new<const N: usize>(
19        array: &'l mut ManuallyDrop<[T; N]>,
20        f: &'f mut F,
21    ) -> Self {
22        // dont drop the array, transfers "ownership" to Self
23        let ptr: NonNull<T> = NonNull::from_mut(array).cast();
24        // SAFETY:
25        // Adding `slice.len()` to the starting pointer gives a pointer
26        // at the end of `slice`. `end` will never be dereferenced, only checked
27        // for direct pointer equality with `ptr` to check if the drainer is done.
28        unsafe {
29            let end_or_len =
30                if T::IS_ZST { without_provenance_mut(N) } else { ptr.as_ptr().add(N) };
31            Self { ptr, end_or_len, f, l: PhantomData }
32        }
33    }
34}
35
36/// See [`Drain::new`]; this is our fake iterator.
37#[ferrocene::prevalidated]
38#[unstable(feature = "array_try_map", issue = "79711")]
39pub(super) struct Drain<'l, 'f, T, F> {
40    // FIXME(const-hack): This is a slice::IterMut<'l>, replace when possible.
41    /// The pointer to the next element to return, or the past-the-end location
42    /// if the drainer is empty.
43    ///
44    /// This address will be used for all ZST elements, never changed.
45    /// As we "own" this array, we dont need to store any lifetime.
46    ptr: NonNull<T>,
47    /// For non-ZSTs, the non-null pointer to the past-the-end element.
48    /// For ZSTs, this is the number of unprocessed items.
49    end_or_len: *mut T,
50
51    f: &'f mut F,
52    l: PhantomData<&'l mut [T]>,
53}
54
55#[rustc_const_unstable(feature = "array_try_map", issue = "79711")]
56#[unstable(feature = "array_try_map", issue = "79711")]
57const impl<T, U, F> FnOnce<(usize,)> for &mut Drain<'_, '_, T, F>
58where
59    F: [const] FnMut(T) -> U,
60{
61    type Output = U;
62
63    /// This implementation is useless.
64    #[ferrocene::prevalidated]
65    extern "rust-call" fn call_once(mut self, args: (usize,)) -> Self::Output {
66        self.call_mut(args)
67    }
68}
69#[rustc_const_unstable(feature = "array_try_map", issue = "79711")]
70#[unstable(feature = "array_try_map", issue = "79711")]
71const impl<T, U, F> FnMut<(usize,)> for &mut Drain<'_, '_, T, F>
72where
73    F: [const] FnMut(T) -> U,
74{
75    // FIXME(const-hack): ideally this would be an unsafe fn `next()`, and to use it you would instead `|_| unsafe { drain.next() }`.
76    #[ferrocene::prevalidated]
77    extern "rust-call" fn call_mut(
78        &mut self,
79        (_ /* ignore argument */,): (usize,),
80    ) -> Self::Output {
81        if T::IS_ZST {
82            #[expect(ptr_to_integer_transmute_in_consts)]
83            // SAFETY:
84            // This is equivalent to `self.end_or_len.addr`, but that's not
85            // available in `const`. `self.end_or_len` doesn't have provenance,
86            // so transmuting is fine.
87            let len = unsafe { transmute::<*mut T, usize>(self.end_or_len) };
88            // SAFETY:
89            // The caller guarantees that this is never called more than N times
90            // (see `Drain::new`), hence this cannot underflow.
91            self.end_or_len = without_provenance_mut(unsafe { len.unchecked_sub(1) });
92            // its UB to call this more than N times, so returning more ZSTs is valid.
93            // SAFETY: its a ZST? we conjur.
94            (self.f)(unsafe { conjure_zst::<T>() })
95        } else {
96            // increment before moving; if `f` panics, we drop the rest.
97            let p = self.ptr;
98            // SAFETY: caller guarantees never called more than N times (see `Drain::new`)
99            self.ptr = unsafe { self.ptr.add(1) };
100            // SAFETY: we are allowed to move this.
101            (self.f)(unsafe { p.read() })
102        }
103    }
104}
105#[rustc_const_unstable(feature = "array_try_map", issue = "79711")]
106#[unstable(feature = "array_try_map", issue = "79711")]
107const impl<T: [const] Destruct, F> Drop for Drain<'_, '_, T, F> {
108    #[ferrocene::prevalidated]
109    fn drop(&mut self) {
110        let slice = if T::IS_ZST {
111            from_raw_parts_mut::<[T]>(
112                self.ptr.as_ptr(),
113                #[expect(ptr_to_integer_transmute_in_consts)]
114                // SAFETY:
115                // This is equivalent to `self.end_or_len.addr`, but that's not
116                // available in `const`. `self.end_or_len` doesn't have provenance,
117                // so transmuting is fine.
118                unsafe {
119                    transmute::<*mut T, usize>(self.end_or_len)
120                },
121            )
122        } else {
123            // SAFETY: we cant read more than N elements
124            unsafe {
125                from_raw_parts_mut::<[T]>(
126                    self.ptr.as_ptr(),
127                    // SAFETY: `start <= end`
128                    self.end_or_len.offset_from_unsigned(self.ptr.as_ptr()),
129                )
130            }
131        };
132
133        // SAFETY: By the type invariant, we're allowed to drop all these. (we own it, after all)
134        unsafe { drop_in_place(slice) }
135    }
136}