my_ecs/ds/vec/
any_vec.rs

1use super::super::{
2    raw::{AsRawIter, FlatRawIter, Iter, IterMut, ParIter, ParIterMut, ParRawIter, RawIter},
3    types::{FnCloneRaw, FnDropRaw, TypeInfo},
4};
5use crate::ds::ptr::SendSyncPtr;
6use rayon::iter::IntoParallelRefIterator;
7use std::{
8    alloc::{self, Layout},
9    any::{self, TypeId},
10    cmp::Ordering,
11    mem,
12    num::NonZeroUsize,
13    ops::{Deref, DerefMut},
14    ptr::{self, NonNull},
15    slice,
16};
17
18/// A type-erased vector containing values of the same type.
19///
20/// This vector would be useful when you need to hold vectors of heterogeneous
21/// types in a single variable. Instead, this vector has methods that looks
22/// quite dirty and not easy to use. Most methods are unsafe because they take
23/// or return pointer instead of concrete type.
24#[derive(Debug)]
25pub struct AnyVec {
26    ptr: NonNull<u8>,
27    len: usize,
28    cap: usize,
29    tinfo: TypeInfo,
30}
31
32// `AnyVec` is currently restricted to be `Send` and `Sync`. See
33// `AnyVec::new()`.
34unsafe impl Send for AnyVec {}
35unsafe impl Sync for AnyVec {}
36
37impl AnyVec {
38    /// Creates a new empty vector.
39    ///
40    /// # Examples
41    ///
42    /// ```
43    /// use my_ecs::{tinfo, ds::AnyVec};
44    ///
45    /// let v = AnyVec::new(tinfo!(i32));
46    /// ```
47    pub fn new(tinfo: TypeInfo) -> Self {
48        assert!(tinfo.is_send, "expected `Send` and `Sync` type");
49        assert!(tinfo.is_sync, "expected `Send` and `Sync` type");
50
51        let mut v = Self {
52            tinfo,
53            ptr: Self::aligned_dangling(tinfo.align),
54            len: 0,
55            cap: 0,
56        };
57
58        // If ZST, we won't allocate any memory for the vector.
59        // But, adjust capacity like `Vec`.
60        if v.is_zst() {
61            v.cap = usize::MAX;
62        }
63        v
64    }
65
66    /// Returns [`TypeInfo`] of the item.
67    ///
68    /// # Examples
69    ///
70    /// ```
71    /// use my_ecs::{tinfo, ds::AnyVec};
72    ///
73    /// let v = AnyVec::new(tinfo!(i32));
74    /// assert_eq!(v.type_info(), &tinfo!(i32));
75    /// ```
76    pub const fn type_info(&self) -> &TypeInfo {
77        &self.tinfo
78    }
79
80    /// Returns [`TypeId`] of the item.
81    ///
82    /// # Examples
83    ///
84    /// ```
85    /// use my_ecs::{tinfo, ds::AnyVec};
86    ///
87    /// let v = AnyVec::new(tinfo!(i32));
88    /// assert_eq!(v.type_id(), std::any::TypeId::of::<i32>());
89    /// ```
90    pub const fn type_id(&self) -> TypeId {
91        self.tinfo.ty
92    }
93
94    /// Returns name of the item based on [`type_name`](any::type_name).
95    ///
96    /// # Examples
97    ///
98    /// ```
99    /// use my_ecs::{tinfo, ds::AnyVec};
100    ///
101    /// let v = AnyVec::new(tinfo!(i32));
102    /// println!("{}", v.type_name());
103    /// ```
104    pub const fn type_name(&self) -> &'static str {
105        self.tinfo.name
106    }
107
108    /// Returns size in bytes of the item.
109    ///
110    /// # Examples
111    ///
112    /// ```
113    /// use my_ecs::{tinfo, ds::AnyVec};
114    ///
115    /// let v = AnyVec::new(tinfo!(i32));
116    /// assert_eq!(v.item_size(), std::mem::size_of::<i32>());
117    /// ```
118    pub const fn item_size(&self) -> usize {
119        self.tinfo.size
120    }
121
122    /// Returns whether the item is zero-sized type or not.
123    ///
124    /// # Examples
125    ///
126    /// ```
127    /// use my_ecs::{tinfo, ds::AnyVec};
128    ///
129    /// let v = AnyVec::new(tinfo!(i32));
130    /// assert!(!v.is_zst());
131    /// let v = AnyVec::new(tinfo!(()));
132    /// assert!(v.is_zst());
133    /// ```
134    pub const fn is_zst(&self) -> bool {
135        self.item_size() == 0
136    }
137
138    /// Returns alignment in bytes of the item.
139    ///
140    /// # Examples
141    ///
142    /// ```
143    /// use my_ecs::{tinfo, ds::AnyVec};
144    ///
145    /// let v = AnyVec::new(tinfo!(i32));
146    /// assert_eq!(v.align(), std::mem::align_of::<i32>());
147    /// ```
148    pub const fn align(&self) -> usize {
149        self.tinfo.align
150    }
151
152    /// Returns raw drop function pointer.
153    pub const fn fn_drop(&self) -> FnDropRaw {
154        self.tinfo.fn_drop
155    }
156
157    /// Returns raw clone function pointer.
158    pub const fn fn_clone(&self) -> FnCloneRaw {
159        self.tinfo.fn_clone
160    }
161
162    /// Returns whether the item is [`Clone`] or not.
163    ///
164    /// # Examples
165    ///
166    /// ```
167    /// use my_ecs::{tinfo, ds::AnyVec};
168    ///
169    /// let v = AnyVec::new(tinfo!(i32));
170    /// assert!(v.is_clone());
171    ///
172    /// struct S;
173    /// let v = AnyVec::new(tinfo!(S));
174    /// assert!(!v.is_clone());
175    /// ```
176    pub const fn is_clone(&self) -> bool {
177        self.tinfo.is_clone
178    }
179
180    /// Returns whether the item is [`Send`] or not.
181    ///
182    /// # Examples
183    ///
184    /// ```
185    /// use my_ecs::{tinfo, ds::AnyVec};
186    ///
187    /// let v = AnyVec::new(tinfo!(i32));
188    /// assert!(v.is_send());
189    /// // let v = AnyVec::new(tinfo!(*const u8)); // Disallowed for now.
190    /// ```
191    pub const fn is_send(&self) -> bool {
192        self.tinfo.is_send
193    }
194
195    /// Returns whether the item is [`Sync`] or not.
196    ///
197    /// # Examples
198    ///
199    /// ```
200    /// use my_ecs::{tinfo, ds::AnyVec};
201    ///
202    /// let v = AnyVec::new(tinfo!(i32));
203    /// assert!(v.is_sync());
204    /// // let v = AnyVec::new(tinfo!(*const u8)); // Disallowed for now.
205    /// ```
206    pub const fn is_sync(&self) -> bool {
207        self.tinfo.is_sync
208    }
209
210    /// Returns true if the given [`TypeId`] is the same as item of the vector.
211    ///
212    /// # Examples
213    ///
214    /// ```
215    /// use my_ecs::{tinfo, ds::AnyVec};
216    ///
217    /// let v = AnyVec::new(tinfo!(i32));
218    /// assert!(v.is_type_of::<i32>());
219    /// ```
220    pub fn is_type_of<T: 'static>(&self) -> bool {
221        self.tinfo.ty == TypeId::of::<T>()
222    }
223
224    /// Returns number of item.
225    ///
226    /// # Examples
227    ///
228    /// ```
229    /// use my_ecs::{tinfo, ds::AnyVec};
230    ///
231    /// let mut v = AnyVec::new(tinfo!(i32));
232    /// unsafe { v.push(0_i32) };
233    /// assert_eq!(v.len(), 1);
234    /// ```
235    pub const fn len(&self) -> usize {
236        self.len
237    }
238
239    /// Returns true if the vector is empty.
240    ///
241    /// # Examples
242    ///
243    /// ```
244    /// use my_ecs::{tinfo, ds::AnyVec};
245    ///
246    /// let v = AnyVec::new(tinfo!(i32));
247    /// assert!(v.is_empty());
248    /// ```
249    pub const fn is_empty(&self) -> bool {
250        self.len() == 0
251    }
252
253    /// Returns capacity in bytes of the vector.
254    ///
255    /// # Examples
256    ///
257    /// ```
258    /// use my_ecs::{tinfo, ds::AnyVec};
259    ///
260    /// let mut v = AnyVec::new(tinfo!(i32));
261    /// v.reserve(10);
262    /// assert!(v.capacity() >= 10);
263    /// ```
264    pub const fn capacity(&self) -> usize {
265        self.cap
266    }
267
268    /// Returns iterator visiting all items.
269    ///
270    /// # Panics
271    ///
272    /// Panics if the given type is not the same as the vector contains.
273    ///
274    /// # Examples
275    ///
276    /// ```
277    /// use my_ecs::{tinfo, ds::AnyVec};
278    ///
279    /// let mut v = AnyVec::new(tinfo!(i32));
280    /// unsafe {
281    ///     v.push(0_i32);
282    ///     v.push(1_i32);
283    /// }
284    /// for x in v.iter_of::<i32>() {
285    ///     println!("{x}");
286    /// }
287    /// ```
288    pub fn iter_of<T: 'static>(&self) -> Iter<'_, T> {
289        assert!(
290            self.is_type_of::<T>(),
291            "type doesn't match, contains {:?} but {:?} requested",
292            self.type_name(),
293            any::type_name::<T>()
294        );
295        // Safety: Vector contains type `T` data in it.
296        unsafe { AsRawIter::iter_of(self) }
297    }
298
299    /// Returns mutable iterator visiting all items.
300    ///
301    /// # Panics
302    ///
303    /// Panics if the given type is not the same as the vector contains.
304    ///
305    /// # Examples
306    ///
307    /// ```
308    /// use my_ecs::{tinfo, ds::AnyVec};
309    ///
310    /// let mut v = AnyVec::new(tinfo!(i32));
311    /// unsafe {
312    ///     v.push(0_i32);
313    ///     v.push(1_i32);
314    /// }
315    /// for x in v.iter_mut_of::<i32>() {
316    ///     *x += 10;
317    /// }
318    /// ```
319    pub fn iter_mut_of<T: 'static>(&mut self) -> IterMut<'_, T> {
320        assert!(
321            self.is_type_of::<T>(),
322            "type doesn't match, contains {:?} but {:?} requested",
323            self.type_name(),
324            any::type_name::<T>()
325        );
326        // Safety: Vector contains type `T` data in it.
327        unsafe { AsRawIter::iter_mut_of(self) }
328    }
329
330    /// Returns parallel iterator visiting all items.
331    ///
332    /// Parallel iterator implements [`rayon`]'s parallel iterator traits, so
333    /// that it can be split into multiple CPU cores then consumed at the same
334    /// time.
335    ///
336    /// # Panics
337    ///
338    /// Panics if the given type is not the same as the vector contains.
339    ///
340    /// # Examples
341    ///
342    /// ```
343    /// use my_ecs::prelude::*;
344    /// use my_ecs::ds::AnyVec;
345    ///
346    /// let mut v = AnyVec::new(tinfo!(i32));
347    /// unsafe {
348    ///     v.push(1_i32);
349    ///     v.push(2_i32);
350    /// }
351    /// let sum: i32 = v.par_iter_of::<i32>().sum();
352    /// assert_eq!(sum, 3);
353    /// ```
354    #[inline]
355    pub fn par_iter_of<T: Send + Sync + 'static>(&self) -> ParIter<'_, T> {
356        assert!(
357            self.is_type_of::<T>(),
358            "type doesn't match, contains {:?} but {:?} requested",
359            self.type_name(),
360            any::type_name::<T>()
361        );
362        // Safety: Vector contains type `T` data in it.
363        unsafe { AsRawIter::par_iter_of(self) }
364    }
365
366    /// Returns mutable parallel iterator visiting all items.
367    ///
368    /// Parallel iterator implements [`rayon`]'s parallel iterator traits, so
369    /// that it can be split into multiple CPU cores then consumed at the same
370    /// time.
371    ///
372    /// # Panics
373    ///
374    /// Panics if the given type is not the same as the vector contains.
375    ///
376    /// # Examples
377    ///
378    /// ```
379    /// use my_ecs::prelude::*;
380    /// use my_ecs::ds::AnyVec;
381    ///
382    /// let mut v = AnyVec::new(tinfo!(i32));
383    /// unsafe {
384    ///     v.push(1_i32);
385    ///     v.push(2_i32);
386    /// }
387    /// let sum: i32 = v.par_iter_mut_of::<i32>().map(|x| *x + 1).sum();
388    /// assert_eq!(sum, 5);
389    /// ```
390    #[inline]
391    pub fn par_iter_mut_of<T: Send + Sync + 'static>(&mut self) -> ParIterMut<'_, T> {
392        assert!(
393            self.is_type_of::<T>(),
394            "type doesn't match, contains {:?} but {:?} requested",
395            self.type_name(),
396            any::type_name::<T>()
397        );
398        // Safety: Vector contains type `T` data in it.
399        unsafe { AsRawIter::par_iter_mut_of(self) }
400    }
401
402    /// Reserves additional capacity more than or equal to the given value.
403    ///
404    /// If capacity of the vector is already sufficient, nothing takes place.
405    /// Otherwise, allocates new memory or reallocates the old memory so that
406    /// the capacity will be greater than or equal to `self.len() + additional`.
407    /// This method deliberately allocates more memory than requested to avoid
408    /// frequent reallocation.
409    ///
410    /// # Panics
411    ///
412    /// Panics if total memory in bytes after calling this method will exceed
413    /// [`isize::MAX`].
414    ///
415    /// # Examples
416    ///
417    /// ```
418    /// use my_ecs::{tinfo, ds::AnyVec};
419    ///
420    /// let mut v = AnyVec::new(tinfo!(i32));
421    /// v.reserve(10);
422    /// assert!(v.capacity() >= 10);
423    /// ```
424    pub fn reserve(&mut self, additional: usize) {
425        let need_cap = self.len().saturating_add(additional);
426        if self.capacity() < need_cap {
427            let max_cap = self.max_capacity();
428            if need_cap > max_cap {
429                panic!("can't allocate {need_cap} x {} bytes", self.item_size());
430            }
431
432            // self.capacity() * 2 doesn't overflow.
433            // If sized, self.capacity() is less than or equal to isize::MAX.
434            // otherwise, self.capacity() is usize::MAX, so that it can't reach.
435            let new_cap = (self.capacity() * 2).clamp(need_cap, max_cap);
436
437            // Safety: Infallible.
438            unsafe { self._reserve(new_cap) };
439        }
440    }
441
442    /// Reserves additional capacity as much as the given value.
443    ///
444    /// If capacity of the vector is already sufficient, nothing takes place.
445    /// Otherwise, allocates new memory or reallocates the old memory so that
446    /// the capacity will be equal to `self.len() + additional` exactly.
447    ///
448    /// Note, however, that allocator may give a memory block that is greater
449    /// than requested for some reason. The exact size of memory block is
450    /// invisible from clients, but you can look into it using something like
451    /// [`libc::malloc_usable_size`](https://docs.rs/libc/latest/libc/fn.malloc_usable_size.html).
452    ///
453    /// # Examples
454    ///
455    /// ```
456    /// use my_ecs::{tinfo, ds::AnyVec};
457    ///
458    /// let mut v = AnyVec::new(tinfo!(i32));
459    /// v.reserve(10);
460    /// assert_eq!(v.capacity(), 10);
461    /// ```
462    pub fn reserve_exact(&mut self, additional: usize) {
463        let need_cap = self.len().saturating_add(additional);
464        if self.capacity() < need_cap {
465            if need_cap > self.max_capacity() {
466                panic!("can't allocate {need_cap} x {} bytes", self.item_size());
467            }
468
469            // Safety: Infallible.
470            unsafe { self._reserve(need_cap) };
471        }
472    }
473
474    /// # Safety
475    ///
476    /// `new_cap` x [`Self::item_size`] must be greater than zero and lesser or
477    /// equal to [`isize::MAX`].
478    unsafe fn _reserve(&mut self, new_cap: usize) {
479        let item_size = self.item_size();
480        let new_size = new_cap * item_size;
481
482        debug_assert!((1..=isize::MAX as usize).contains(&new_size));
483
484        if self.capacity() == 0 {
485            let layout = Layout::from_size_align(new_size, self.align()).unwrap();
486
487            let ptr = unsafe { alloc::alloc(layout) };
488            let Some(ptr) = NonNull::new(ptr) else {
489                alloc::handle_alloc_error(layout);
490            };
491
492            self.ptr = ptr;
493            self.cap = new_cap;
494        } else {
495            unsafe { self.realloc_unchecked(new_cap) }
496        };
497    }
498
499    /// Shrinks capacity of the vector as much as possible.
500    ///
501    /// # Examples
502    ///
503    /// ```
504    /// use my_ecs::{tinfo, ds::AnyVec};
505    ///
506    /// let mut v = AnyVec::new(tinfo!(i32));
507    /// assert_eq!(v.capacity(), 0);
508    ///
509    /// v.reserve(10);
510    /// assert!(v.capacity() >= 10);
511    ///
512    /// unsafe { v.push(1_i32) };
513    /// v.shrink_to_fit();
514    /// assert!(v.capacity() >= 1);
515    ///
516    /// v.pop_drop();
517    /// v.shrink_to_fit();
518    /// assert_eq!(v.capacity(), 0);
519    /// ```
520    pub fn shrink_to_fit(&mut self) {
521        if self.is_zst() || self.len() == self.capacity() {
522            return;
523        }
524
525        if self.is_empty() {
526            self.dealloc();
527        } else {
528            // Safety:
529            // - Extra capacity, so current pointer is valid.
530            // - Not ZST and empty, so that new capacity size in bytes is
531            //   greater than zero.
532            // - Size of current items in bytes cannot exceed `isize::MAX`.
533            unsafe { self.realloc_unchecked(self.len()) };
534        }
535    }
536
537    /// Sets length of the vector to the given value without any additional
538    /// operations.
539    ///
540    /// # Safety
541    ///
542    /// - `new_len` must be less than or equal to `self.capacity()`.
543    /// - If `new_len` is greater than the previous length, caller must
544    ///   initialize the extended range with proper values.
545    /// - If `new_len` is less than the previous length, caller must drop
546    ///   abandoned values from the vector properly.
547    ///
548    /// # Examples
549    ///
550    /// ```
551    /// use my_ecs::{tinfo, ds::AnyVec};
552    ///
553    /// let mut v = AnyVec::new(tinfo!(i32));
554    ///
555    /// unsafe {
556    ///     v.push(0_i32);
557    ///     v.set_len(0);
558    /// }
559    /// ```
560    pub unsafe fn set_len(&mut self, new_len: usize) {
561        debug_assert!(new_len <= self.capacity());
562
563        self.len = new_len;
564    }
565
566    /// Copies data as much as [`AnyVec::item_size`] from `src` address to the
567    /// memory pointed by `index`.
568    ///
569    /// Note that the old stored value is dropped before the copy, which means
570    /// the given index must be in bounds.
571    ///
572    /// # Safety
573    ///
574    /// - `index` must be in bounds.
575    /// - `src` must point to a valid type that the vector contains.
576    /// - Memory range pointed by `index` must not need to be dropped.
577    /// - `src` must not be dropped after calling this method because it is
578    ///   moved into the vector.
579    ///
580    /// # Examples
581    ///
582    /// ```
583    /// use my_ecs::{tinfo, ds::AnyVec};
584    /// use std::ptr::NonNull;
585    ///
586    /// let mut v = AnyVec::new(tinfo!(i32));
587    ///
588    /// unsafe {
589    ///     v.push(0_i32);
590    ///     let value = 1_i32;
591    ///     let ptr = (&value as *const i32 as *const u8).cast_mut();
592    ///     v.set_raw_unchecked(0, NonNull::new(ptr).unwrap());
593    ///     assert_eq!(v.pop(), Some(1_i32));
594    /// }
595    /// ```
596    pub unsafe fn set_raw_unchecked(&mut self, index: usize, src: NonNull<u8>) {
597        unsafe {
598            let dst = self.get_ptr(index);
599            let fn_drop = self.fn_drop();
600            fn_drop(dst);
601            ptr::copy_nonoverlapping(src.as_ptr(), dst, self.item_size());
602        }
603    }
604
605    /// Copies data as much as `self.item_size()` from `src` address to the end
606    /// of the vector.
607    ///
608    /// If the vector doesn't have sufficient capacity for the appended value,
609    /// then the vector increases its capacity first by calling
610    /// [`AnyVec::reserve`] which allocates memory more than just one value,
611    /// then does the copy.
612    ///
613    /// # Safety
614    ///
615    /// - `src` must point to a valid type that the vector contains.
616    /// - `src` must not be dropped after calling this method because it is
617    ///   moved into the vector.
618    ///
619    /// # Examples
620    ///
621    /// ```
622    /// use my_ecs::{tinfo, ds::AnyVec};
623    /// use std::ptr::NonNull;
624    ///
625    /// let mut v = AnyVec::new(tinfo!(i32));
626    ///
627    /// let value = 0x01020304_i32;
628    /// unsafe {
629    ///     let ptr = (&value as *const i32 as *const u8).cast_mut();
630    ///     v.push_raw(NonNull::new(ptr).unwrap());
631    ///     assert_eq!(v.pop(), Some(value));
632    /// }
633    /// ```
634    pub unsafe fn push_raw(&mut self, src: NonNull<u8>) {
635        if !self.is_zst() {
636            self.reserve(1);
637
638            // Safety: index is valid.
639            unsafe {
640                let dst = self.get_ptr(self.len());
641                ptr::copy_nonoverlapping(src.as_ptr(), dst, self.item_size());
642            }
643        }
644
645        // Safety: Infallible.
646        unsafe { self.set_len(self.len().checked_add(1).unwrap()) };
647    }
648
649    /// Writes a value to the end of the vector by calling the given function.
650    ///
651    /// If the vector doesn't have sufficient capacity for the appended value,
652    /// then the vector increases its capacity first by calling
653    /// [`AnyVec::reserve`] which allocates memory more than just one value,
654    /// then does the write operation.
655    ///
656    /// # Safety
657    ///
658    /// - `write` must write a valid type that the vector contains.
659    ///
660    /// # Examples
661    ///
662    /// ```
663    /// use my_ecs::{tinfo, ds::AnyVec};
664    /// use std::ptr::{self, NonNull};
665    ///
666    /// let mut v = AnyVec::new(tinfo!(i32));
667    ///
668    /// let value = 0x01020304_i32;
669    /// unsafe {
670    ///     v.push_with(|dst| {
671    ///         ptr::write(dst as *mut i32, value);
672    ///     });
673    ///     assert_eq!(v.pop(), Some(value));
674    /// }
675    /// ```
676    pub unsafe fn push_with<F>(&mut self, write: F)
677    where
678        F: FnOnce(*mut u8),
679    {
680        if !self.is_zst() {
681            self.reserve(1);
682
683            let dst = unsafe { self.get_ptr(self.len()) };
684            write(dst);
685        }
686
687        // Safety: Infallible.
688        unsafe { self.set_len(self.len().checked_add(1).unwrap()) };
689    }
690
691    /// Appends the given value to the end of the vector.
692    ///
693    /// # Safety
694    ///
695    /// - `value` must be the same type as the vector contains.
696    ///
697    /// # Examples
698    ///
699    /// ```
700    /// use my_ecs::{tinfo, ds::AnyVec};
701    ///
702    /// let mut v = AnyVec::new(tinfo!(i32));
703    /// unsafe {
704    ///     v.push(0_i32);
705    ///     assert_eq!(v.pop(), Some(0_i32));
706    /// }
707    /// ```
708    pub unsafe fn push<T: 'static>(&mut self, mut value: T) {
709        debug_assert!(
710            self.is_type_of::<T>(),
711            "expected `{}`, but received `{}`",
712            self.type_name(),
713            any::type_name::<T>()
714        );
715
716        // Safety: Infallible.
717        unsafe {
718            let ptr = NonNull::new_unchecked(&mut value as *mut T as *mut u8);
719            self.push_raw(ptr);
720        }
721        mem::forget(value);
722    }
723
724    /// Removes the last item from the vector and writes it to the given
725    /// buffer, then returns `Some`.
726    ///
727    /// If removing is successful, caller becomes to own the item in the
728    /// buffer, so that caller must call `drop()` on it correctly.
729    /// Otherwise, returns `None` without change to the buffer.
730    ///
731    /// # Safety
732    ///
733    /// Undefined behavior if conditions below are not met.
734    /// - `buf` must have enough size to be copied an item.
735    /// - When `Some` is returned, `buf` must be correctly handled as an item.
736    ///   For example, if an item should be dropped, caller must call drop() on
737    ///   it.
738    /// - When `None` is returned, `buf` must be correctly handled as it was.
739    ///
740    /// # Examples
741    ///
742    /// ```
743    /// use my_ecs::{tinfo, ds::AnyVec};
744    ///
745    /// let mut v = AnyVec::new(tinfo!(i32));
746    /// unsafe { v.push(42_i32) };
747    /// assert_eq!(v.len(), 1);
748    ///
749    /// let mut buf = 0_i32;
750    /// let res = unsafe { v.pop_raw(&mut buf as *mut i32 as *mut u8) };
751    /// assert!(res.is_some());
752    /// assert!(v.is_empty());
753    /// assert_eq!(buf, 42);
754    /// ```
755    pub unsafe fn pop_raw(&mut self, buf: *mut u8) -> Option<()> {
756        if self.is_empty() {
757            None
758        } else {
759            unsafe {
760                // Safety: Vector is not empty.
761                let ptr = self._pop();
762                ptr::copy_nonoverlapping(ptr, buf, self.item_size());
763            }
764            Some(())
765        }
766    }
767
768    /// Removes the last item from the vector.
769    ///
770    /// # Safety
771    ///
772    /// - `T` must be the same type as the vector contains.
773    ///
774    /// # Examples
775    ///
776    /// ```
777    /// use my_ecs::{tinfo, ds::AnyVec};
778    ///
779    /// let mut v = AnyVec::new(tinfo!(i32));
780    ///
781    /// unsafe {
782    ///     v.push(0_i32);
783    ///     let value = v.pop::<i32>().unwrap();
784    ///     assert_eq!(value, 0_i32);
785    /// }
786    /// ```
787    pub unsafe fn pop<T: 'static>(&mut self) -> Option<T> {
788        debug_assert!(
789            self.is_type_of::<T>(),
790            "expected `{}`, but received `{}`",
791            self.type_name(),
792            any::type_name::<T>()
793        );
794
795        if self.is_empty() {
796            None
797        } else {
798            // Safety: Vector is not empty.
799            let ptr = unsafe { self._pop() as *mut T };
800            let value = unsafe { ptr.read() };
801            Some(value)
802        }
803    }
804
805    /// Removes the last item from the vector then drops it immediately.
806    ///
807    /// # Examples
808    ///
809    /// ```
810    /// use my_ecs::{tinfo, ds::AnyVec};
811    ///
812    /// let mut v = AnyVec::new(tinfo!(i32));
813    ///
814    /// unsafe {
815    ///     v.push(0_i32);
816    ///     assert_eq!(v.pop_drop(), Some(()));
817    /// }
818    /// ```
819    pub fn pop_drop(&mut self) -> Option<()> {
820        if self.is_empty() {
821            None
822        } else {
823            let fn_drop = self.fn_drop();
824            // Safety: Vector is not empty.
825            unsafe { fn_drop(self._pop()) };
826            Some(())
827        }
828    }
829
830    /// Removes the last item from the vector without calling drop function on
831    /// it.
832    ///
833    /// # Safety
834    ///
835    /// Rust safety doesn't include calling drop function. See
836    /// [`forget`](mem::forget) for more information. However, caller must
837    /// guarantee that not calling drop function is fine for the item.
838    ///
839    /// # Examples
840    ///
841    /// ```
842    /// use my_ecs::{tinfo, ds::AnyVec};
843    ///
844    /// let mut v = AnyVec::new(tinfo!(i32));
845    ///
846    /// unsafe {
847    ///     v.push(0_i32);
848    ///     assert_eq!(v.pop_forget(), Some(()));
849    /// }
850    /// ```
851    pub fn pop_forget(&mut self) -> Option<()> {
852        if self.is_empty() {
853            None
854        } else {
855            // Safety: Vector is not empty.
856            unsafe { self._pop() };
857            Some(())
858        }
859    }
860
861    /// # Safety
862    ///
863    /// Length of the vector must not be zero.
864    unsafe fn _pop(&mut self) -> *mut u8 {
865        unsafe {
866            // Safety: Decreasing is safe.
867            self.set_len(self.len() - 1);
868
869            // Safety: We're using `Layout::from_size_align` which restricts
870            // size to be under the limit.
871            self.get_ptr(self.len())
872        }
873    }
874
875    /// Removes an item at the given index from the vector and writes it to the
876    /// given buffer.
877    ///
878    /// Therefore, the item is actually moved from the vector to the given
879    /// buffer. So caller must take care of calling drop on it.
880    ///
881    /// # Panics
882    ///
883    /// Panics if the given index is out of bounds.
884    ///
885    /// # Safety
886    ///
887    /// Undefined behavior if conditions below are not met.
888    /// - `buf` must have enough size to be copied an item.
889    /// - When `Some` is returned, `buf` must be correctly handled as an item.
890    ///   For example, if an item should be dropped, caller must call drop() on
891    ///   it.
892    /// - When `None` is returned, `buf` must be correctly handled as it was.
893    ///
894    /// # Examples
895    ///
896    /// ```
897    /// use my_ecs::{tinfo, ds::AnyVec};
898    ///
899    /// let mut v = AnyVec::new(tinfo!(i32));
900    /// unsafe {
901    ///     v.push(0_i32);
902    ///     v.push(1_i32);
903    ///     v.push(2_i32);
904    /// }
905    /// assert_eq!(v.len(), 3);
906    ///
907    /// let mut buf = 3_i32;
908    /// unsafe { v.swap_remove_raw(0, &mut buf as *mut i32 as *mut u8) };
909    /// assert_eq!(buf, 0);
910    ///
911    /// unsafe {
912    ///     assert_eq!(v.pop::<i32>(), Some(1));
913    ///     assert_eq!(v.pop::<i32>(), Some(2));
914    /// }
915    /// ```
916    pub unsafe fn swap_remove_raw(&mut self, index: usize, buf: *mut u8) {
917        // If index is out of bounds or len() - 1 overflows, swap() panics.
918        self.swap(index, self.len().wrapping_sub(1));
919        unsafe { self.pop_raw(buf) };
920    }
921
922    /// Removes an item at the given index from the vector and returns it.
923    ///
924    /// Then the last item of the vector is moved to the vacant slot.
925    ///
926    /// # Panics
927    ///
928    /// Panics if the given index is out of bounds.
929    ///
930    /// # Safety
931    ///
932    /// - `T` must be the same type as the vector contains.
933    ///
934    /// # Examples
935    ///
936    /// ```
937    /// use my_ecs::{tinfo, ds::AnyVec};
938    ///
939    /// let mut v = AnyVec::new(tinfo!(i32));
940    ///
941    /// unsafe {
942    ///     v.push(0_i32);
943    ///     v.push(1_i32);
944    ///     v.push(2_i32);
945    ///     assert_eq!(v.swap_remove::<i32>(0), 0);
946    ///     assert_eq!(v.swap_remove::<i32>(0), 2);
947    ///     assert_eq!(v.swap_remove::<i32>(0), 1);
948    /// }
949    /// ```
950    pub unsafe fn swap_remove<T: 'static>(&mut self, index: usize) -> T {
951        // If index is out of bounds or len() - 1 overflows, swap() panics.
952        self.swap(index, self.len().wrapping_sub(1));
953        unsafe { self.pop().unwrap() }
954    }
955
956    /// Removes an item at the given index from the vector and drops it
957    /// immediately.
958    ///
959    /// Then the last item of the vector is moved to the vacant slot.
960    ///
961    /// # Panics
962    ///
963    /// Panics if the given index is out of bounds.
964    ///
965    /// # Examples
966    ///
967    /// ```
968    /// use my_ecs::{tinfo, ds::AnyVec};
969    ///
970    /// let mut v = AnyVec::new(tinfo!(i32));
971    ///
972    /// unsafe {
973    ///     v.push(0_i32);
974    ///     v.swap_remove_drop(0);
975    ///     assert!(v.is_empty());
976    /// }
977    /// ```
978    pub fn swap_remove_drop(&mut self, index: usize) {
979        // If index is out of bounds or len() - 1 overflows, swap() panics.
980        self.swap(index, self.len().wrapping_sub(1));
981        self.pop_drop();
982    }
983
984    /// Removes an item at the given index from the vector without calling drop
985    /// function on it.
986    ///
987    /// Then the last item of the vector is moved to the vacant slot.
988    ///
989    /// # Panics
990    ///
991    /// Panics if given index is out of bounds.
992    ///
993    /// # Safety
994    ///
995    /// Rust safety doesn't include calling drop function. See
996    /// [`forget`](mem::forget) for more information. However, caller must
997    /// guarantee that not calling drop function is fine for the item.
998    ///
999    /// # Examples
1000    ///
1001    /// ```
1002    /// use my_ecs::{tinfo, ds::AnyVec};
1003    ///
1004    /// let mut v = AnyVec::new(tinfo!(i32));
1005    ///
1006    /// unsafe {
1007    ///     v.push(0_i32);
1008    ///     v.swap_remove_forget(0);
1009    ///     assert!(v.is_empty());
1010    /// }
1011    /// ```
1012    pub fn swap_remove_forget(&mut self, index: usize) {
1013        // If index is out of bounds or len() - 1 overflows, swap() panics.
1014        self.swap(index, self.len().wrapping_sub(1));
1015        self.pop_forget();
1016    }
1017
1018    /// Replaces an item with another item in the vector.
1019    ///
1020    /// # Panics
1021    ///
1022    /// Panics if any given indices is out of bounds.
1023    ///
1024    /// # Examples
1025    ///
1026    /// ```
1027    /// use my_ecs::{tinfo, ds::AnyVec};
1028    ///
1029    /// let mut v = AnyVec::new(tinfo!(i32));
1030    ///
1031    /// unsafe {
1032    ///     v.push(0_i32);
1033    ///     v.push(1_i32);
1034    ///     v.swap(0, 1);
1035    ///     assert_eq!(v.pop(), Some(0));
1036    ///     assert_eq!(v.pop(), Some(1));
1037    /// }
1038    /// ```
1039    pub fn swap(&mut self, index0: usize, index1: usize) {
1040        assert!(index0 < self.len(), "{index0} is out of bounds");
1041        assert!(index1 < self.len(), "{index1} is out of bounds");
1042
1043        unsafe {
1044            let ptr0 = self.get_ptr(index0);
1045            let ptr1 = self.get_ptr(index1);
1046            if ptr0 != ptr1 {
1047                ptr::swap_nonoverlapping(ptr0, ptr1, self.item_size());
1048            }
1049        }
1050    }
1051
1052    /// Returns a pointer to an item at the given index.
1053    ///
1054    /// # Examples
1055    ///
1056    /// ```
1057    /// use my_ecs::{tinfo, ds::AnyVec};
1058    ///
1059    /// let mut v = AnyVec::new(tinfo!(i32));
1060    ///
1061    /// let value = 0x01020304_i32;
1062    /// unsafe { v.push(value) };
1063    ///
1064    /// let ptr = v.get_raw(0).unwrap().cast::<i32>().as_ptr().cast_const();
1065    /// unsafe {
1066    ///     assert_eq!(std::ptr::read(ptr), value);
1067    /// }
1068    /// ```
1069    pub fn get_raw(&self, index: usize) -> Option<NonNull<u8>> {
1070        if index < self.len() {
1071            unsafe { Some(self.get_raw_unchecked(index)) }
1072        } else {
1073            None
1074        }
1075    }
1076
1077    /// Returns a pointer to an item at the given index.
1078    ///
1079    /// # Safety
1080    ///
1081    /// - Index must be in bounds.
1082    ///
1083    /// # Examples
1084    ///
1085    /// ```
1086    /// use my_ecs::{tinfo, ds::AnyVec};
1087    ///
1088    /// let mut v = AnyVec::new(tinfo!(i32));
1089    ///
1090    /// let value = 0x01020304_i32;
1091    /// unsafe {
1092    ///     v.push(value);
1093    ///     let ptr = v.get_raw_unchecked(0)
1094    ///         .cast::<i32>()
1095    ///         .as_ptr()
1096    ///         .cast_const();
1097    ///     assert_eq!(std::ptr::read(ptr), value);
1098    /// }
1099    /// ```
1100    pub unsafe fn get_raw_unchecked(&self, index: usize) -> NonNull<u8> {
1101        unsafe {
1102            let item_ptr = self.get_ptr(index);
1103            NonNull::new_unchecked(item_ptr)
1104        }
1105    }
1106
1107    /// Returns shared reference to an item at the given index.
1108    ///
1109    /// # Safety
1110    ///
1111    /// - `T` must be the same type as the vector contains.
1112    ///
1113    /// # Examples
1114    ///
1115    /// ```
1116    /// use my_ecs::{tinfo, ds::AnyVec};
1117    ///
1118    /// let mut v = AnyVec::new(tinfo!(i32));
1119    ///
1120    /// unsafe {
1121    ///     v.push(0_i32);
1122    ///     assert_eq!(v.get(0), Some(&0_i32));
1123    /// }
1124    /// ```
1125    pub unsafe fn get<T: 'static>(&self, index: usize) -> Option<&T> {
1126        debug_assert!(
1127            self.is_type_of::<T>(),
1128            "expected `{}`, but received `{}`",
1129            self.type_name(),
1130            any::type_name::<T>()
1131        );
1132
1133        self.get_raw(index)
1134            .map(|ptr| unsafe { (ptr.as_ptr() as *const T).as_ref().unwrap_unchecked() })
1135    }
1136
1137    /// Returns mutable reference to an item at the given index.
1138    ///
1139    /// # Safety
1140    ///
1141    /// - `T` must be the same type as the vector contains.
1142    ///
1143    /// # Examples
1144    ///
1145    /// ```
1146    /// use my_ecs::{tinfo, ds::AnyVec};
1147    ///
1148    /// let mut v = AnyVec::new(tinfo!(i32));
1149    ///
1150    /// unsafe {
1151    ///     v.push(0_i32);
1152    ///     *v.get_mut(0).unwrap() = 1_i32;
1153    ///     assert_eq!(v.get(0), Some(&1_i32));
1154    /// }
1155    /// ```
1156    pub unsafe fn get_mut<T: 'static>(&mut self, index: usize) -> Option<&mut T> {
1157        debug_assert!(
1158            self.is_type_of::<T>(),
1159            "expected `{}`, but received `{}`",
1160            self.type_name(),
1161            any::type_name::<T>()
1162        );
1163
1164        self.get_raw(index)
1165            .map(|ptr| unsafe { (ptr.as_ptr() as *mut T).as_mut().unwrap_unchecked() })
1166    }
1167
1168    /// Resizes the vector to the given length.
1169    ///
1170    /// If the new length is greater than previous length of the vector, then
1171    /// the vector is extended with the given value. Otherwise, the vector is
1172    /// shrunk.
1173    ///
1174    /// # Panics
1175    ///
1176    /// Panics if `T` is not the same type as the vector contains.
1177    ///
1178    /// # Examples
1179    ///
1180    /// ```
1181    /// use my_ecs::{tinfo, ds::AnyVec};
1182    ///
1183    /// let mut v = AnyVec::new(tinfo!(i32));
1184    ///
1185    /// unsafe {
1186    ///     v.resize(2, 0_i32);
1187    ///     assert_eq!(v.pop(), Some(0_i32));
1188    ///     assert_eq!(v.pop(), Some(0_i32));
1189    ///     assert!(v.is_empty());
1190    /// }
1191    /// ```
1192    pub fn resize<T>(&mut self, new_len: usize, value: T)
1193    where
1194        T: Clone + 'static,
1195    {
1196        // Panic: `self.resize_with` panics if the given type `T` is incorrect.
1197        self.resize_with(new_len, || value.clone());
1198    }
1199
1200    /// Resizes the vector to the given length.
1201    ///
1202    /// If the new length is greater than previous length of the vector, then
1203    /// the vector is extended with clones of a value pointed by the given
1204    /// pointer. Otherwise, the vector is shrunk.
1205    ///
1206    /// # Panics
1207    ///
1208    /// Panics if vector item is not [`Clone`].
1209    ///
1210    /// # Safety
1211    ///
1212    /// - `val_ptr` must point to a valid type that the vector contains.
1213    ///
1214    /// # Examples
1215    ///
1216    /// ```
1217    /// use my_ecs::{tinfo, ds::AnyVec};
1218    /// use std::ptr::NonNull;
1219    ///
1220    /// let mut v = AnyVec::new(tinfo!(i32));
1221    ///
1222    /// let value = 0x01020304_i32;
1223    /// unsafe {
1224    ///     let ptr = (&value as *const i32 as *const u8).cast_mut();
1225    ///     v.resize_raw(2, NonNull::new(ptr).unwrap());
1226    ///     assert_eq!(v.pop(), Some(value));
1227    ///     assert_eq!(v.pop(), Some(value));
1228    ///     assert!(v.is_empty());
1229    /// }
1230    /// ```
1231    pub unsafe fn resize_raw(&mut self, new_len: usize, val_ptr: NonNull<u8>) {
1232        assert!(self.is_clone(), "expected `Clone` type");
1233
1234        match new_len.cmp(&self.len()) {
1235            Ordering::Less => self.truncate(new_len),
1236            Ordering::Equal => {}
1237            Ordering::Greater => {
1238                self.reserve(new_len - self.len());
1239
1240                let (mut offset, stride) = self.get_ptr_offset(self.len());
1241                let src = val_ptr.as_ptr().cast_const();
1242
1243                let range = self.len()..new_len;
1244                for _ in range {
1245                    unsafe {
1246                        let dst = self.ptr.as_ptr().add(offset);
1247                        (self.tinfo.fn_clone)(src, dst);
1248                    };
1249                    offset += stride;
1250                }
1251
1252                unsafe { self.set_len(new_len) };
1253            }
1254        }
1255    }
1256
1257    /// Resizes the vector to the given length.
1258    ///
1259    /// If the new length is greater than previous length of the vector, then
1260    /// the vector is extended with values the given function generates. In this
1261    /// case, generated values are appended in order. Otherwise, the vector is
1262    /// shrunk.
1263    ///
1264    /// # Panics
1265    ///
1266    /// Panics if `T` is not the same type as the vector contains.
1267    ///
1268    /// # Examples
1269    ///
1270    /// ```
1271    /// use my_ecs::{tinfo, ds::AnyVec};
1272    ///
1273    /// let mut v = AnyVec::new(tinfo!(i32));
1274    ///
1275    /// unsafe {
1276    ///     v.resize_with(2, || 0_i32);
1277    ///     assert_eq!(v.pop(), Some(0_i32));
1278    ///     assert_eq!(v.pop(), Some(0_i32));
1279    ///     assert!(v.is_empty());
1280    /// }
1281    /// ```
1282    pub fn resize_with<T, F>(&mut self, new_len: usize, mut f: F)
1283    where
1284        T: 'static,
1285        F: FnMut() -> T,
1286    {
1287        assert!(
1288            self.is_type_of::<T>(),
1289            "expected `{}`, but received `{}`",
1290            self.type_name(),
1291            any::type_name::<T>()
1292        );
1293
1294        match new_len.cmp(&self.len()) {
1295            Ordering::Less => self.truncate(new_len),
1296            Ordering::Equal => {}
1297            Ordering::Greater => {
1298                self.reserve(new_len - self.len());
1299
1300                let (mut offset, stride) = self.get_ptr_offset(self.len());
1301
1302                let range = self.len()..new_len;
1303                for _ in range {
1304                    let ptr = unsafe { self.ptr.as_ptr().add(offset) } as *mut T;
1305                    unsafe { ptr.write(f()) };
1306                    offset += stride;
1307                }
1308
1309                unsafe { self.set_len(new_len) };
1310            }
1311        }
1312    }
1313
1314    /// Shrinks the vector to the given length, and drops abandoned items.
1315    ///
1316    /// If the given length is greater than or equal to the current length of
1317    /// the vector, nothing takes place.
1318    ///
1319    /// # Examples
1320    ///
1321    /// ```
1322    /// use my_ecs::{tinfo, ds::AnyVec};
1323    ///
1324    /// let mut v = AnyVec::new(tinfo!(i32));
1325    ///
1326    /// unsafe { v.resize(10, 0_i32) };
1327    /// v.truncate(5);
1328    /// assert_eq!(v.len(), 5);
1329    /// ```
1330    pub fn truncate(&mut self, len: usize) {
1331        if len >= self.len() {
1332            return;
1333        }
1334
1335        let (mut offset, stride) = self.get_ptr_offset(len);
1336
1337        let range = len..self.len();
1338        let fn_drop = self.fn_drop();
1339        for _ in range {
1340            unsafe {
1341                let ptr = self.ptr.as_ptr().add(offset);
1342                fn_drop(ptr);
1343            }
1344            offset += stride;
1345        }
1346
1347        unsafe { self.set_len(len) };
1348    }
1349
1350    /// Creates [`TypedAnyVec`] which looks like `Vec<T>`.
1351    ///
1352    /// You can call tons of useful methods on [`Vec`] by converting the vector.
1353    ///
1354    /// # Panics
1355    ///
1356    /// Panics if `T` it not the same type as the vector contains.
1357    ///
1358    /// # Examples
1359    ///
1360    /// ```
1361    /// use my_ecs::{tinfo, ds::AnyVec};
1362    ///
1363    /// let mut v = AnyVec::new(tinfo!(i32));
1364    /// {
1365    ///     let mut tv = v.as_vec_mut::<i32>();
1366    ///     tv.push(0);
1367    ///     tv.push(1);
1368    /// }
1369    /// unsafe {
1370    ///     assert_eq!(v.pop(), Some(1_i32));
1371    ///     assert_eq!(v.pop(), Some(0_i32));
1372    /// }
1373    /// ```
1374    pub fn as_vec_mut<T: 'static>(&mut self) -> TypedAnyVec<'_, T> {
1375        assert!(
1376            self.is_type_of::<T>(),
1377            "expected `{}`, but received `{}`",
1378            self.type_name(),
1379            any::type_name::<T>()
1380        );
1381
1382        let typed = unsafe {
1383            Vec::from_raw_parts(self.ptr.as_ptr() as *mut T, self.len(), self.capacity())
1384        };
1385        TypedAnyVec { typed, any: self }
1386    }
1387
1388    /// Creates a slice from the vector.
1389    ///
1390    /// # Panics
1391    ///
1392    /// Panics if `T` it not the same type as the vector contains.
1393    ///
1394    /// # Examples
1395    ///
1396    /// ```
1397    /// use my_ecs::{tinfo, ds::AnyVec};
1398    ///
1399    /// let mut v = AnyVec::new(tinfo!(i32));
1400    /// unsafe {
1401    ///     v.push(0_i32);
1402    ///     v.push(1_i32);
1403    /// }
1404    /// assert_eq!(v.as_slice::<i32>(), &[0, 1]);
1405    /// ```
1406    pub fn as_slice<T: 'static>(&self) -> &[T] {
1407        assert!(
1408            self.is_type_of::<T>(),
1409            "expected `{}`, but received `{}`",
1410            self.type_name(),
1411            any::type_name::<T>()
1412        );
1413
1414        unsafe { slice::from_raw_parts(self.ptr.as_ptr() as *const T, self.len()) }
1415    }
1416
1417    /// Creates a mutable slice from the vector.
1418    ///
1419    /// # Panics
1420    ///
1421    /// Panics if `T` it not the same type as the vector contains.
1422    ///
1423    /// # Examples
1424    ///
1425    /// ```
1426    /// use my_ecs::{tinfo, ds::AnyVec};
1427    ///
1428    /// let mut v = AnyVec::new(tinfo!(i32));
1429    /// unsafe { v.push(0_i32) };
1430    /// let slice = v.as_mut_slice::<i32>();
1431    /// assert_eq!(slice, &mut [0]);
1432    /// ```
1433    pub fn as_mut_slice<T: 'static>(&mut self) -> &mut [T] {
1434        assert!(
1435            self.is_type_of::<T>(),
1436            "expected `{}`, but received `{}`",
1437            self.type_name(),
1438            any::type_name::<T>()
1439        );
1440
1441        unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr() as *mut T, self.len()) }
1442    }
1443
1444    /// `index` is an index of T, not u8.
1445    ///
1446    /// # Safety
1447    ///
1448    /// `index` must be inbound and result address must not overflow `isize`.
1449    pub(crate) const unsafe fn get_ptr(&self, index: usize) -> *mut u8 {
1450        let offset = index * self.item_size();
1451        unsafe { self.ptr.as_ptr().add(offset) }
1452    }
1453
1454    /// # Safety
1455    ///
1456    /// Undefined behavior if conditions below are not met.
1457    /// - Current pointer must point to a valid memory location.
1458    /// - `new_cap` x [`Self::item_size`] is greater than zero and lesser or
1459    ///   equal to [`isize::MAX`].
1460    unsafe fn realloc_unchecked(&mut self, new_cap: usize) {
1461        let item_size = self.item_size();
1462        let old_size = self.capacity() * item_size;
1463        let old_layout = Layout::from_size_align(old_size, self.align()).unwrap();
1464        let new_size = new_cap * item_size;
1465
1466        debug_assert_ne!(self.ptr, Self::aligned_dangling(self.align()));
1467        debug_assert!((1..=isize::MAX as usize).contains(&new_size));
1468
1469        // Safety
1470        // - `ptr` and `layout` are valid.
1471        // - `new_size` doesn't overflow `isize::MAX`.
1472        let ptr = unsafe { alloc::realloc(self.ptr.as_ptr(), old_layout, new_size) };
1473        if ptr.is_null() {
1474            let layout = Layout::from_size_align(new_size, self.align()).unwrap();
1475            alloc::handle_alloc_error(layout);
1476        }
1477
1478        self.ptr = unsafe { NonNull::new_unchecked(ptr) };
1479        self.cap = new_cap;
1480    }
1481
1482    /// Drops all items in the vector and frees memory.
1483    fn dealloc(&mut self) {
1484        // Calls every drop method.
1485        self.truncate(0);
1486
1487        // Releases the memory.
1488        if !self.is_zst() && self.capacity() > 0 {
1489            let size = self.capacity() * self.item_size();
1490            let layout = Layout::from_size_align(size, self.align()).unwrap();
1491            unsafe { alloc::dealloc(self.ptr.as_ptr(), layout) };
1492
1493            self.ptr = Self::aligned_dangling(self.align());
1494            self.cap = 0;
1495        }
1496    }
1497
1498    /// Converts start index into start pointer offset from the beginning of the vector and stride in bytes.
1499    /// If the type is zero sized, it will return all zeros.
1500    /// So, you must not use offset as loop counter.
1501    /// And caller must provide valid index.
1502    /// This method assumes that, therefore doesn't check either index validity and arithmetic overflow.
1503    const fn get_ptr_offset(&self, index: usize) -> (usize, usize) {
1504        if self.is_zst() {
1505            (0, 0)
1506        } else {
1507            let item_size = self.item_size();
1508            // Valid pointer offset can't exceed isize::MAX.
1509            (index * item_size, item_size)
1510        }
1511    }
1512
1513    /// Mimics [`NonNull::dangling`].
1514    /// This helps to use lots of ptr module's APIs because they request aligned pointer even if the type is zero sized.
1515    pub(crate) fn aligned_dangling(align: usize) -> NonNull<u8> {
1516        NonNull::new(align as *mut u8).unwrap()
1517    }
1518
1519    pub(crate) fn iter2(&self) -> FlatRawIter {
1520        unsafe fn fn_iter(this: NonNull<u8>, chunk_idx: usize) -> RawIter {
1521            if chunk_idx == 0 {
1522                let this = unsafe { this.cast::<AnyVec>().as_ref() };
1523                this.iter()
1524            } else {
1525                RawIter::empty()
1526            }
1527        }
1528        unsafe fn fn_find(this: NonNull<u8>, item_idx: usize) -> (RawIter, usize, usize) {
1529            let this = unsafe { this.cast::<AnyVec>().as_ref() };
1530            (this.iter(), 0, item_idx)
1531        }
1532        // If ZST, alignment will become stride.
1533        let stride = self.item_size().max(self.align());
1534        let len = self.len();
1535
1536        unsafe {
1537            let this = (self as *const Self as *const u8).cast_mut();
1538            let this = NonNull::new_unchecked(this);
1539            let chunks = 1;
1540            FlatRawIter::new(this, chunks, fn_iter as _, fn_find as _, stride, len)
1541        }
1542    }
1543
1544    /// Maximum capacity only if the type is not zero sized.
1545    const fn max_capacity(&self) -> usize {
1546        isize::MAX as usize / self.item_size()
1547    }
1548}
1549
1550impl Clone for AnyVec {
1551    fn clone(&self) -> Self {
1552        let ptr = if self.is_zst() || self.is_empty() {
1553            self.ptr
1554        } else {
1555            let item_size = self.item_size();
1556
1557            let size = self.len() * item_size;
1558            let layout = Layout::from_size_align(size, self.align()).unwrap();
1559            let ptr = unsafe { alloc::alloc(layout) };
1560            if ptr.is_null() {
1561                alloc::handle_alloc_error(layout);
1562            }
1563
1564            let mut offset = 0;
1565            let fn_clone = self.fn_clone();
1566            while offset < size {
1567                unsafe {
1568                    let src = self.ptr.as_ptr().add(offset);
1569                    let dst = ptr.add(offset);
1570                    // If data type doesn't support clone, panics here.
1571                    fn_clone(src, dst);
1572                }
1573                offset += item_size;
1574            }
1575
1576            NonNull::new(ptr).unwrap()
1577        };
1578
1579        Self {
1580            tinfo: self.tinfo,
1581            ptr,
1582            len: self.len(),
1583            cap: self.len(),
1584        }
1585    }
1586}
1587
1588impl Drop for AnyVec {
1589    fn drop(&mut self) {
1590        self.dealloc();
1591    }
1592}
1593
1594impl AsRawIter for AnyVec {
1595    fn iter(&self) -> RawIter {
1596        unsafe {
1597            // Safety: Alignment must be at least 1.
1598            let stride = NonZeroUsize::new_unchecked(self.item_size().max(self.align()));
1599            RawIter::new(self.ptr, self.len(), stride)
1600        }
1601    }
1602}
1603
1604impl IntoIterator for &AnyVec {
1605    type Item = SendSyncPtr<u8>;
1606    type IntoIter = RawIter;
1607
1608    fn into_iter(self) -> Self::IntoIter {
1609        self.iter()
1610    }
1611}
1612
1613impl<'data> IntoParallelRefIterator<'data> for AnyVec {
1614    type Iter = ParRawIter;
1615    type Item = SendSyncPtr<u8>;
1616
1617    fn par_iter(&'data self) -> Self::Iter {
1618        AsRawIter::par_iter(self)
1619    }
1620}
1621
1622/// A [`Vec`]-like type you can get from [`AnyVec`].
1623///
1624/// This struct implements [`Deref`] and [`DerefMut`] for `Vec<T>`, so that you
1625/// can access the struct as `Vec<T>`. When this struct is dropped, any changes
1626/// you've made are reflected to the `AnyVec`.
1627pub struct TypedAnyVec<'a, T> {
1628    typed: Vec<T>,
1629    any: &'a mut AnyVec,
1630}
1631
1632impl<T> Deref for TypedAnyVec<'_, T> {
1633    type Target = Vec<T>;
1634
1635    fn deref(&self) -> &Self::Target {
1636        &self.typed
1637    }
1638}
1639
1640impl<T> DerefMut for TypedAnyVec<'_, T> {
1641    fn deref_mut(&mut self) -> &mut Self::Target {
1642        &mut self.typed
1643    }
1644}
1645
1646impl<T> Drop for TypedAnyVec<'_, T> {
1647    fn drop(&mut self) {
1648        let ptr = self.typed.as_mut_ptr() as *mut u8;
1649        self.any.ptr = NonNull::new(ptr).unwrap();
1650        self.any.len = self.typed.len();
1651        self.any.cap = self.typed.capacity();
1652        let v = mem::take(&mut self.typed);
1653        mem::forget(v);
1654    }
1655}
1656
1657#[cfg(test)]
1658mod tests {
1659    use super::*;
1660
1661    #[derive(PartialEq, Debug, Clone, Copy, Default)]
1662    struct SA {
1663        x: [usize; 2],
1664    }
1665
1666    #[cfg(debug_assertions)]
1667    #[derive(PartialEq, Debug, Clone, Copy, Default)]
1668    struct SB {
1669        x: [usize; 2],
1670        y: [f32; 2],
1671    }
1672
1673    #[test]
1674    fn test_any_vec_clone() {
1675        // Safety: Type is correct.
1676        unsafe {
1677            let mut a = AnyVec::new(crate::tinfo!(SA));
1678            let mut b = a.clone();
1679
1680            a.push(SA { x: [0, 0] });
1681            b.push(SA { x: [1, 1] });
1682
1683            let c = a.clone();
1684            let d = b.clone();
1685
1686            assert_eq!(a.len(), c.len());
1687            assert_eq!(a.get::<SA>(0), c.get::<SA>(0));
1688            assert_eq!(b.len(), d.len());
1689            assert_eq!(b.get::<SA>(0), d.get::<SA>(0));
1690        }
1691    }
1692
1693    #[test]
1694    #[should_panic]
1695    fn test_any_vec_non_cloneable_panic() {
1696        // Safety: Type is correct.
1697        unsafe {
1698            #[allow(dead_code)]
1699            struct S(i32);
1700            let mut a = AnyVec::new(crate::tinfo!(S));
1701            a.push(S(0));
1702            let _ = a.clone();
1703        }
1704    }
1705
1706    #[test]
1707    fn test_any_vec_drop() {
1708        use std::sync::{Arc, Mutex};
1709
1710        struct X(Arc<Mutex<i32>>);
1711        impl Drop for X {
1712            fn drop(&mut self) {
1713                *self.0.lock().unwrap() += 1;
1714            }
1715        }
1716
1717        // Safety: Type is correct.
1718        unsafe {
1719            let cnt = Arc::new(Mutex::new(0));
1720            let mut v = AnyVec::new(crate::tinfo!(X));
1721            for _ in 0..10 {
1722                v.push(X(Arc::clone(&cnt)));
1723            }
1724
1725            for i in 1..=5 {
1726                v.pop_drop();
1727                assert_eq!(*cnt.lock().unwrap(), i);
1728            }
1729
1730            drop(v);
1731            assert_eq!(*cnt.lock().unwrap(), 10);
1732        }
1733    }
1734
1735    #[test]
1736    fn test_any_vec_push_pop() {
1737        // Safety: Type is correct.
1738        unsafe {
1739            let mut a = AnyVec::new(crate::tinfo!(SA));
1740            assert_eq!(true, a.is_empty());
1741
1742            a.push(SA { x: [0, 1] });
1743            assert_eq!(1, a.len());
1744            assert!(a.capacity() >= 1);
1745            assert_eq!(false, a.is_empty());
1746
1747            a.push(SA { x: [2, 3] });
1748            assert_eq!(2, a.len());
1749            assert!(a.capacity() >= 2);
1750            assert_eq!(false, a.is_empty());
1751
1752            assert_eq!(Some(SA { x: [2, 3] }), a.pop::<SA>());
1753            assert_eq!(1, a.len());
1754            assert!(a.capacity() >= 1);
1755            assert_eq!(false, a.is_empty());
1756
1757            assert_eq!(Some(SA { x: [0, 1] }), a.pop::<SA>());
1758            assert_eq!(0, a.len());
1759            assert_eq!(true, a.is_empty());
1760
1761            assert_eq!(None, a.pop::<SA>());
1762        }
1763    }
1764
1765    #[test]
1766    fn test_any_vec_remove() {
1767        // Safety: Type is correct.
1768        unsafe {
1769            let mut a = AnyVec::new(crate::tinfo!(SA));
1770
1771            a.push(SA { x: [0, 1] });
1772            a.push(SA { x: [2, 3] });
1773            a.push(SA { x: [4, 5] });
1774            a.push(SA { x: [6, 7] });
1775
1776            let removed = a.swap_remove(1);
1777            assert_eq!(SA { x: [2, 3] }, removed);
1778            assert_eq!(3, a.len());
1779            assert_eq!(Some(&SA { x: [0, 1] }), a.get(0));
1780            assert_eq!(Some(&SA { x: [6, 7] }), a.get(1));
1781            assert_eq!(Some(&SA { x: [4, 5] }), a.get(2));
1782
1783            a.swap_remove_drop(1);
1784            assert_eq!(2, a.len());
1785            assert_eq!(Some(&SA { x: [0, 1] }), a.get(0));
1786            assert_eq!(Some(&SA { x: [4, 5] }), a.get(1));
1787        }
1788    }
1789
1790    #[test]
1791    fn test_any_vec_resize() {
1792        unsafe {
1793            // Tests resize().
1794            let mut v = AnyVec::new(crate::tinfo!(i32));
1795            assert!(v.is_empty());
1796
1797            v.resize(10, 42_i32);
1798            assert_eq!(v.len(), 10);
1799
1800            for val in v.iter_of::<i32>() {
1801                assert_eq!(*val, 42);
1802            }
1803
1804            // Tests resize_raw().
1805            #[derive(Clone)]
1806            struct Val(String);
1807
1808            let mut v = AnyVec::new(crate::tinfo!(Val));
1809
1810            let val = Val("42".to_owned());
1811            let val_ptr = NonNull::new(&val as *const Val as *mut Val as *mut u8).unwrap();
1812            v.resize_raw(10, val_ptr);
1813            assert_eq!(v.len(), 10);
1814
1815            for val in v.iter_of::<Val>() {
1816                assert_eq!(val.0.as_str(), "42");
1817            }
1818        }
1819    }
1820
1821    #[cfg(debug_assertions)]
1822    #[test]
1823    #[should_panic]
1824    fn test_any_vec_push_incorrect_type_panic() {
1825        // Unsafe: It will be panicked in debug mode.
1826        unsafe {
1827            let mut a = AnyVec::new(crate::tinfo!(SA));
1828            a.push(SB {
1829                x: [0, 1],
1830                y: [0.1, 0.2],
1831            });
1832        }
1833    }
1834
1835    #[cfg(debug_assertions)]
1836    #[test]
1837    #[should_panic]
1838    fn test_any_vec_pop_incorrect_type_panic() {
1839        // Unsafe: It will be panicked in debug mode.
1840        unsafe {
1841            let mut a = AnyVec::new(crate::tinfo!(SB));
1842            a.push(SB {
1843                x: [0, 1],
1844                y: [0.1, 0.2],
1845            });
1846            let _ = a.pop::<SA>();
1847        }
1848    }
1849
1850    #[test]
1851    fn test_any_vec_into_vec_push_pop() {
1852        // Safety: Type is correct.
1853        unsafe {
1854            let mut a = AnyVec::new(crate::tinfo!(SA));
1855            {
1856                let mut v = (&mut a).as_vec_mut::<SA>();
1857                v.push(SA { x: [0, 1] });
1858                v.push(SA { x: [2, 3] });
1859                assert_eq!(Some(SA { x: [2, 3] }), v.pop());
1860            }
1861
1862            assert_eq!(Some(SA { x: [0, 1] }), a.pop::<SA>());
1863            assert_eq!(None, a.pop::<SA>());
1864
1865            {
1866                let mut v = (&mut a).as_vec_mut::<SA>();
1867                v.push(SA { x: [0, 1] });
1868                v.push(SA { x: [2, 3] });
1869            }
1870            let v_imm = a.as_slice::<SA>();
1871            assert_eq!(Some(&SA { x: [0, 1] }), v_imm.get(0));
1872            assert_eq!(Some(&SA { x: [2, 3] }), v_imm.get(1));
1873        }
1874    }
1875
1876    #[test]
1877    fn test_any_vec_zst() {
1878        // Safety: Type is correct.
1879        unsafe {
1880            let mut v = AnyVec::new(crate::tinfo!(()));
1881            assert!(v.is_empty());
1882            assert_eq!(v.capacity(), usize::MAX);
1883
1884            // Pushing ZST must be possible, and length must be grown by
1885            // pushing.
1886            for i in 1..10 {
1887                v.push(());
1888                assert_eq!(v.len(), i);
1889            }
1890
1891            // We've pushed ZST values, but the vector must not have allocated
1892            // memory.
1893            assert_eq!(v.ptr, AnyVec::aligned_dangling(crate::tinfo!(()).align));
1894
1895            // Popping ZST must be possible, and length must be shrunk by
1896            // popping.
1897            for i in (1..10).rev() {
1898                v.pop_drop();
1899                assert_eq!(v.len(), i - 1);
1900            }
1901
1902            // Reserving capacity for ZST in the vector must have no effects.
1903            v.reserve(100);
1904            assert_eq!(v.capacity(), usize::MAX);
1905
1906            // Shrinking capacity for ZST in the vector must have no effects.
1907            v.shrink_to_fit();
1908            assert_eq!(v.capacity(), usize::MAX);
1909        }
1910    }
1911}