abi_stable/std_types/
vec.rs

1//! Contains an ffi-safe equivalent of `Vec<T>`.
2
3use std::{
4    borrow::{Borrow, BorrowMut, Cow},
5    cmp::Ordering,
6    io,
7    iter::FromIterator,
8    marker::PhantomData,
9    mem::{self, ManuallyDrop},
10    ops::{Bound, Deref, DerefMut, Index, IndexMut, RangeBounds},
11    ptr::{self, NonNull},
12    slice::SliceIndex,
13};
14
15use serde::{Deserialize, Deserializer, Serialize, Serializer};
16
17use core_extensions::SelfOps;
18
19use crate::{
20    pointer_trait::CanTransmuteElement,
21    prefix_type::WithMetadata,
22    sabi_types::RMut,
23    std_types::{
24        utypeid::{new_utypeid, UTypeId},
25        RSlice, RSliceMut,
26    },
27};
28
29#[cfg(test)]
30// #[cfg(all(test, not(feature = "only_new_tests")))]
31mod tests;
32
33mod iters;
34
35use self::iters::{DrainFilter, RawValIter};
36
37pub use self::iters::{Drain, IntoIter};
38
39mod private {
40    use super::*;
41
42    /// Ffi-safe equivalent of `std::vec::Vec`.
43    ///
44    /// # Example
45    ///
46    /// Here is a function that partitions numbers by whether they are even or odd.
47    ///
48    /// ```
49    ///
50    /// use abi_stable::{
51    ///     sabi_extern_fn,
52    ///     std_types::{RSlice, RVec},
53    ///     StableAbi,
54    /// };
55    ///
56    /// #[repr(C)]
57    /// #[derive(StableAbi)]
58    /// pub struct Partitioned {
59    ///     pub even: RVec<u32>,
60    ///     pub odd: RVec<u32>,
61    /// }
62    ///
63    /// #[sabi_extern_fn]
64    /// pub fn partition_evenness(numbers: RSlice<'_, u32>) -> Partitioned {
65    ///     let (even, odd) = numbers.iter().cloned().partition(|n| *n % 2 == 0);
66    ///
67    ///     Partitioned { even, odd }
68    /// }
69    ///
70    /// ```
71    ///
72    #[repr(C)]
73    #[derive(StableAbi)]
74    // #[sabi(debug_print)]
75    pub struct RVec<T> {
76        // using this to make `Option<RVec<T>>` smaller (not ffi-safe though),
77        // and to make `RVec<T>` covariant over `T`.
78        pub(super) buffer: NonNull<T>,
79        pub(super) length: usize,
80        capacity: usize,
81        vtable: VecVTable_Ref,
82        _marker: PhantomData<T>,
83    }
84
85    impl<T> RVec<T> {
86        /// Creates a new, empty `RVec<T>`.
87        ///
88        /// This function does not allocate.
89        ///
90        /// # Example
91        ///
92        /// ```
93        /// use abi_stable::std_types::RVec;
94        ///
95        /// let list = RVec::<u32>::new();
96        ///
97        /// ```
98        pub const fn new() -> Self {
99            Self::NEW
100        }
101
102        const NEW: Self = {
103            // unsafety:
104            // While this implementation is correct,
105            // it would be better to do `RVec::from_vec(Vec::new())`
106            // when it's possible to call `Vec::{as_mut_ptr, capacity, len}` in const contexts.
107            RVec {
108                vtable: VTableGetter::<T>::LIB_VTABLE,
109                buffer: NonNull::dangling(),
110                length: 0,
111                capacity: 0_usize.wrapping_sub((std::mem::size_of::<T>() == 0) as usize),
112                _marker: PhantomData,
113            }
114        };
115
116        #[allow(dead_code)]
117        // Used to test functions that change behavior when the vtable changes
118        pub(super) fn set_vtable_for_testing(mut self) -> Self {
119            self.vtable = VTableGetter::<T>::LIB_VTABLE_FOR_TESTING;
120            self
121        }
122
123        #[inline(always)]
124        pub(super) const fn vtable(&self) -> VecVTable_Ref {
125            self.vtable
126        }
127
128        #[inline(always)]
129        pub(super) const fn buffer(&self) -> *const T {
130            self.buffer.as_ptr()
131        }
132
133        pub(super) fn buffer_mut(&mut self) -> *mut T {
134            self.buffer.as_ptr()
135        }
136
137        /// This returns the amount of elements this RVec can store without reallocating.
138        ///
139        /// # Example
140        ///
141        /// ```
142        /// use abi_stable::std_types::RVec;
143        ///
144        /// let mut list = RVec::new();
145        ///
146        /// assert_eq!(list.capacity(), 0);
147        ///
148        /// list.push(0);
149        /// assert_ne!(list.capacity(), 0);
150        ///
151        /// ```
152        #[inline(always)]
153        pub const fn capacity(&self) -> usize {
154            self.capacity
155        }
156
157        /// Constructs a vec to do operations on the underlying buffer.
158        ///
159        /// # Safety
160        ///
161        /// This must not be called outside of functions that get stored in the vtable.
162        pub(super) unsafe fn with_vec<U, F>(&mut self, f: F) -> U
163        where
164            F: FnOnce(&mut Vec<T>) -> U,
165        {
166            let mut old = mem::replace(self, RVec::new()).piped(ManuallyDrop::new);
167            let mut list =
168                unsafe { Vec::<T>::from_raw_parts(old.buffer_mut(), old.len(), old.capacity()) };
169            let ret = f(&mut list);
170            unsafe {
171                ptr::write(self, list.into());
172            }
173            ret
174        }
175
176        /// Gets a raw pointer to the start of this RVec's buffer.
177        #[inline(always)]
178        pub const fn as_ptr(&self) -> *const T {
179            self.buffer.as_ptr()
180        }
181        /// Gets a mutable raw pointer to the start of this RVec's buffer.
182        #[inline(always)]
183        pub fn as_mut_ptr(&mut self) -> *mut T {
184            self.buffer.as_ptr()
185        }
186    }
187    impl_from_rust_repr! {
188        impl[T] From<Vec<T>> for RVec<T>{
189            fn(this){
190                let mut this = ManuallyDrop::new(this);
191                RVec {
192                    vtable: VTableGetter::<T>::LIB_VTABLE,
193                    buffer: unsafe{ NonNull::new_unchecked(this.as_mut_ptr()) },
194                    length: this.len(),
195                    capacity: this.capacity(),
196                    _marker: PhantomData,
197                }
198            }
199        }
200    }
201}
202
203pub use self::private::RVec;
204
205impl<T> RVec<T> {
206    /// Creates a new, empty `RVec<T>`, with a capacity of `cap`.
207    ///
208    /// This function does not allocate if `cap == 0`.
209    ///
210    /// # Example
211    ///
212    /// ```
213    /// use abi_stable::std_types::RVec;
214    ///
215    /// let mut list = RVec::<u32>::with_capacity(7);
216    ///
217    /// assert_eq!(list.len(), 0);
218    /// assert_eq!(list.capacity(), 7);
219    ///
220    /// list.extend(std::iter::repeat(11).take(7));
221    /// assert_eq!(list.len(), 7);
222    /// assert_eq!(list.capacity(), 7);
223    ///
224    /// list.push(17);
225    /// assert_ne!(list.capacity(), 7);
226    /// ```
227    pub fn with_capacity(cap: usize) -> Self {
228        Vec::with_capacity(cap).into()
229    }
230
231    /// Creates an `RSlice<'a, T>` with access to the `range` range of
232    /// elements of the `RVec<T>`.
233    ///
234    /// # Example
235    ///
236    /// ```
237    /// use abi_stable::std_types::{RSlice, RVec};
238    ///
239    /// let list = RVec::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8]);
240    ///
241    /// assert_eq!(
242    ///     list.slice(..),
243    ///     RSlice::from_slice(&[0, 1, 2, 3, 4, 5, 6, 7, 8])
244    /// );
245    /// assert_eq!(list.slice(..4), RSlice::from_slice(&[0, 1, 2, 3]));
246    /// assert_eq!(list.slice(4..), RSlice::from_slice(&[4, 5, 6, 7, 8]));
247    /// assert_eq!(list.slice(4..7), RSlice::from_slice(&[4, 5, 6]));
248    ///
249    /// ```
250    #[inline]
251    #[allow(clippy::needless_lifetimes)]
252    pub fn slice<'a, R>(&'a self, range: R) -> RSlice<'a, T>
253    where
254        R: RangeBounds<usize>,
255    {
256        let slice_start = match range.start_bound() {
257            Bound::Unbounded => 0,
258            Bound::Included(&n) => n,
259            Bound::Excluded(&n) => n.saturating_add(1),
260        };
261        let slice_end = match range.end_bound() {
262            Bound::Unbounded => self.length,
263            Bound::Included(&n) => n.saturating_add(1),
264            Bound::Excluded(&n) => n,
265        };
266        (&self[slice_start..slice_end]).into()
267    }
268
269    /// Creates an `RSliceMut<'a, T>` with access to the `range` range of
270    /// elements of the `RVec<T>`.
271    ///
272    /// # Example
273    ///
274    /// ```
275    /// use abi_stable::std_types::{RSliceMut, RVec};
276    ///
277    /// let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8]);
278    ///
279    /// assert_eq!(
280    ///     list.slice_mut(..),
281    ///     RSliceMut::from_mut_slice(&mut [0, 1, 2, 3, 4, 5, 6, 7, 8])
282    /// );
283    /// assert_eq!(
284    ///     list.slice_mut(..4),
285    ///     RSliceMut::from_mut_slice(&mut [0, 1, 2, 3])
286    /// );
287    /// assert_eq!(
288    ///     list.slice_mut(4..),
289    ///     RSliceMut::from_mut_slice(&mut [4, 5, 6, 7, 8])
290    /// );
291    /// assert_eq!(
292    ///     list.slice_mut(4..7),
293    ///     RSliceMut::from_mut_slice(&mut [4, 5, 6])
294    /// );
295    ///
296    /// ```
297    #[inline]
298    #[allow(clippy::needless_lifetimes)]
299    pub fn slice_mut<'a, R>(&'a mut self, range: R) -> RSliceMut<'a, T>
300    where
301        R: RangeBounds<usize>,
302    {
303        let slice_start = match range.start_bound() {
304            Bound::Unbounded => 0,
305            Bound::Included(&n) => n,
306            Bound::Excluded(&n) => n.saturating_add(1),
307        };
308        let slice_end = match range.end_bound() {
309            Bound::Unbounded => self.length,
310            Bound::Included(&n) => n.saturating_add(1),
311            Bound::Excluded(&n) => n,
312        };
313        (&mut self[slice_start..slice_end]).into()
314    }
315
316    conditionally_const! {
317        feature = "rust_1_64"
318        /// Creates a `&[T]` with access to all the elements of the `RVec<T>`.
319        ///
320        ;
321        ///
322        /// # Example
323        ///
324        /// ```
325        /// use abi_stable::std_types::RVec;
326        ///
327        /// let list = RVec::from(vec![0, 1, 2, 3]);
328        /// assert_eq!(list.as_slice(), &[0, 1, 2, 3]);
329        ///
330        /// ```
331        pub fn as_slice(&self) -> &[T] {
332            unsafe { ::std::slice::from_raw_parts(self.buffer(), self.len()) }
333        }
334    }
335
336    /// Creates a `&mut [T]` with access to all the elements of the `RVec<T>`.
337    ///
338    /// # Example
339    ///
340    /// ```
341    /// use abi_stable::std_types::RVec;
342    ///
343    /// let mut list = RVec::from(vec![0, 1, 2, 3]);
344    /// assert_eq!(list.as_mut_slice(), &mut [0, 1, 2, 3]);
345    ///
346    /// ```
347    pub fn as_mut_slice(&mut self) -> &mut [T] {
348        let len = self.len();
349        unsafe { ::std::slice::from_raw_parts_mut(self.buffer_mut(), len) }
350    }
351
352    /// Creates an `RSlice<'_, T>` with access to all the elements of the `RVec<T>`.
353    ///
354    /// # Example
355    ///
356    /// ```
357    /// use abi_stable::std_types::{RSlice, RVec};
358    ///
359    /// let list = RVec::from(vec![0, 1, 2, 3]);
360    /// assert_eq!(list.as_rslice(), RSlice::from_slice(&[0, 1, 2, 3]));
361    ///
362    /// ```
363    pub const fn as_rslice(&self) -> RSlice<'_, T> {
364        unsafe { RSlice::from_raw_parts(self.as_ptr(), self.len()) }
365    }
366
367    /// Creates an `RSliceMut<'_, T>` with access to all the elements of the `RVec<T>`.
368    ///
369    /// # Example
370    ///
371    /// ```
372    /// use abi_stable::std_types::{RSliceMut, RVec};
373    ///
374    /// let mut list = RVec::from(vec![0, 1, 2, 3]);
375    /// assert_eq!(
376    ///     list.as_mut_rslice(),
377    ///     RSliceMut::from_mut_slice(&mut [0, 1, 2, 3])
378    /// );
379    ///
380    /// ```
381    pub fn as_mut_rslice(&mut self) -> RSliceMut<'_, T> {
382        self.as_mut_slice().into()
383    }
384
385    /// Returns the amount of elements of the `RVec<T>`.
386    ///
387    /// # Example
388    ///
389    /// ```
390    /// use abi_stable::std_types::RVec;
391    ///
392    /// let mut list = RVec::<u64>::new();
393    ///
394    /// assert_eq!(list.len(), 0);
395    ///
396    /// list.push(0xDEAFBEEF);
397    /// assert_eq!(list.len(), 1);
398    ///
399    /// list.push(0xCAFE);
400    /// assert_eq!(list.len(), 2);
401    ///
402    /// ```
403    #[inline(always)]
404    pub const fn len(&self) -> usize {
405        self.length
406    }
407
408    /// Sets the length field of `RVec<T>` to `new_len`.
409    ///
410    /// # Safety
411    ///
412    /// `new_len` must be less than or equal to `self.capacity()`.
413    ///
414    /// The elements betweem the old length and the new length must be initialized.
415    ///
416    /// # Example
417    ///
418    /// ```
419    /// use abi_stable::std_types::RVec;
420    ///
421    /// let mut list = RVec::<u64>::new();
422    ///
423    /// list.reserve_exact(10);
424    ///
425    /// unsafe {
426    ///     let start = list.as_mut_ptr();
427    ///     for i in 0..10 {
428    ///         start.add(i as usize).write(i);
429    ///     }
430    ///     list.set_len(10);
431    /// }
432    ///
433    /// assert_eq!(list, (0..10).collect::<RVec<u64>>());
434    ///
435    /// ```
436    pub unsafe fn set_len(&mut self, new_len: usize) {
437        self.length = new_len;
438    }
439
440    /// Shrinks the capacity of the `RVec` to match its length.
441    ///
442    /// # Example
443    ///
444    /// ```
445    /// use abi_stable::std_types::RVec;
446    ///
447    /// let mut list = RVec::<u32>::with_capacity(7);
448    ///
449    /// list.extend(std::iter::repeat(11).take(4));
450    /// assert_eq!(list.len(), 4);
451    /// assert_eq!(list.capacity(), 7);
452    ///
453    /// list.shrink_to_fit();
454    /// assert_eq!(list.len(), 4);
455    /// assert_eq!(list.capacity(), 4);
456    /// ```
457    pub fn shrink_to_fit(&mut self) {
458        let vtable = self.vtable();
459        unsafe {
460            vtable.shrink_to_fit()(RMut::new(self).transmute_element_());
461        }
462    }
463
464    /// Whether the length of the `RVec<T>` is 0.
465    ///
466    /// # Example
467    ///
468    /// ```
469    /// use abi_stable::std_types::RVec;
470    ///
471    /// let mut list = RVec::<u64>::new();
472    ///
473    /// assert_eq!(list.is_empty(), true);
474    ///
475    /// list.push(0x1337);
476    /// assert_eq!(list.is_empty(), false);
477    ///
478    /// list.push(0xC001);
479    /// assert_eq!(list.is_empty(), false);
480    ///
481    /// ```
482    #[inline(always)]
483    pub const fn is_empty(&self) -> bool {
484        self.length == 0
485    }
486
487    /// Converts this `RVec<T>` into a `Vec<T>`.
488    ///
489    /// # Allocation
490    ///
491    /// If this is invoked outside of the dynamic library/binary that created it,
492    /// it will allocate a new `Vec<T>` and move the data into it.
493    ///
494    /// # Example
495    ///
496    /// ```
497    /// use abi_stable::std_types::RVec;
498    ///
499    /// let mut list = RVec::<u64>::new();
500    ///
501    /// list.push(0);
502    /// list.push(1);
503    /// list.push(2);
504    ///
505    /// assert_eq!(list.into_vec(), vec![0, 1, 2]);
506    ///
507    /// ```
508    pub fn into_vec(self) -> Vec<T> {
509        let mut this = ManuallyDrop::new(self);
510
511        unsafe {
512            let this_vtable = this.vtable();
513            let other_vtable = VTableGetter::<T>::LIB_VTABLE;
514            if ::std::ptr::eq(this_vtable.0.to_raw_ptr(), other_vtable.0.to_raw_ptr())
515                || this_vtable.type_id()() == other_vtable.type_id()()
516            {
517                Vec::from_raw_parts(this.buffer_mut(), this.len(), this.capacity())
518            } else {
519                let len = this.length;
520                let mut ret = Vec::with_capacity(len);
521                ptr::copy_nonoverlapping(this.as_ptr(), ret.as_mut_ptr(), len);
522                ret.set_len(len);
523                this.length = 0;
524                ManuallyDrop::drop(&mut this);
525                ret
526            }
527        }
528    }
529
530    /// Creates a `Vec<T>`, copying all the elements of this `RVec<T>`.
531    ///
532    /// # Example
533    ///
534    /// ```
535    /// use abi_stable::std_types::RVec;
536    ///
537    /// let mut list = RVec::<u64>::new();
538    ///
539    /// list.extend((4..=7).rev());
540    ///
541    /// assert_eq!(list.to_vec(), vec![7, 6, 5, 4]);
542    ///
543    /// ```
544    pub fn to_vec(&self) -> Vec<T>
545    where
546        T: Clone,
547    {
548        self.as_slice().to_vec()
549    }
550
551    /// Clones a `&[T]` into a new `RVec<T>`.
552    ///
553    /// This function was defined to aid type inference,
554    /// because eg: `&[0, 1]` is a `&[i32;2]` not a `&[i32]`.
555    ///
556    /// # Example
557    ///
558    /// ```
559    /// use abi_stable::std_types::RVec;
560    ///
561    /// let slic = &[99, 88, 77, 66];
562    /// let list = RVec::<u64>::from_slice(slic);
563    ///
564    /// assert_eq!(list.as_slice(), slic);
565    /// ```
566    #[inline]
567    pub fn from_slice(slic: &[T]) -> RVec<T>
568    where
569        T: Clone,
570    {
571        slic.into()
572    }
573
574    /// Inserts the `value` value at `index` position.
575    ///
576    /// # Panics
577    ///
578    /// Panics if `self.len() < index`.
579    ///
580    /// # Example
581    ///
582    /// ```
583    /// use abi_stable::std_types::RVec;
584    ///
585    /// let mut list = RVec::from(vec![0, 1, 2, 3]);
586    ///
587    /// list.insert(2, 22);
588    /// assert_eq!(list.as_slice(), &[0, 1, 22, 2, 3]);
589    ///
590    /// list.insert(5, 55);
591    /// assert_eq!(list.as_slice(), &[0, 1, 22, 2, 3, 55]);
592    ///
593    /// ```
594    pub fn insert(&mut self, index: usize, value: T) {
595        assert!(
596            index <= self.length,
597            "index out of bounds, index={} len={} ",
598            index,
599            self.length
600        );
601        if self.capacity() == self.length {
602            self.grow_capacity_to_1();
603        }
604
605        unsafe {
606            let buffer = self.buffer_mut();
607            if index < self.length {
608                ptr::copy(
609                    buffer.offset(index as isize),
610                    buffer.offset(index as isize + 1),
611                    self.length - index,
612                );
613            }
614            ptr::write(buffer.offset(index as isize), value);
615            self.length += 1;
616        }
617    }
618
619    /// Attemps to remove the element at `index` position,
620    /// returns `None` if `self.len() <= index`.
621    ///
622    /// # Example
623    ///
624    /// ```
625    /// use abi_stable::std_types::RVec;
626    ///
627    /// let mut list = RVec::from(vec![0, 1, 2, 3]);
628    ///
629    /// assert_eq!(list.try_remove(4), None);
630    /// assert_eq!(list.try_remove(3), Some(3));
631    /// assert_eq!(list.try_remove(1), Some(1));
632    ///
633    /// assert_eq!(list.as_slice(), &[0, 2]);
634    /// ```
635    pub fn try_remove(&mut self, index: usize) -> Option<T> {
636        if self.length <= index {
637            return None;
638        }
639        unsafe {
640            let buffer = self.buffer_mut();
641            self.length -= 1;
642            let result = ptr::read(buffer.offset(index as isize));
643            ptr::copy(
644                buffer.offset(index as isize + 1),
645                buffer.offset(index as isize),
646                self.length - index,
647            );
648            Some(result)
649        }
650    }
651
652    /// Removes the element at `index` position,
653    ///
654    /// # Panic
655    ///
656    /// Panics if `self.len() <= index`.
657    ///
658    /// # Example
659    ///
660    /// ```
661    /// use abi_stable::{
662    ///     std_types::{RStr, RVec},
663    ///     traits::IntoReprC,
664    /// };
665    ///
666    /// // This type annotation is purely for the reader.
667    /// let mut list: RVec<RStr<'static>> =
668    ///     vec!["foo".into_c(), "bar".into(), "baz".into()].into_c();
669    ///
670    /// assert_eq!(list.remove(2), "baz".into_c());
671    /// assert_eq!(list.as_slice(), &["foo".into_c(), "bar".into_c()]);
672    ///
673    /// assert_eq!(list.remove(0), "foo".into_c());
674    /// assert_eq!(list.as_slice(), &["bar".into_c()]);
675    /// ```
676    pub fn remove(&mut self, index: usize) -> T {
677        match self.try_remove(index) {
678            Some(x) => x,
679            None => panic!("index out of bounds, index={} len={} ", index, self.length),
680        }
681    }
682
683    /// Swaps the element at `index` position with the last element, and then removes it.
684    ///
685    /// # Panic
686    ///
687    /// Panics if `self.len() <= index`.
688    ///
689    /// # Example
690    ///
691    /// ```
692    /// use abi_stable::{
693    ///     std_types::{RStr, RVec},
694    ///     traits::IntoReprC,
695    /// };
696    ///
697    /// // This type annotation is purely for the reader.
698    /// let mut list: RVec<RStr<'static>> =
699    ///     vec!["foo".into_c(), "bar".into(), "baz".into(), "geo".into()].into_c();
700    ///
701    /// assert_eq!(list.swap_remove(1), "bar".into_c());
702    /// assert_eq!(
703    ///     list.as_slice(),
704    ///     &["foo".into_c(), "geo".into(), "baz".into()]
705    /// );
706    ///
707    /// assert_eq!(list.swap_remove(0), "foo".into_c());
708    /// assert_eq!(list.as_slice(), &["baz".to_string(), "geo".into()]);
709    ///
710    /// ```
711    pub fn swap_remove(&mut self, index: usize) -> T {
712        unsafe {
713            let hole: *mut T = &mut self[index];
714            let last = ptr::read(self.buffer_mut().offset((self.length - 1) as isize));
715            self.length -= 1;
716            ptr::replace(hole, last)
717        }
718    }
719
720    /// Appends `new_val` at the end of the `RVec<T>`.
721    ///
722    /// # Example
723    ///
724    /// ```
725    /// use abi_stable::std_types::RVec;
726    ///
727    /// let mut list = RVec::<u32>::new();
728    ///
729    /// list.push(11);
730    /// assert_eq!(list.as_slice(), &[11]);
731    ///
732    /// list.push(22);
733    /// assert_eq!(list.as_slice(), &[11, 22]);
734    ///
735    /// list.push(55);
736    /// assert_eq!(list.as_slice(), &[11, 22, 55]);
737    ///
738    /// ```
739    pub fn push(&mut self, new_val: T) {
740        if self.length == self.capacity() {
741            self.grow_capacity_to_1();
742        }
743        unsafe {
744            ptr::write(self.buffer_mut().offset(self.length as isize), new_val);
745        }
746        self.length += 1;
747    }
748
749    /// Attempts to remove the last element,
750    /// returns `None` if the `RVec<T>` is empty.
751    ///
752    /// # Example
753    ///
754    /// ```
755    /// use abi_stable::std_types::{RSlice, RVec};
756    ///
757    /// let mut list = RVec::<u32>::from_slice(&[11, 22, 55]);
758    ///
759    /// assert_eq!(list.pop(), Some(55));
760    /// assert_eq!(list.as_slice(), &[11, 22]);
761    ///
762    /// assert_eq!(list.pop(), Some(22));
763    /// assert_eq!(list.as_slice(), &[11]);
764    ///
765    /// assert_eq!(list.pop(), Some(11));
766    /// assert_eq!(list.as_rslice(), RSlice::<u32>::EMPTY);
767    ///
768    /// assert_eq!(list.pop(), None);
769    ///
770    /// ```
771    pub fn pop(&mut self) -> Option<T> {
772        if self.length == 0 {
773            None
774        } else {
775            unsafe {
776                self.length -= 1;
777                Some(ptr::read(self.buffer_mut().offset(self.length as isize)))
778            }
779        }
780    }
781
782    /// Moves all the elements of `other` into `Self`, leaving `other` empty.
783    ///
784    /// # Panics
785    ///
786    /// Panics if the number of elements in the vector overflows a `usize`.
787    ///
788    /// # Examples
789    ///
790    /// ```
791    /// use abi_stable::std_types::{RSlice, RVec};
792    ///
793    /// let mut vec = RVec::from_slice(&[1, 2, 3]);
794    /// let mut vec2 = RVec::from_slice(&[4, 5, 6]);
795    /// vec.append(&mut vec2);
796    /// assert_eq!(vec.as_slice(), &[1, 2, 3, 4, 5, 6]);
797    /// assert_eq!(vec2.as_slice(), RSlice::<u32>::EMPTY);
798    /// ```
799    #[inline]
800    pub fn append(&mut self, other: &mut Self) {
801        unsafe {
802            self.append_elements(other.as_slice() as _);
803            other.set_len(0);
804        }
805    }
806
807    /// Appends elements to `Self` from other buffer.
808    #[inline]
809    unsafe fn append_elements(&mut self, other: *const [T]) {
810        let count = unsafe { (*other).len() };
811        self.reserve(count);
812        let len = self.len();
813        unsafe {
814            ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count);
815        }
816        self.length += count;
817    }
818
819    /// Truncates the `RVec<T>` to `to` length.
820    /// Does nothing if `self.len() <= to`.
821    ///
822    /// Note: this has no effect on the capacity of the `RVec<T>`.
823    ///
824    /// # Example
825    ///
826    /// ```
827    /// use abi_stable::std_types::{RSlice, RVec};
828    ///
829    /// let mut list = RVec::<u32>::from_slice(&[11, 22, 55, 66, 77]);
830    ///
831    /// list.truncate(3);
832    /// assert_eq!(list.as_slice(), &[11, 22, 55]);
833    ///
834    /// list.truncate(0);
835    /// assert_eq!(list.as_rslice(), RSlice::<u32>::EMPTY);
836    ///
837    /// list.truncate(5555); //This is a no-op.
838    /// ```    
839    pub fn truncate(&mut self, to: usize) {
840        if to < self.len() {
841            self.truncate_inner(to);
842        }
843    }
844
845    /// Removes all the elements from collection.
846    ///
847    /// Note: this has no effect on the capacity of the `RVec<T>`.
848    ///
849    /// # Example
850    ///
851    /// ```
852    /// use abi_stable::std_types::{RSlice, RVec};
853    ///
854    /// let mut list = RVec::<u32>::from_slice(&[11, 22, 55]);
855    ///
856    /// assert_eq!(list.as_slice(), &[11, 22, 55]);
857    ///
858    /// list.clear();
859    /// assert_eq!(list.as_rslice(), RSlice::<u32>::EMPTY);
860    /// assert_ne!(list.capacity(), 0);
861    ///
862    /// ```
863    pub fn clear(&mut self) {
864        self.truncate_inner(0);
865    }
866
867    /// Retains only the elements that satisfy the `pred` predicate
868    ///
869    /// This means that a element will be removed if `pred(that_element)`
870    /// returns false.
871    ///
872    /// # Example
873    ///
874    /// ```
875    /// use abi_stable::std_types::RVec;
876    ///
877    /// {
878    ///     let mut list = (0..=10).collect::<Vec<u32>>();
879    ///     list.retain(|x| *x % 3 == 0);
880    ///     assert_eq!(list.as_slice(), &[0, 3, 6, 9]);
881    /// }
882    /// {
883    ///     let mut list = (0..=10).collect::<Vec<u32>>();
884    ///     list.retain(|x| *x % 5 == 0);
885    ///     assert_eq!(list.as_slice(), &[0, 5, 10]);
886    /// }
887    ///
888    /// ```
889    pub fn retain<F>(&mut self, mut pred: F)
890    where
891        F: FnMut(&T) -> bool,
892    {
893        let old_len = self.len();
894        unsafe {
895            self.set_len(0);
896        }
897        DrainFilter {
898            vec_len: &mut self.length,
899            allocation_start: self.buffer.as_ptr(),
900            idx: 0,
901            del: 0,
902            old_len,
903            pred: |x| !pred(x),
904            panic_flag: false,
905        };
906    }
907
908    fn truncate_inner(&mut self, to: usize) {
909        let old_length = self.length;
910        self.length = to;
911        unsafe {
912            ptr::drop_in_place(std::slice::from_raw_parts_mut(
913                self.buffer.as_ptr().add(to),
914                old_length - to,
915            ))
916        }
917    }
918
919    /// Reserves `àdditional` additional capacity for extra elements.
920    /// This may reserve more than necessary for the additional capacity.
921    ///
922    /// # Example
923    ///
924    /// ```
925    /// use abi_stable::std_types::RVec;
926    ///
927    /// let mut list = RVec::<u32>::new();
928    ///
929    /// list.reserve(10);
930    /// assert!(list.capacity() >= 10);
931    ///
932    /// let cap = list.capacity();
933    /// list.extend(0..10);
934    /// assert_eq!(list.capacity(), cap);
935    ///
936    /// ```
937    pub fn reserve(&mut self, additional: usize) {
938        self.resize_capacity(self.len() + additional, Exactness::Above)
939    }
940
941    /// Reserves `àdditional` additional capacity for extra elements.
942    ///
943    /// Prefer using `reserve` for most situations.
944    ///
945    /// # Example
946    ///
947    /// ```
948    /// use abi_stable::std_types::RVec;
949    ///
950    /// let mut list = RVec::<u32>::new();
951    ///
952    /// list.reserve_exact(17);
953    /// assert_eq!(list.capacity(), 17);
954    ///
955    /// let cap = list.capacity();
956    /// list.extend(0..17);
957    /// assert_eq!(list.capacity(), cap);
958    ///
959    /// ```
960    pub fn reserve_exact(&mut self, additional: usize) {
961        self.resize_capacity(self.len() + additional, Exactness::Exact)
962    }
963
964    #[inline]
965    fn grow_capacity_to_1(&mut self) {
966        let vtable = self.vtable();
967        unsafe {
968            let cap = self.capacity() + 1;
969            vtable.grow_capacity_to()(RMut::new(self).transmute_element_(), cap, Exactness::Above);
970        }
971    }
972
973    fn resize_capacity(&mut self, to: usize, exactness: Exactness) {
974        let vtable = self.vtable();
975        if self.capacity() < to {
976            unsafe {
977                vtable.grow_capacity_to()(RMut::new(self).transmute_element_(), to, exactness);
978            }
979        }
980    }
981}
982
983impl<T> RVec<T>
984where
985    T: Clone,
986{
987    /// Resizes the `RVec<T>` to `new_len` length.
988    /// extending the `RVec<T>` with clones of `value`
989    /// to reach the new length.
990    ///
991    /// # Example
992    ///
993    /// ```
994    /// use abi_stable::std_types::RVec;
995    ///
996    /// let mut list = RVec::<u32>::new();
997    ///
998    /// list.resize(5, 88);
999    /// assert_eq!(list.as_slice(), &[88, 88, 88, 88, 88]);
1000    ///
1001    /// list.resize(3, 0);
1002    /// assert_eq!(list.as_slice(), &[88, 88, 88]);
1003    ///
1004    /// list.resize(6, 123);
1005    /// assert_eq!(list.as_slice(), &[88, 88, 88, 123, 123, 123]);
1006    ///
1007    /// ```
1008    pub fn resize(&mut self, new_len: usize, value: T) {
1009        let old_len = self.len();
1010        match new_len.cmp(&old_len) {
1011            Ordering::Less => self.truncate_inner(new_len),
1012            Ordering::Equal => {}
1013            Ordering::Greater => unsafe {
1014                self.resize_capacity(new_len, Exactness::Above);
1015                // Using new_len instead of the capacity because resize_capacity may
1016                // grow the capacity more than requested.
1017                //
1018                // Also replaced usage of slice with raw pointers based on a
1019                // comment mentioning how slices must only reference initialized memory.
1020                let start = self.buffer_mut();
1021                let mut current = start.add(old_len);
1022                let end = start.add(new_len);
1023                while current != end {
1024                    ptr::write(current, value.clone());
1025                    current = current.add(1);
1026                }
1027                self.length = new_len;
1028            },
1029        }
1030    }
1031
1032    /// Extends this `RVec<_>` with clones of the elements of the slice.
1033    ///
1034    /// # Example
1035    ///
1036    /// ```
1037    /// use abi_stable::std_types::RVec;
1038    ///
1039    /// let mut list = RVec::<u64>::new();
1040    ///
1041    /// list.extend_from_slice(&[99, 88]);
1042    /// list.extend_from_slice(&[77, 66]);
1043    ///
1044    /// assert_eq!(list.as_slice(), &[99, 88, 77, 66]);
1045    /// ```
1046    pub fn extend_from_slice(&mut self, slic_: &[T]) {
1047        self.reserve(slic_.len());
1048        for elem in slic_ {
1049            self.push(elem.clone());
1050        }
1051    }
1052}
1053
1054impl<T> RVec<T>
1055where
1056    T: Copy,
1057{
1058    /// Extends this `RVec<_>` with copies of the elements of the slice.
1059    ///
1060    /// # Example
1061    ///
1062    /// ```
1063    /// use abi_stable::{
1064    ///     std_types::{RStr, RVec},
1065    ///     traits::IntoReprC,
1066    /// };
1067    ///
1068    /// let mut list = RVec::<RStr<'_>>::new();
1069    ///
1070    /// list.extend_from_slice(&["foo".into_c(), "bar".into()]);
1071    /// list.extend_from_slice(&["baz".into_c(), "goo".into()]);
1072    ///
1073    /// assert_eq!(
1074    ///     list.as_slice(),
1075    ///     &["foo".into_c(), "bar".into(), "baz".into(), "goo".into()],
1076    /// );
1077    /// ```
1078    pub fn extend_from_copy_slice(&mut self, slic_: &[T]) {
1079        self.reserve(slic_.len());
1080        let old_len = self.len();
1081        unsafe {
1082            let entire: *mut T = self.buffer_mut().offset(old_len as isize);
1083            ptr::copy_nonoverlapping(slic_.as_ptr(), entire, slic_.len());
1084            self.length = old_len + slic_.len();
1085        }
1086    }
1087}
1088
1089impl<T> Clone for RVec<T>
1090where
1091    T: Clone,
1092{
1093    fn clone(&self) -> Self {
1094        self.to_vec().into()
1095    }
1096}
1097
1098impl<T> Default for RVec<T> {
1099    fn default() -> Self {
1100        Vec::new().into()
1101    }
1102}
1103
1104impl<T> Deref for RVec<T> {
1105    type Target = [T];
1106
1107    #[inline]
1108    fn deref(&self) -> &Self::Target {
1109        self.as_slice()
1110    }
1111}
1112
1113impl<T> DerefMut for RVec<T> {
1114    #[inline]
1115    fn deref_mut(&mut self) -> &mut Self::Target {
1116        self.as_mut_slice()
1117    }
1118}
1119
1120impl<T> AsRef<[T]> for RVec<T> {
1121    fn as_ref(&self) -> &[T] {
1122        self
1123    }
1124}
1125impl<T> AsMut<[T]> for RVec<T> {
1126    fn as_mut(&mut self) -> &mut [T] {
1127        self
1128    }
1129}
1130
1131impl<T> Borrow<[T]> for RVec<T> {
1132    fn borrow(&self) -> &[T] {
1133        self
1134    }
1135}
1136
1137impl<T> BorrowMut<[T]> for RVec<T> {
1138    fn borrow_mut(&mut self) -> &mut [T] {
1139        self
1140    }
1141}
1142
1143slice_like_impl_cmp_traits! {
1144    impl[] RVec<T>,
1145    where[];
1146    Vec<U>,
1147    [U],
1148    &[U],
1149    &mut [U],
1150    RSlice<'_, U>,
1151    RSliceMut<'_, U>,
1152}
1153
1154slice_like_impl_cmp_traits! {
1155    impl[const N: usize] RVec<T>,
1156    where[];
1157    [U; N],
1158}
1159
1160slice_like_impl_cmp_traits! {
1161    impl[] RVec<T>,
1162    where[T: Clone, U: Clone];
1163    std::borrow::Cow<'_, [U]>,
1164    crate::std_types::RCowSlice<'_, U>,
1165}
1166
1167shared_impls! {
1168    mod = buffer_impls
1169    new_type = RVec[][T],
1170    original_type = Vec,
1171}
1172
1173impl_into_rust_repr! {
1174    impl[T] Into<Vec<T>> for RVec<T> {
1175        fn(this){
1176            this.into_vec()
1177        }
1178    }
1179}
1180
1181impl<T> From<&[T]> for RVec<T>
1182where
1183    T: Clone,
1184{
1185    fn from(this: &[T]) -> Self {
1186        this.to_vec().into()
1187    }
1188}
1189
1190impl<T> From<&mut [T]> for RVec<T>
1191where
1192    T: Clone,
1193{
1194    fn from(this: &mut [T]) -> Self {
1195        this.to_vec().into()
1196    }
1197}
1198
1199impl From<&str> for RVec<u8> {
1200    fn from(s: &str) -> Self {
1201        From::from(s.as_bytes())
1202    }
1203}
1204
1205impl<'a, T> From<Cow<'a, [T]>> for RVec<T>
1206where
1207    T: Clone,
1208{
1209    fn from(this: Cow<'a, [T]>) -> Self {
1210        this.into_owned().into()
1211    }
1212}
1213
1214unsafe impl<T> Send for RVec<T> where T: Send {}
1215unsafe impl<T> Sync for RVec<T> where T: Sync {}
1216
1217impl<T> Drop for RVec<T> {
1218    fn drop(&mut self) {
1219        let vtable = self.vtable();
1220        unsafe { vtable.destructor()(RMut::new(self).transmute_element_()) }
1221    }
1222}
1223
1224impl<'de, T> Deserialize<'de> for RVec<T>
1225where
1226    T: Deserialize<'de>,
1227{
1228    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1229    where
1230        D: Deserializer<'de>,
1231    {
1232        <Vec<T>>::deserialize(deserializer).map(Self::from)
1233    }
1234}
1235
1236impl<T> Serialize for RVec<T>
1237where
1238    T: Serialize,
1239{
1240    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1241    where
1242        S: Serializer,
1243    {
1244        self.as_slice().serialize(serializer)
1245    }
1246}
1247
1248/////////////////////////////////////////////////////////////////////////////////////
1249//             Iteration implementation based on the nomicon                       //
1250/////////////////////////////////////////////////////////////////////////////////////
1251
1252impl<T> RVec<T> {
1253    /// Creates a draining iterator that removes the specified range in
1254    /// the `RVec<T>` and yields the removed items.
1255    ///
1256    /// # Panic
1257    ///
1258    /// Panics if the index is out of bounds or if the start of the range is
1259    /// greater than the end of the range.
1260    ///
1261    /// # Consumption
1262    ///
1263    /// The elements in the range will be removed even if the iterator
1264    /// was dropped before yielding them.
1265    ///
1266    /// # Example
1267    ///
1268    /// ```
1269    /// use abi_stable::std_types::{RSlice, RVec};
1270    ///
1271    /// {
1272    ///     let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]);
1273    ///     assert_eq!(list.drain(2..4).collect::<Vec<_>>(), vec![2, 3]);
1274    ///     assert_eq!(list.as_slice(), &[0, 1, 4, 5]);
1275    /// }
1276    /// {
1277    ///     let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]);
1278    ///     assert_eq!(list.drain(2..).collect::<Vec<_>>(), vec![2, 3, 4, 5]);
1279    ///     assert_eq!(list.as_slice(), &[0, 1]);
1280    /// }
1281    /// {
1282    ///     let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]);
1283    ///     assert_eq!(list.drain(..2).collect::<Vec<_>>(), vec![0, 1]);
1284    ///     assert_eq!(list.as_slice(), &[2, 3, 4, 5]);
1285    /// }
1286    /// {
1287    ///     let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]);
1288    ///     assert_eq!(list.drain(..).collect::<Vec<_>>(), vec![0, 1, 2, 3, 4, 5]);
1289    ///     assert_eq!(list.as_rslice(), RSlice::<u32>::EMPTY);
1290    /// }
1291    ///
1292    /// ```
1293    ///
1294    ///
1295    pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1296    where
1297        R: RangeBounds<usize>,
1298    {
1299        unsafe {
1300            let slice_start = match range.start_bound() {
1301                Bound::Unbounded => 0,
1302                Bound::Included(&n) => n,
1303                Bound::Excluded(&n) => n.saturating_add(1),
1304            };
1305            let slice_end = match range.end_bound() {
1306                Bound::Unbounded => self.length,
1307                Bound::Included(&n) => n.saturating_add(1),
1308                Bound::Excluded(&n) => n,
1309            };
1310            let slice_len = slice_end - slice_start;
1311
1312            let allocation_start = self.buffer.as_ptr();
1313            let removed_start = allocation_start.add(slice_start);
1314            let iter = RawValIter::new(removed_start, slice_len);
1315            let old_length = self.length;
1316            self.length = 0;
1317
1318            Drain {
1319                removed_start,
1320                slice_len,
1321                iter,
1322                vec_len: &mut self.length,
1323                allocation_start,
1324                len: old_length,
1325            }
1326        }
1327    }
1328}
1329
1330impl<T> IntoIterator for RVec<T> {
1331    type Item = T;
1332
1333    type IntoIter = IntoIter<T>;
1334
1335    fn into_iter(self) -> IntoIter<T> {
1336        unsafe {
1337            let _buf = ManuallyDrop::new(self);
1338            let len = _buf.length;
1339            let ptr = _buf.buffer.as_ptr();
1340            let iter = RawValIter::new(ptr, len);
1341            IntoIter { iter, _buf }
1342        }
1343    }
1344}
1345
1346impl<'a, T> IntoIterator for &'a RVec<T> {
1347    type Item = &'a T;
1348
1349    type IntoIter = ::std::slice::Iter<'a, T>;
1350
1351    fn into_iter(self) -> Self::IntoIter {
1352        self.iter()
1353    }
1354}
1355
1356impl<'a, T> IntoIterator for &'a mut RVec<T> {
1357    type Item = &'a mut T;
1358
1359    type IntoIter = ::std::slice::IterMut<'a, T>;
1360
1361    fn into_iter(self) -> Self::IntoIter {
1362        self.iter_mut()
1363    }
1364}
1365
1366impl<T> FromIterator<T> for RVec<T> {
1367    fn from_iter<I>(iter: I) -> Self
1368    where
1369        I: IntoIterator<Item = T>,
1370    {
1371        iter.piped(Vec::from_iter).piped(Self::from)
1372    }
1373}
1374
1375impl<T> Extend<T> for RVec<T> {
1376    fn extend<I>(&mut self, iter: I)
1377    where
1378        I: IntoIterator<Item = T>,
1379    {
1380        // optimizable
1381        let iter = iter.into_iter();
1382        let (lower, _) = iter.size_hint();
1383        self.reserve(lower);
1384        for elem in iter {
1385            self.push(elem);
1386        }
1387    }
1388}
1389
1390impl<'a, T> Extend<&'a T> for RVec<T>
1391where
1392    T: 'a + Copy,
1393{
1394    fn extend<I>(&mut self, iter: I)
1395    where
1396        I: IntoIterator<Item = &'a T>,
1397    {
1398        // optimizable
1399        let iter = iter.into_iter();
1400        let (lower, _) = iter.size_hint();
1401        self.reserve(lower);
1402        for elem in iter {
1403            self.push(*elem);
1404        }
1405    }
1406}
1407
1408impl<T, I: SliceIndex<[T]>> Index<I> for RVec<T> {
1409    type Output = I::Output;
1410
1411    #[inline]
1412    fn index(&self, index: I) -> &Self::Output {
1413        Index::index(&**self, index)
1414    }
1415}
1416
1417impl<T, I: SliceIndex<[T]>> IndexMut<I> for RVec<T> {
1418    #[inline]
1419    fn index_mut(&mut self, index: I) -> &mut Self::Output {
1420        IndexMut::index_mut(&mut **self, index)
1421    }
1422}
1423
1424////////////////////////////////////////////////////////////////////////////////
1425
1426impl io::Write for RVec<u8> {
1427    #[inline]
1428    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1429        self.extend_from_copy_slice(buf);
1430        Ok(buf.len())
1431    }
1432
1433    #[inline]
1434    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1435        self.extend_from_copy_slice(buf);
1436        Ok(())
1437    }
1438
1439    #[inline]
1440    fn flush(&mut self) -> io::Result<()> {
1441        Ok(())
1442    }
1443}
1444
1445////////////////////////////////////////////////////////////////////////////////
1446
1447#[repr(C)]
1448#[derive(Debug, Copy, Clone, PartialEq, StableAbi)]
1449enum Exactness {
1450    Exact,
1451    Above,
1452}
1453
1454////////////////////////////////////////////////////////////////////////////////
1455////////////////////////////////////////////////////////////////////////////////
1456
1457/// Dummy type used to create a statically allocated constant that can only be
1458/// accessed of the lifetime of T.
1459struct VTableGetter<'a, T>(&'a T);
1460
1461impl<'a, T: 'a> VTableGetter<'a, T> {
1462    const DEFAULT_VTABLE: VecVTable = VecVTable {
1463        type_id: new_utypeid::<RVec<()>>,
1464        destructor: destructor_vec::<T>,
1465        grow_capacity_to: grow_capacity_to_vec::<T>,
1466        shrink_to_fit: shrink_to_fit_vec::<T>,
1467    };
1468
1469    staticref! {
1470        const WM_DEFAULT: WithMetadata<VecVTable> = WithMetadata::new(Self::DEFAULT_VTABLE);
1471    }
1472
1473    // The VTABLE for this type in this executable/library
1474    const LIB_VTABLE: VecVTable_Ref = VecVTable_Ref(Self::WM_DEFAULT.as_prefix());
1475
1476    staticref! {
1477        const WM_FOR_TESTING: WithMetadata<VecVTable> =
1478            WithMetadata::new(
1479                VecVTable {
1480                    type_id: new_utypeid::<RVec<i32>>,
1481                    ..Self::DEFAULT_VTABLE
1482                }
1483            )
1484    }
1485
1486    // Used to test functions that change behavior based on the vtable being used
1487    const LIB_VTABLE_FOR_TESTING: VecVTable_Ref = VecVTable_Ref(Self::WM_FOR_TESTING.as_prefix());
1488}
1489
1490#[repr(C)]
1491#[derive(StableAbi)]
1492#[sabi(kind(Prefix))]
1493#[sabi(missing_field(panic))]
1494struct VecVTable {
1495    type_id: extern "C" fn() -> UTypeId,
1496    destructor: unsafe extern "C" fn(RMut<'_, ()>),
1497    grow_capacity_to: unsafe extern "C" fn(RMut<'_, ()>, usize, Exactness),
1498    #[sabi(last_prefix_field)]
1499    shrink_to_fit: unsafe extern "C" fn(RMut<'_, ()>),
1500}
1501
1502unsafe extern "C" fn destructor_vec<T>(this: RMut<'_, ()>) {
1503    extern_fn_panic_handling! {no_early_return; unsafe {
1504        let this = this.transmute_into_mut::<RVec<T>>();
1505        drop(Vec::from_raw_parts(
1506            this.buffer_mut(),
1507            this.len(),
1508            this.capacity(),
1509        ));
1510    }}
1511}
1512
1513unsafe extern "C" fn grow_capacity_to_vec<T>(this: RMut<'_, ()>, to: usize, exactness: Exactness) {
1514    extern_fn_panic_handling! {no_early_return; unsafe {
1515        let this = this.transmute_into_mut::<RVec<T>>();
1516        this.with_vec(|list| {
1517            let additional = to.saturating_sub(list.len());
1518            match exactness {
1519                Exactness::Above => list.reserve(additional),
1520                Exactness::Exact => list.reserve_exact(additional),
1521            }
1522        })
1523    }}
1524}
1525
1526unsafe extern "C" fn shrink_to_fit_vec<T>(this: RMut<'_, ()>) {
1527    extern_fn_panic_handling! {no_early_return; unsafe {
1528        let this = this.transmute_into_mut::<RVec<T>>();
1529        this.with_vec(|list| {
1530            list.shrink_to_fit();
1531        })
1532    }}
1533}