Skip to main content

rustpython_common/
boxvec.rs

1// spell-checker:disable
2//! An unresizable vector backed by a `Box<[T]>`
3
4#![allow(clippy::needless_lifetimes)]
5use alloc::{fmt, slice};
6use core::{
7    borrow::{Borrow, BorrowMut},
8    cmp,
9    mem::{self, MaybeUninit},
10    ops::{Bound, Deref, DerefMut, RangeBounds},
11    ptr,
12};
13
14pub struct BoxVec<T> {
15    xs: Box<[MaybeUninit<T>]>,
16    len: usize,
17}
18
19impl<T> Drop for BoxVec<T> {
20    fn drop(&mut self) {
21        self.clear();
22
23        // MaybeUninit inhibits array's drop
24    }
25}
26
27macro_rules! panic_oob {
28    ($method_name:expr, $index:expr, $len:expr) => {
29        panic!(
30            concat!(
31                "BoxVec::",
32                $method_name,
33                ": index {} is out of bounds in vector of length {}"
34            ),
35            $index, $len
36        )
37    };
38}
39
40impl<T> BoxVec<T> {
41    #[must_use]
42    pub fn new(n: usize) -> Self {
43        Self {
44            xs: Box::new_uninit_slice(n),
45            len: 0,
46        }
47    }
48
49    #[inline]
50    #[must_use]
51    pub const fn len(&self) -> usize {
52        self.len
53    }
54
55    #[inline]
56    #[must_use]
57    pub const fn is_empty(&self) -> bool {
58        self.len() == 0
59    }
60
61    #[inline]
62    #[must_use]
63    pub const fn capacity(&self) -> usize {
64        self.xs.len()
65    }
66
67    #[must_use]
68    pub const fn is_full(&self) -> bool {
69        self.len() == self.capacity()
70    }
71
72    #[must_use]
73    pub const fn remaining_capacity(&self) -> usize {
74        self.capacity() - self.len()
75    }
76
77    pub fn push(&mut self, element: T) {
78        self.try_push(element).unwrap()
79    }
80
81    pub fn try_push(&mut self, element: T) -> Result<(), CapacityError<T>> {
82        if self.len() < self.capacity() {
83            unsafe {
84                self.push_unchecked(element);
85            }
86            Ok(())
87        } else {
88            Err(CapacityError::new(element))
89        }
90    }
91
92    /// # Safety
93    /// Must ensure that self.len() < self.capacity()
94    pub unsafe fn push_unchecked(&mut self, element: T) {
95        let len = self.len();
96        debug_assert!(len < self.capacity());
97        // SAFETY: len < capacity
98        unsafe {
99            ptr::write(self.get_unchecked_ptr(len), element);
100            self.set_len(len + 1);
101        }
102    }
103
104    /// Get pointer to where element at `index` would be
105    unsafe fn get_unchecked_ptr(&mut self, index: usize) -> *mut T {
106        unsafe { self.xs.as_mut_ptr().add(index).cast() }
107    }
108
109    pub fn insert(&mut self, index: usize, element: T) {
110        self.try_insert(index, element).unwrap()
111    }
112
113    pub fn try_insert(&mut self, index: usize, element: T) -> Result<(), CapacityError<T>> {
114        if index > self.len() {
115            panic_oob!("try_insert", index, self.len())
116        }
117        if self.len() == self.capacity() {
118            return Err(CapacityError::new(element));
119        }
120        let len = self.len();
121
122        // follows is just like Vec<T>
123        unsafe {
124            // infallible
125            // The spot to put the new value
126            {
127                let p: *mut _ = self.get_unchecked_ptr(index);
128                // Shift everything over to make space. (Duplicating the
129                // `index`th element into two consecutive places.)
130                ptr::copy(p, p.add(1), len - index);
131                // Write it in, overwriting the first copy of the `index`th
132                // element.
133                ptr::write(p, element);
134            }
135            self.set_len(len + 1);
136        }
137        Ok(())
138    }
139
140    pub fn pop(&mut self) -> Option<T> {
141        if self.is_empty() {
142            return None;
143        }
144        unsafe {
145            let new_len = self.len() - 1;
146            self.set_len(new_len);
147            Some(ptr::read(self.get_unchecked_ptr(new_len)))
148        }
149    }
150
151    pub fn swap_remove(&mut self, index: usize) -> T {
152        self.swap_pop(index)
153            .unwrap_or_else(|| panic_oob!("swap_remove", index, self.len()))
154    }
155
156    pub fn swap_pop(&mut self, index: usize) -> Option<T> {
157        let len = self.len();
158        if index >= len {
159            return None;
160        }
161        self.swap(index, len - 1);
162        self.pop()
163    }
164
165    pub fn remove(&mut self, index: usize) -> T {
166        self.pop_at(index)
167            .unwrap_or_else(|| panic_oob!("remove", index, self.len()))
168    }
169
170    pub fn pop_at(&mut self, index: usize) -> Option<T> {
171        if index >= self.len() {
172            None
173        } else {
174            self.drain(index..=index).next()
175        }
176    }
177
178    pub fn truncate(&mut self, new_len: usize) {
179        unsafe {
180            if new_len < self.len() {
181                let tail: *mut [_] = &mut self[new_len..];
182                self.len = new_len;
183                ptr::drop_in_place(tail);
184            }
185        }
186    }
187
188    /// Remove all elements in the vector.
189    pub fn clear(&mut self) {
190        self.truncate(0)
191    }
192
193    /// Retains only the elements specified by the predicate.
194    ///
195    /// In other words, remove all elements `e` such that `f(&mut e)` returns false.
196    /// This method operates in place and preserves the order of the retained
197    /// elements.
198    pub fn retain<F>(&mut self, mut f: F)
199    where
200        F: FnMut(&mut T) -> bool,
201    {
202        let len = self.len();
203        let mut del = 0;
204        {
205            let v = &mut **self;
206
207            for i in 0..len {
208                if !f(&mut v[i]) {
209                    del += 1;
210                } else if del > 0 {
211                    v.swap(i - del, i);
212                }
213            }
214        }
215        if del > 0 {
216            self.drain(len - del..);
217        }
218    }
219
220    /// Set the vector’s length without dropping or moving out elements
221    ///
222    /// This method is `unsafe` because it changes the notion of the
223    /// number of “valid” elements in the vector. Use with care.
224    ///
225    /// This method uses *debug assertions* to check that `length` is
226    /// not greater than the capacity.
227    ///
228    /// # Safety
229    /// Must ensure that length <= self.capacity()
230    pub unsafe fn set_len(&mut self, length: usize) {
231        debug_assert!(length <= self.capacity());
232        self.len = length;
233    }
234
235    /// Copy and appends all elements in a slice to the `BoxVec`.
236    ///
237    /// # Errors
238    ///
239    /// This method will return an error if the capacity left (see
240    /// [`remaining_capacity`]) is smaller then the length of the provided
241    /// slice.
242    ///
243    /// [`remaining_capacity`]: #method.remaining_capacity
244    pub fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), CapacityError>
245    where
246        T: Copy,
247    {
248        if self.remaining_capacity() < other.len() {
249            return Err(CapacityError::new(()));
250        }
251
252        let self_len = self.len();
253        let other_len = other.len();
254
255        unsafe {
256            let dst = self.as_mut_ptr().add(self_len);
257            ptr::copy_nonoverlapping(other.as_ptr(), dst, other_len);
258            self.set_len(self_len + other_len);
259        }
260        Ok(())
261    }
262
263    /// Create a draining iterator that removes the specified range in the vector
264    /// and yields the removed items from start to end. The element range is
265    /// removed even if the iterator is not consumed until the end.
266    ///
267    /// Note: It is unspecified how many elements are removed from the vector,
268    /// if the `Drain` value is leaked.
269    ///
270    /// **Panics** if the starting point is greater than the end point or if
271    /// the end point is greater than the length of the vector.
272    pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
273    where
274        R: RangeBounds<usize>,
275    {
276        // Memory safety
277        //
278        // When the Drain is first created, it shortens the length of
279        // the source vector to make sure no uninitialized or moved-from elements
280        // are accessible at all if the Drain's destructor never gets to run.
281        //
282        // Drain will ptr::read out the values to remove.
283        // When finished, remaining tail of the vec is copied back to cover
284        // the hole, and the vector length is restored to the new length.
285        //
286        let len = self.len();
287        let start = match range.start_bound() {
288            Bound::Unbounded => 0,
289            Bound::Included(&i) => i,
290            Bound::Excluded(&i) => i.saturating_add(1),
291        };
292        let end = match range.end_bound() {
293            Bound::Excluded(&j) => j,
294            Bound::Included(&j) => j.saturating_add(1),
295            Bound::Unbounded => len,
296        };
297        self.drain_range(start, end)
298    }
299
300    fn drain_range(&mut self, start: usize, end: usize) -> Drain<'_, T> {
301        let len = self.len();
302
303        // bounds check happens here (before length is changed!)
304        let range_slice: *const _ = &self[start..end];
305
306        // Calling `set_len` creates a fresh and thus unique mutable references, making all
307        // older aliases we created invalid. So we cannot call that function.
308        self.len = start;
309
310        unsafe {
311            Drain {
312                tail_start: end,
313                tail_len: len - end,
314                iter: (*range_slice).iter(),
315                vec: ptr::NonNull::from(self),
316            }
317        }
318    }
319
320    /// Return a slice containing all elements of the vector.
321    #[must_use]
322    pub fn as_slice(&self) -> &[T] {
323        self
324    }
325
326    /// Return a mutable slice containing all elements of the vector.
327    pub fn as_mut_slice(&mut self) -> &mut [T] {
328        self
329    }
330
331    /// Return a raw pointer to the vector's buffer.
332    #[inline]
333    #[must_use]
334    pub fn as_ptr(&self) -> *const T {
335        self.xs.as_ptr().cast()
336    }
337
338    /// Return a raw mutable pointer to the vector's buffer.
339    #[inline]
340    pub fn as_mut_ptr(&mut self) -> *mut T {
341        self.xs.as_mut_ptr().cast()
342    }
343}
344
345impl<T> Deref for BoxVec<T> {
346    type Target = [T];
347
348    #[inline]
349    fn deref(&self) -> &[T] {
350        unsafe { slice::from_raw_parts(self.as_ptr(), self.len()) }
351    }
352}
353
354impl<T> DerefMut for BoxVec<T> {
355    #[inline]
356    fn deref_mut(&mut self) -> &mut [T] {
357        let len = self.len();
358        unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), len) }
359    }
360}
361
362/// Iterate the `BoxVec` with references to each element.
363impl<'a, T> IntoIterator for &'a BoxVec<T> {
364    type Item = &'a T;
365    type IntoIter = slice::Iter<'a, T>;
366
367    fn into_iter(self) -> Self::IntoIter {
368        self.iter()
369    }
370}
371
372/// Iterate the `BoxVec` with mutable references to each element.
373impl<'a, T> IntoIterator for &'a mut BoxVec<T> {
374    type Item = &'a mut T;
375    type IntoIter = slice::IterMut<'a, T>;
376
377    fn into_iter(self) -> Self::IntoIter {
378        self.iter_mut()
379    }
380}
381
382/// Iterate the `BoxVec` with each element by value.
383///
384/// The vector is consumed by this operation.
385impl<T> IntoIterator for BoxVec<T> {
386    type Item = T;
387    type IntoIter = IntoIter<T>;
388
389    fn into_iter(self) -> IntoIter<T> {
390        IntoIter { index: 0, v: self }
391    }
392}
393
394/// By-value iterator for `BoxVec`.
395pub struct IntoIter<T> {
396    index: usize,
397    v: BoxVec<T>,
398}
399
400impl<T> Iterator for IntoIter<T> {
401    type Item = T;
402
403    fn next(&mut self) -> Option<T> {
404        if self.index == self.v.len {
405            None
406        } else {
407            unsafe {
408                let index = self.index;
409                self.index += 1;
410                Some(ptr::read(self.v.get_unchecked_ptr(index)))
411            }
412        }
413    }
414
415    fn size_hint(&self) -> (usize, Option<usize>) {
416        let len = self.v.len() - self.index;
417        (len, Some(len))
418    }
419}
420
421impl<T> DoubleEndedIterator for IntoIter<T> {
422    fn next_back(&mut self) -> Option<T> {
423        if self.index == self.v.len {
424            None
425        } else {
426            unsafe {
427                let new_len = self.v.len() - 1;
428                self.v.set_len(new_len);
429                Some(ptr::read(self.v.get_unchecked_ptr(new_len)))
430            }
431        }
432    }
433}
434
435impl<T> ExactSizeIterator for IntoIter<T> {}
436
437impl<T> Drop for IntoIter<T> {
438    fn drop(&mut self) {
439        // panic safety: Set length to 0 before dropping elements.
440        let index = self.index;
441        let len = self.v.len();
442        unsafe {
443            self.v.set_len(0);
444            let elements = slice::from_raw_parts_mut(self.v.get_unchecked_ptr(index), len - index);
445            ptr::drop_in_place(elements);
446        }
447    }
448}
449
450impl<T> fmt::Debug for IntoIter<T>
451where
452    T: fmt::Debug,
453{
454    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455        f.debug_list().entries(&self.v[self.index..]).finish()
456    }
457}
458
459/// A draining iterator for `BoxVec`.
460pub struct Drain<'a, T> {
461    /// Index of tail to preserve
462    tail_start: usize,
463    /// Length of tail
464    tail_len: usize,
465    /// Current remaining range to remove
466    iter: slice::Iter<'a, T>,
467    vec: ptr::NonNull<BoxVec<T>>,
468}
469
470unsafe impl<T: Sync> Sync for Drain<'_, T> {}
471unsafe impl<T: Sync> Send for Drain<'_, T> {}
472
473impl<T> Iterator for Drain<'_, T> {
474    type Item = T;
475
476    fn next(&mut self) -> Option<Self::Item> {
477        self.iter
478            .next()
479            .map(|elt| unsafe { ptr::read(elt as *const _) })
480    }
481
482    fn size_hint(&self) -> (usize, Option<usize>) {
483        self.iter.size_hint()
484    }
485}
486
487impl<T> DoubleEndedIterator for Drain<'_, T> {
488    fn next_back(&mut self) -> Option<Self::Item> {
489        self.iter
490            .next_back()
491            .map(|elt| unsafe { ptr::read(elt as *const _) })
492    }
493}
494
495impl<T> ExactSizeIterator for Drain<'_, T> {}
496
497impl<'a, T> Drain<'a, T> {
498    #[must_use]
499    pub fn as_slice(&self) -> &'a [T] {
500        self.iter.as_slice()
501    }
502}
503
504impl<T> Drop for Drain<'_, T> {
505    fn drop(&mut self) {
506        // len is currently 0 so panicking while dropping will not cause a double drop.
507
508        for _ in self.by_ref() {}
509
510        if self.tail_len > 0 {
511            unsafe {
512                let source_vec = self.vec.as_mut();
513                // memmove back untouched tail, update to new length
514                let start = source_vec.len();
515                let tail = self.tail_start;
516                let src = source_vec.as_ptr().add(tail);
517                let dst = source_vec.as_mut_ptr().add(start);
518                ptr::copy(src, dst, self.tail_len);
519                source_vec.set_len(start + self.tail_len);
520            }
521        }
522    }
523}
524
525struct ScopeExitGuard<T, Data, F>
526where
527    F: FnMut(&Data, &mut T),
528{
529    value: T,
530    data: Data,
531    f: F,
532}
533
534impl<T, Data, F> Drop for ScopeExitGuard<T, Data, F>
535where
536    F: FnMut(&Data, &mut T),
537{
538    fn drop(&mut self) {
539        (self.f)(&self.data, &mut self.value)
540    }
541}
542
543/// Extend the `BoxVec` with an iterator.
544///
545/// Does not extract more items than there is space for. No error
546/// occurs if there are more iterator elements.
547impl<T> Extend<T> for BoxVec<T> {
548    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
549        let take = self.capacity() - self.len();
550        unsafe {
551            let len = self.len();
552            let mut ptr = raw_ptr_add(self.as_mut_ptr(), len);
553            let end_ptr = raw_ptr_add(ptr, take);
554            // Keep the length in a separate variable, write it back on scope
555            // exit. To help the compiler with alias analysis and stuff.
556            // We update the length to handle panic in the iteration of the
557            // user's iterator, without dropping any elements on the floor.
558            let mut guard = ScopeExitGuard {
559                value: &mut self.len,
560                data: len,
561                f: move |&len, self_len| {
562                    **self_len = len;
563                },
564            };
565            let mut iter = iter.into_iter();
566            loop {
567                if core::ptr::eq(ptr, end_ptr) {
568                    break;
569                }
570                if let Some(elt) = iter.next() {
571                    raw_ptr_write(ptr, elt);
572                    ptr = raw_ptr_add(ptr, 1);
573                    guard.data += 1;
574                } else {
575                    break;
576                }
577            }
578        }
579    }
580}
581
582/// Rawptr add but uses arithmetic distance for ZST
583unsafe fn raw_ptr_add<T>(ptr: *mut T, offset: usize) -> *mut T {
584    if mem::size_of::<T>() == 0 {
585        // Special case for ZST
586        (ptr as usize).wrapping_add(offset) as _
587    } else {
588        unsafe { ptr.add(offset) }
589    }
590}
591
592unsafe fn raw_ptr_write<T>(ptr: *mut T, value: T) {
593    if mem::size_of::<T>() == 0 {
594        /* nothing */
595    } else {
596        unsafe { ptr::write(ptr, value) }
597    }
598}
599
600impl<T> Clone for BoxVec<T>
601where
602    T: Clone,
603{
604    fn clone(&self) -> Self {
605        let mut new = Self::new(self.capacity());
606        new.extend(self.iter().cloned());
607        new
608    }
609
610    fn clone_from(&mut self, rhs: &Self) {
611        // recursive case for the common prefix
612        let prefix = cmp::min(self.len(), rhs.len());
613        self[..prefix].clone_from_slice(&rhs[..prefix]);
614
615        if prefix < self.len() {
616            // rhs was shorter
617            for _ in 0..self.len() - prefix {
618                self.pop();
619            }
620        } else {
621            let rhs_elems = rhs[self.len()..].iter().cloned();
622            self.extend(rhs_elems);
623        }
624    }
625}
626
627impl<T> PartialEq for BoxVec<T>
628where
629    T: PartialEq,
630{
631    fn eq(&self, other: &Self) -> bool {
632        **self == **other
633    }
634}
635
636impl<T> PartialEq<[T]> for BoxVec<T>
637where
638    T: PartialEq,
639{
640    fn eq(&self, other: &[T]) -> bool {
641        **self == *other
642    }
643}
644
645impl<T> Eq for BoxVec<T> where T: Eq {}
646
647impl<T> Borrow<[T]> for BoxVec<T> {
648    fn borrow(&self) -> &[T] {
649        self
650    }
651}
652
653impl<T> BorrowMut<[T]> for BoxVec<T> {
654    fn borrow_mut(&mut self) -> &mut [T] {
655        self
656    }
657}
658
659impl<T> AsRef<[T]> for BoxVec<T> {
660    fn as_ref(&self) -> &[T] {
661        self
662    }
663}
664
665impl<T> AsMut<[T]> for BoxVec<T> {
666    fn as_mut(&mut self) -> &mut [T] {
667        self
668    }
669}
670
671impl<T> fmt::Debug for BoxVec<T>
672where
673    T: fmt::Debug,
674{
675    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
676        (**self).fmt(f)
677    }
678}
679
680/// Error value indicating insufficient capacity
681#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
682pub struct CapacityError<T = ()> {
683    element: T,
684}
685
686impl<T> CapacityError<T> {
687    /// Create a new `CapacityError` from `element`.
688    pub const fn new(element: T) -> Self {
689        Self { element }
690    }
691
692    /// Extract the overflowing element
693    pub fn element(self) -> T {
694        self.element
695    }
696
697    /// Convert into a `CapacityError` that does not carry an element.
698    pub fn simplify(self) -> CapacityError {
699        CapacityError { element: () }
700    }
701}
702
703const CAPERROR: &str = "insufficient capacity";
704
705impl<T> core::error::Error for CapacityError<T> {}
706
707impl<T> fmt::Display for CapacityError<T> {
708    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
709        write!(f, "{CAPERROR}")
710    }
711}
712
713impl<T> fmt::Debug for CapacityError<T> {
714    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
715        write!(f, "capacity error: {CAPERROR}")
716    }
717}