any_vec/
any_vec.rs

1use core::alloc::Layout;
2use core::any::TypeId;
3use core::fmt::{Debug, Formatter};
4use core::marker::PhantomData;
5use core::mem::{ManuallyDrop, MaybeUninit};
6use core::ops::{Deref, DerefMut, Range, RangeBounds};
7use core::ptr::NonNull;
8use core::{fmt, ptr, slice};
9use core::slice::{from_raw_parts, from_raw_parts_mut};
10use crate::{AnyVecTyped, into_range, mem, ops, assert_types_equal};
11use crate::any_value::{AnyValue, AnyValueSizeless, Unknown};
12use crate::any_vec_raw::{AnyVecRaw, DropFn};
13use crate::ops::{TempValue, Remove, SwapRemove, remove, swap_remove, Pop, pop};
14use crate::ops::{Drain, Splice, drain, splice};
15use crate::any_vec::traits::{None};
16use crate::clone_type::{CloneFn, CloneFnTrait, CloneType};
17use crate::element::{ElementPointer, ElementMut, ElementRef};
18use crate::any_vec_ptr::AnyVecPtr;
19use crate::iter::{Iter, IterMut, IterRef};
20use crate::mem::{Mem, MemBuilder, MemBuilderSizeable, MemRawParts, MemResizable};
21use crate::traits::{Cloneable, Trait};
22
23/// Trait constraints.
24/// Possible variants [`Cloneable`], [`Send`] and [`Sync`], in any combination.
25///
26/// # Example
27/// ```rust
28/// use any_vec::AnyVec;
29/// use any_vec::traits::*;
30/// let v1: AnyVec<dyn Cloneable + Sync + Send> = AnyVec::new::<String>();
31/// let v2 = v1.clone();
32///
33/// ```
34pub mod traits{
35    // TODO: rename to TraitConstraints or Constraints?
36    /// [`AnyVec`]s trait constraints.
37    ///
38    /// [`AnyVec`]: crate::AnyVec
39    pub trait Trait: 'static + crate::clone_type::CloneType{}
40    impl Trait for dyn None {}
41    impl Trait for dyn Sync{}
42    impl Trait for dyn Send{}
43    impl Trait for dyn Sync + Send{}
44    impl Trait for dyn Cloneable{}
45    impl Trait for dyn Cloneable + Send{}
46    impl Trait for dyn Cloneable + Sync{}
47    impl Trait for dyn Cloneable + Send+ Sync{}
48
49    /// Does not enforce anything. Default.
50    pub trait None {}
51
52    pub use core::marker::Sync;
53
54    pub use core::marker::Send;
55
56    /// Enforce type [`Clone`]-ability.
57    pub trait Cloneable{}
58}
59
60/// Trait for compile time check - does `T` satisfy `Traits` constraints.
61///
62/// Almost for sure you don't need to use it. It is public - just in case.
63/// In our tests we found niche case where it was needed:
64/// ```rust
65///     # use any_vec::AnyVec;
66///     # use any_vec::SatisfyTraits;
67///     # use any_vec::traits::*;
68///     fn do_test<Traits: ?Sized + Cloneable + Trait>(vec: &mut AnyVec<Traits>)
69///         where String: SatisfyTraits<Traits>,
70///               usize:  SatisfyTraits<Traits>
71///     {
72///         # let something = true;
73///         # let other_something = true;
74///         if something {
75///             *vec = AnyVec::new::<String>();
76///             /*...*/
77///         } else if other_something {
78///             *vec = AnyVec::new::<usize>();
79///             /*...*/
80///         }
81///     # }
82/// ```
83pub trait SatisfyTraits<Traits: ?Sized>: CloneFnTrait<Traits> {}
84impl<T> SatisfyTraits<dyn None> for T{}
85impl<T: Clone> SatisfyTraits<dyn Cloneable> for T{}
86impl<T: Send> SatisfyTraits<dyn Send> for T{}
87impl<T: Sync> SatisfyTraits<dyn Sync> for T{}
88impl<T: Send + Sync> SatisfyTraits<dyn Send + Sync> for T{}
89impl<T: Clone + Send> SatisfyTraits<dyn Cloneable + Send> for T{}
90impl<T: Clone + Sync> SatisfyTraits<dyn Cloneable + Sync> for T{}
91impl<T: Clone + Send + Sync> SatisfyTraits<dyn Cloneable + Send + Sync> for T{}
92
93/// [`AnyVec`] raw parts.
94///
95/// You can get it with [`AnyVec::into_raw_parts`], or build/edit
96/// it manually. And with [`AnyVec::from_raw_parts`], you can construct
97/// [`AnyVec`].
98pub struct RawParts<M: MemBuilder/* = mem::Default*/>
99where
100    M::Mem: MemRawParts
101{
102    pub mem_builder: M,
103    pub mem_handle: <M::Mem as MemRawParts>::Handle,
104    pub capacity:       usize,
105    pub len:            usize,
106    pub element_layout: Layout,
107    pub element_typeid: TypeId,
108    pub element_drop:   Option<DropFn>,
109
110    /// Ignored if non Cloneable.
111    pub element_clone:  CloneFn,
112}
113
114impl<M: MemBuilder> Clone for RawParts<M>
115where
116    M::Mem: MemRawParts,
117    <M::Mem as MemRawParts>::Handle: Clone
118{
119    #[inline]
120    fn clone(&self) -> Self {
121        Self{
122            mem_builder: self.mem_builder.clone(),
123            mem_handle: self.mem_handle.clone(),
124            capacity: self.capacity,
125            len: self.capacity,
126            element_layout: self.element_layout,
127            element_typeid: self.element_typeid,
128            element_drop: self.element_drop,
129            element_clone: self.element_clone,
130        }
131    }
132}
133
134/// Type erased vec-like container.
135/// All elements have the same type.
136///
137/// Only destruct and clone operations have indirect call overhead.
138///
139/// You can make AnyVec [`Send`]-able, [`Sync`]-able, [`Cloneable`], by
140/// specifying trait constraints: `AnyVec<dyn Cloneable + Sync + Send>`. See [`traits`].
141///
142/// Some operations return [`TempValue<Operation>`], which internally holds &mut to [`AnyVec`].
143/// You can drop it, cast to concrete type, or put into another vector. (See [any_value])
144///
145/// *`T: 'static` due to TypeId requirements*
146///
147/// [any_value]: crate::any_value
148pub struct AnyVec<Traits: ?Sized + Trait = dyn None, M: MemBuilder = mem::Default>
149{
150    pub(crate) raw: AnyVecRaw<M>,
151    clone_fn: <Traits as CloneType>::Type,  // ZST if Traits: !Cloneable
152    phantom: PhantomData<Traits>
153}
154
155impl<Traits: ?Sized + Trait, M: MemBuilder> AnyVec<Traits, M>
156{
157    #[inline]
158    fn build<T: SatisfyTraits<Traits>>(raw: AnyVecRaw<M>) -> Self {
159        let clone_fn = <T as CloneFnTrait<Traits>>::CLONE_FN;
160        Self{
161            raw,
162            clone_fn: <Traits as CloneType>::new(clone_fn),
163            phantom: PhantomData
164        }
165    }
166
167    /// Constructs empty [`AnyVec`] with elements of type `T`,
168    /// using [`Default`] [`MemBuilder`].
169    ///
170    /// `T` should satisfy requested Traits.
171    ///
172    /// Not available, if provided [`MemBuilder`] is not [`Default`].
173    #[inline]
174    #[must_use]
175    pub fn new<T: 'static>() -> Self
176    where
177        T: SatisfyTraits<Traits>,
178        M: Default
179    {
180        Self::new_in::<T>(Default::default())
181    }
182
183    /// Constructs empty [`AnyVec`] with elements of type `T`,
184    /// using provided `mem_builder`.
185    ///
186    /// `T` should satisfy requested Traits.
187    #[inline]
188    #[must_use]
189    pub fn new_in<T: 'static>(mut mem_builder: M) -> Self
190        where T: SatisfyTraits<Traits>
191    {
192        let mem = mem_builder.build(Layout::new::<T>());
193        let raw = AnyVecRaw::new::<T>(mem_builder, mem);
194        Self::build::<T>(raw)
195    }
196
197    /// Constructs empty [`AnyVec`] with specified capacity and
198    /// elements of type `T`, using [`Default`] [`MemBuilder`].
199    ///
200    /// `T` should satisfy requested Traits.
201    ///
202    /// Not available, if provided [`MemBuilder`] is not
203    /// [`MemBuilderSizeable`] and [`Default`].
204    #[inline]
205    #[must_use]
206    pub fn with_capacity<T: 'static>(capacity: usize) -> Self
207    where
208        T: SatisfyTraits<Traits>,
209        M: MemBuilderSizeable,
210        M: Default
211    {
212        Self::with_capacity_in::<T>(capacity, Default::default())
213    }
214
215    /// Constructs empty [`AnyVec`] with specified capacity and
216    /// elements of type `T`, using `mem_builder`.
217    ///
218    /// `T` should satisfy requested Traits.
219    ///
220    /// Not available, if provided [`MemBuilder`] is not
221    /// [`MemBuilderSizeable`].
222    #[inline]
223    #[must_use]
224    pub fn with_capacity_in<T: 'static>(capacity: usize, mut mem_builder: M) -> Self
225    where
226        T: SatisfyTraits<Traits>,
227        M: MemBuilderSizeable
228    {
229        let mem = mem_builder.build_with_size(Layout::new::<T>(), capacity);
230        let raw = AnyVecRaw::new::<T>(mem_builder, mem);
231        Self::build::<T>(raw)
232    }
233
234    /// Destructure `AnyVec` into [`RawParts`].
235    #[inline]
236    #[must_use]
237    pub fn into_raw_parts(self) -> RawParts<M>
238    where
239        M::Mem: MemRawParts
240    {
241        let this = ManuallyDrop::new(self);
242
243        let mem_builder = unsafe{ ptr::read(&this.raw.mem_builder) };
244        let mem = unsafe{ ptr::read(&this.raw.mem) };
245        let (mem_handle, element_layout, capacity) = mem.into_raw_parts();
246        RawParts{
247            mem_builder,
248            mem_handle,
249            capacity,
250            len: this.raw.len,
251            element_layout,
252            element_typeid: this.raw.type_id,
253            element_drop: this.raw.drop_fn,
254            element_clone: this.clone_fn()
255        }
256    }
257
258    /// Construct `AnyVec` from previously deconstructed raw parts.
259    ///
260    /// # Safety
261    ///
262    /// ## Traits
263    ///
264    /// Traits validity not checked. `RawParts` of underlying type must implement Traits.
265    /// It is not safe to opt-in [`Cloneable`], if initial `AnyVec` was not constructed with
266    /// that trait.
267    ///
268    /// ## RawParts
269    ///
270    /// `RawParts` validity not checked.
271    ///
272    #[inline]
273    #[must_use]
274    pub unsafe fn from_raw_parts(raw_parts: RawParts<M>) -> Self
275    where
276        M::Mem: MemRawParts
277    {
278        Self{
279            raw: AnyVecRaw{
280                mem_builder: raw_parts.mem_builder,
281                mem: MemRawParts::from_raw_parts(
282                    raw_parts.mem_handle,
283                    raw_parts.element_layout,
284                    raw_parts.capacity
285                ),
286                len: raw_parts.len,
287                type_id: raw_parts.element_typeid,
288                drop_fn: raw_parts.element_drop
289            },
290            clone_fn: <Traits as CloneType>::new(raw_parts.element_clone),
291            phantom: PhantomData
292        }
293    }
294
295    /// Constructs **empty** [`AnyVec`] with the same elements type, `Traits` and `MemBuilder`.
296    /// IOW, same as [`clone`], but without elements copy.
297    ///
298    /// [`clone`]: Clone::clone
299    #[inline]
300    #[must_use]
301    pub fn clone_empty(&self) -> Self {
302        Self {
303            raw: self.raw.clone_empty(),
304            clone_fn: self.clone_fn,
305            phantom: PhantomData
306        }
307    }
308
309    /// Constructs **empty** [`AnyVec`] with the same elements type and `Traits`,
310    /// but with other `MemBuilder`.
311    ///
312    /// Use it to construct intermediate storage, with fast [`MemBuilder`].
313    ///
314    /// # Example
315    ///
316    /// ```
317    /// # use any_vec::any_value::AnyValueCloneable;
318    /// # use any_vec::AnyVec;
319    /// # use any_vec::mem::Stack;
320    /// # use any_vec::traits::Cloneable;
321    /// # let mut any_vec: AnyVec<dyn Cloneable> = AnyVec::new::<String>();
322    /// # any_vec.downcast_mut::<String>().unwrap().push(String::from("0"));
323    /// let mut tmp = any_vec.clone_empty_in(Stack::<256>);
324    ///     tmp.push(any_vec.at(0).lazy_clone());
325    /// any_vec.push(tmp.pop().unwrap());
326    /// ```
327    #[inline]
328    #[must_use]
329    pub fn clone_empty_in<NewM: MemBuilder>(&self, mem_builder: NewM) -> AnyVec<Traits, NewM> {
330        AnyVec {
331            raw: self.raw.clone_empty_in(mem_builder),
332            clone_fn: self.clone_fn,
333            phantom: PhantomData
334        }
335    }
336
337    #[inline]
338    pub(crate) fn clone_fn(&self) -> CloneFn{
339        <Traits as CloneType>::get(self.clone_fn)
340    }
341
342    /// Reserves capacity for at least `additional` more elements to be inserted
343    /// in the given container. More space may be reserved to avoid
344    /// frequent reallocations. After calling `reserve`, capacity will be
345    /// greater than or equal to `self.len() + additional`. Exact behavior defined by
346    /// implementation of [`MemResizable`]. Does nothing if capacity is already sufficient.
347    ///
348    /// Not available, if provided [`MemBuilder::Mem`] is not [`MemResizable`].
349    ///
350    /// # Panics
351    ///
352    /// [`MemResizable`] implementation may panic - see implementation description.
353    #[inline]
354    pub fn reserve(&mut self, additional: usize)
355        where M::Mem: MemResizable
356    {
357        self.raw.reserve(additional)
358    }
359
360    /// Reserves the minimum capacity for exactly `additional` more elements to
361    /// be inserted in the given container. After calling `reserve_exact`,
362    /// capacity will be greater than or equal to `self.len() + additional`.
363    /// Exact behavior defined by implementation of [`MemResizable`].
364    /// Does nothing if the capacity is already sufficient.
365    ///
366    /// Note that the [`Mem`] implementation may grow bigger then requested.
367    /// Therefore, capacity can not be relied upon to be precisely
368    /// minimal. Prefer [`reserve`] if future insertions are expected.
369    ///
370    /// Not available, if provided [`MemBuilder::Mem`] is not [`MemResizable`].
371    ///
372    /// # Panics
373    ///
374    /// [`MemResizable`] implementation may panic - see implementation description.
375    ///
376    /// [`reserve`]: Self::reserve
377    #[inline]
378    pub fn reserve_exact(&mut self, additional: usize)
379        where M::Mem: MemResizable
380    {
381        self.raw.reserve_exact(additional)
382    }
383
384    /// Shrinks the capacity as much as possible.
385    /// Exact behavior defined by implementation of [`MemResizable`].
386    ///
387    /// Not available, if provided [`MemBuilder::Mem`] is not [`MemResizable`].
388    ///
389    /// # Panics
390    ///
391    /// [`MemResizable`] implementation may panic - see implementation description.
392    #[inline]
393    pub fn shrink_to_fit(&mut self)
394        where M::Mem: MemResizable
395    {
396        self.raw.shrink_to_fit()
397    }
398
399    /// Shrinks the capacity of the vector with a lower bound.
400    ///
401    /// The capacity will remain at least as large as both the length
402    /// and the supplied value. Exact behavior defined by implementation of [`MemResizable`].
403    ///
404    /// If the current capacity is less than the lower limit, this is a no-op.
405    ///
406    /// Not available, if provided [`MemBuilder::Mem`] is not [`MemResizable`].
407    ///
408    /// # Panics
409    ///
410    /// [`MemResizable`] implementation may panic - see implementation description.
411    #[inline]
412    pub fn shrink_to(&mut self, min_capacity: usize)
413        where M::Mem: MemResizable
414    {
415        self.raw.shrink_to(min_capacity)
416    }
417
418    #[inline]
419    pub unsafe fn set_len(&mut self, new_len: usize) {
420        self.raw.set_len(new_len);
421    }
422
423    /// Returns [`AnyVecRef`] - typed view to const AnyVec,
424    /// if container holds elements of type T, or None if it isn’t.
425    #[inline]
426    pub fn downcast_ref<T: 'static>(&self) -> Option<AnyVecRef<'_, T, M>> {
427        if self.element_typeid() == TypeId::of::<T>() {
428            unsafe{ Some(self.downcast_ref_unchecked()) }
429        } else {
430            None
431        }
432    }
433
434    /// Returns [`AnyVecRef`] - typed view to const AnyVec.
435    ///
436    /// # Safety
437    ///
438    /// The container elements must be of type `T`.
439    /// Calling this method with the incorrect type is undefined behavior.
440    #[inline]
441    pub unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> AnyVecRef<'_, T, M> {
442        AnyVecRef(AnyVecTyped::new(NonNull::from(&self.raw)))
443    }
444
445    /// Returns [`AnyVecMut`] - typed view to mut AnyVec,
446    /// if container holds elements of type T, or None if it isn’t.
447    #[inline]
448    pub fn downcast_mut<T: 'static>(&mut self) -> Option<AnyVecMut<'_, T, M>> {
449        if self.element_typeid() == TypeId::of::<T>() {
450            unsafe{ Some(self.downcast_mut_unchecked()) }
451        } else {
452            None
453        }
454    }
455
456    /// Returns [`AnyVecMut`] - typed view to mut AnyVec.
457    ///
458    /// # Safety
459    ///
460    /// The container elements must be of type `T`.
461    /// Calling this method with the incorrect type is undefined behavior.
462    #[inline]
463    pub unsafe fn downcast_mut_unchecked<T: 'static>(&mut self) -> AnyVecMut<'_, T, M> {
464        AnyVecMut(AnyVecTyped::new(NonNull::from(&mut self.raw)))
465    }
466
467    #[inline]
468    pub fn as_bytes(&self) -> &[u8] {
469        unsafe{from_raw_parts(
470            self.raw.mem.as_ptr(),
471            self.len() * self.element_layout().size()
472        )}
473    }
474
475    #[inline]
476    pub fn as_bytes_mut(&mut self) -> &mut [u8]{
477        unsafe{from_raw_parts_mut(
478            self.raw.mem.as_mut_ptr(),
479            self.len() * self.element_layout().size()
480        )}
481    }
482
483    #[inline]
484    pub fn spare_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>]{
485        unsafe{from_raw_parts_mut(
486            self.raw.mem.as_mut_ptr().add(self.len()) as *mut MaybeUninit<u8>,
487            (self.capacity() - self.len()) * self.element_layout().size()
488        )}
489    }
490
491    #[inline]
492    pub fn iter(&self) -> IterRef<'_, Traits, M>{
493        Iter::new(AnyVecPtr::from(self), 0, self.len())
494    }
495
496    #[inline]
497    pub fn iter_mut(&mut self) -> IterMut<'_, Traits, M>{
498        let len = self.len();
499        Iter::new(AnyVecPtr::from(self), 0, len)
500    }
501
502    /// Return reference to element at `index` with bounds check.
503    ///
504    /// # Panics
505    ///
506    /// * Panics if index is out of bounds.
507    #[inline]
508    pub fn at(&self, index: usize) -> ElementRef<'_, Traits, M>{
509        self.get(index).unwrap()
510    }
511
512    #[inline]
513    pub fn get(&self, index: usize) -> Option<ElementRef<'_, Traits, M>>{
514        if index < self.len(){
515            Some(unsafe{ self.get_unchecked(index) })
516        } else {
517            None
518        }
519    }
520
521    #[inline]
522    pub unsafe fn get_unchecked(&self, index: usize) -> ElementRef<'_, Traits, M>{
523        let element_ptr = self.raw.get_unchecked(index) as *mut u8;
524        ElementRef(
525            ManuallyDrop::new(ElementPointer::new(
526                AnyVecPtr::from(self),
527                NonNull::new_unchecked(element_ptr)
528            ))
529        )
530    }
531
532    /// Return mutable reference to element at `index` with bounds check.
533    ///
534    /// # Panics
535    ///
536    /// * Panics if index is out of bounds.
537    #[inline]
538    pub fn at_mut(&mut self, index: usize) -> ElementMut<'_, Traits, M>{
539        self.get_mut(index).unwrap()
540    }
541
542    #[inline]
543    pub fn get_mut(&mut self, index: usize) -> Option<ElementMut<'_, Traits, M>>{
544        if index < self.len(){
545            Some(unsafe{ self.get_unchecked_mut(index) })
546        } else {
547            None
548        }
549    }
550
551    #[inline]
552    pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> ElementMut<'_, Traits, M> {
553        let element_ptr = self.raw.get_unchecked_mut(index);
554        ElementMut(
555            ManuallyDrop::new(ElementPointer::new(
556                AnyVecPtr::from(self),
557                NonNull::new_unchecked(element_ptr)
558            ))
559        )
560    }
561
562    /// # Panics
563    ///
564    /// * Panics if type mismatch.
565    /// * Panics if index is out of bounds.
566    /// * Panics if out of memory.
567    #[inline]
568    pub fn insert<V: AnyValue>(&mut self, index: usize, value: V) {
569        self.raw.type_check(&value);
570        unsafe{
571            self.raw.insert_unchecked(index, value);
572        }
573    }
574
575    /// Same as [`insert`], but without type checks.
576    ///
577    /// # Panics
578    ///
579    /// * Panics if index is out of bounds.
580    /// * Panics if out of memory.
581    ///
582    /// # Safety
583    ///
584    /// Type not checked.
585    ///
586    /// [`insert`]: Self::insert
587    #[inline]
588    pub unsafe fn insert_unchecked<V: AnyValueSizeless>(&mut self, index: usize, value: V) {
589        self.raw.insert_unchecked(index, value);
590    }
591
592    /// # Panics
593    ///
594    /// * Panics if type mismatch.
595    /// * Panics if out of memory.
596    #[inline]
597    pub fn push<V: AnyValue>(&mut self, value: V) {
598        self.raw.type_check(&value);
599        unsafe{
600            self.raw.push_unchecked(value);
601        }
602    }
603
604    /// Same as [`push`], but without type checks.
605    ///
606    /// # Panics
607    ///
608    /// Panics if out of memory.
609    ///
610    /// # Safety
611    ///
612    /// Type not checked.
613    ///
614    /// [`push`]: Self::push
615    #[inline]
616    pub unsafe fn push_unchecked<V: AnyValueSizeless>(&mut self, value: V) {
617        self.raw.push_unchecked(value);
618    }
619
620    /// # Leaking
621    ///
622    /// If the returned [`TempValue`] goes out of scope without being dropped (due to
623    /// [`mem::forget`], for example), the vector will lost and leak last element.
624    ///
625    /// [`mem::forget`]: core::mem::forget
626    ///
627    #[inline]
628    pub fn pop(&mut self) -> Option<Pop<'_, Traits, M>> {
629        if self.is_empty(){
630            None
631        } else {
632            Some(TempValue::new(
633                pop::Pop::new(AnyVecPtr::from(self))
634            ))
635        }
636    }
637
638    /// # Panics
639    ///
640    /// Panics if index out of bounds.
641    ///
642    /// # Leaking
643    ///
644    /// If the returned [`TempValue`] goes out of scope without being dropped (due to
645    /// [`mem::forget`], for example), the vector may have lost and leaked
646    /// elements with indices >= index.
647    ///
648    /// [`mem::forget`]: core::mem::forget
649    ///
650    #[inline]
651    pub fn remove(&mut self, index: usize) -> Remove<'_, Traits, M> {
652        self.raw.index_check(index);
653        TempValue::new(remove::Remove::new(
654            AnyVecPtr::from(self),
655            index
656        ))
657    }
658
659    /// # Panics
660    ///
661    /// Panics if index out of bounds.
662    ///
663    /// # Leaking
664    ///
665    /// If the returned [`TempValue`] goes out of scope without being dropped (due to
666    /// [`mem::forget`], for example), the vector may have lost and leaked
667    /// elements with indices >= index.
668    ///
669    /// [`mem::forget`]: core::mem::forget
670    ///
671    #[inline]
672    pub fn swap_remove(&mut self, index: usize) -> SwapRemove<'_, Traits, M> {
673        self.raw.index_check(index);
674        TempValue::new(swap_remove::SwapRemove::new(
675            AnyVecPtr::from(self),
676            index
677        ))
678    }
679    
680    /// Moves all the elements of `other` into `self`, leaving `other` empty.
681    /// 
682    /// # Panics
683    /// 
684    /// * Panics if types mismatch.
685    /// * Panics if out of memory.
686    pub fn append<OtherTraits, OtherM>(
687        &mut self, other: &mut AnyVec<OtherTraits, OtherM>
688    ) where
689        OtherTraits: ?Sized + Trait, 
690        OtherM: MemBuilder
691    {
692        assert_types_equal(other.element_typeid(), self.element_typeid());
693        unsafe{
694            self.raw.append_unchecked::<Unknown, _>(&mut other.raw);
695        }
696    }
697
698    /// Removes the specified range from the vector in bulk, returning all removed
699    /// elements as an iterator. If the iterator is dropped before being fully consumed,
700    /// it drops the remaining removed elements.
701    ///
702    /// The returned iterator keeps a mutable borrow on the vector.
703    ///
704    /// # Panics
705    ///
706    /// Panics if the starting point is greater than the end point or if the end point
707    /// is greater than the length of the vector.
708    ///
709    /// # Leaking
710    ///
711    /// If the returned iterator goes out of scope without being dropped (due to
712    /// [`mem::forget`], for example), the vector may have lost and leaked
713    /// elements with indices in and past the range.
714    ///
715    /// [`mem::forget`]: core::mem::forget
716    ///
717    #[inline]
718    pub fn drain(&mut self, range: impl RangeBounds<usize>) -> Drain<'_, Traits, M> {
719        let Range{start, end} = into_range(self.len(), range);
720        ops::Iter(drain::Drain::new(
721            AnyVecPtr::from(self),
722            start,
723            end
724        ))
725    }
726
727    /// Creates a splicing iterator that replaces the specified range in the vector
728    /// with the given `replace_with` iterator and yields the removed items.
729    /// `replace_with` does not need to be the same length as `range`.
730    ///
731    /// `range` is removed even if the iterator is not consumed until the end.
732    ///
733    /// The returned iterator keeps a mutable borrow on the vector.
734    ///
735    /// # Panics
736    ///
737    /// Panics if the starting point is greater than the end point or if
738    /// the end point is greater than the length of the vector.
739    ///
740    /// # Leaking
741    ///
742    /// If the returned iterator goes out of scope without being dropped (due to
743    /// [`mem::forget`], for example), the vector may have lost and leaked
744    /// elements with indices in and past the range.
745    ///
746    /// [`mem::forget`]: core::mem::forget
747    ///
748    #[inline]
749    pub fn splice<I: IntoIterator>(&mut self, range: impl RangeBounds<usize>, replace_with: I)
750        -> Splice<'_, Traits, M, I::IntoIter>
751    where
752        I::IntoIter: ExactSizeIterator,
753        I::Item: AnyValue
754    {
755        let Range{start, end} = into_range(self.len(), range);
756        ops::Iter(splice::Splice::new(
757            AnyVecPtr::from(self),
758            start,
759            end,
760            replace_with.into_iter()
761        ))
762    }
763
764    #[inline]
765    pub fn clear(&mut self){
766        self.raw.clear()
767    }
768
769    /// Element TypeId
770    #[inline]
771    pub fn element_typeid(&self) -> TypeId{
772        self.raw.type_id
773    }
774
775    /// Element Layout
776    #[inline]
777    pub fn element_layout(&self) -> Layout {
778        self.raw.element_layout()
779    }
780
781    /// Element drop function.
782    ///
783    /// `len` - elements count.
784    /// None - drop is not needed.
785    #[inline]
786    pub fn element_drop(&self) -> Option<DropFn> {
787        self.raw.drop_fn
788    }
789
790    /// Element clone function.
791    ///
792    /// `len` - elements count.
793    #[inline]
794    pub fn element_clone(&self) -> CloneFn
795    where
796        Traits: Cloneable
797    {
798        self.clone_fn()
799    }
800
801    #[inline]
802    pub fn len(&self) -> usize {
803        self.raw.len
804    }
805
806    #[inline]
807    pub fn is_empty(&self) -> bool {
808        self.len() == 0
809    }
810
811    #[inline]
812    pub fn capacity(&self) -> usize {
813        self.raw.capacity()
814    }
815}
816
817unsafe impl<Traits: ?Sized + Send + Trait, M: MemBuilder + Send> Send for AnyVec<Traits, M>
818    where M::Mem: Send
819{}
820unsafe impl<Traits: ?Sized + Sync + Trait, M: MemBuilder + Sync> Sync for AnyVec<Traits, M>
821    where M::Mem: Sync
822{}
823impl<Traits: ?Sized + Cloneable + Trait, M: MemBuilder> Clone for AnyVec<Traits, M>
824{
825    fn clone(&self) -> Self {
826        Self{
827            raw: unsafe{ self.raw.clone(self.clone_fn()) },
828            clone_fn: self.clone_fn,
829            phantom: PhantomData
830        }
831    }
832}
833
834impl<Traits, M, A> Extend<A> for AnyVec<Traits, M>
835where
836    Traits: ?Sized + Trait, 
837    M: MemBuilder,
838    A: AnyValue,
839{
840    /// # Panics
841    ///
842    /// * Panics if type mismatch.
843    /// * Panics if out of memory.
844    fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T) {
845        let iter = iter.into_iter();
846        self.raw.reserve(iter.size_hint().0);
847        for v in iter {
848            self.push(v);
849        }
850    }
851}
852
853impl<Traits: ?Sized + Trait, M: MemBuilder> Debug for AnyVec<Traits, M>{
854    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
855        f.debug_struct("AnyVec")
856         .field("typeid", &self.element_typeid())
857         .field("len", &self.len())
858         .finish()
859    }
860}
861
862impl<'a, Traits: ?Sized + Trait, M: MemBuilder> IntoIterator for &'a AnyVec<Traits, M>{
863    type Item = ElementRef<'a, Traits, M>;
864    type IntoIter = IterRef<'a, Traits, M>;
865
866    #[inline]
867    fn into_iter(self) -> Self::IntoIter {
868        self.iter()
869    }
870}
871
872impl<'a, Traits: ?Sized + Trait, M: MemBuilder> IntoIterator for &'a mut AnyVec<Traits, M>{
873    type Item = ElementMut<'a, Traits, M>;
874    type IntoIter = IterMut<'a, Traits, M>;
875
876    #[inline]
877    fn into_iter(self) -> Self::IntoIter {
878        self.iter_mut()
879    }
880}
881
882/// Typed view to &[`AnyVec`].
883///
884/// You can get it from [`AnyVec::downcast_ref`].
885///
886/// [`AnyVec`]: crate::AnyVec
887/// [`AnyVec::downcast_ref`]: crate::AnyVec::downcast_ref
888pub struct AnyVecRef<'a, T: 'static, M: MemBuilder + 'a>(pub(crate) AnyVecTyped<'a, T, M>);
889impl<'a, T: 'static, M: MemBuilder + 'a> Clone for AnyVecRef<'a, T, M>{
890    #[inline]
891    fn clone(&self) -> Self {
892        Self(self.0.clone())
893    }
894}
895impl<'a, T: 'static, M: MemBuilder + 'a> Deref for AnyVecRef<'a, T, M>{
896    type Target = AnyVecTyped<'a, T, M>;
897
898    #[inline]
899    fn deref(&self) -> &Self::Target {
900        &self.0
901    }
902}
903impl<'a, T: 'static, M: MemBuilder + 'a> IntoIterator for AnyVecRef<'a, T, M>{
904    type Item = &'a T;
905    type IntoIter = slice::Iter<'a, T>;
906
907    #[inline]
908    fn into_iter(self) -> Self::IntoIter {
909        self.iter()
910    }
911}
912impl<'a, T: 'static + Debug, M: MemBuilder + 'a> Debug for AnyVecRef<'a, T, M>{
913    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
914        self.0.fmt(f)
915    }
916}
917
918/// Typed view to &mut [`AnyVec`].
919///
920/// You can get it from [`AnyVec::downcast_mut`].
921///
922/// [`AnyVec`]: crate::AnyVec
923/// [`AnyVec::downcast_mut`]: crate::AnyVec::downcast_mut
924pub struct AnyVecMut<'a, T: 'static, M: MemBuilder + 'a>(pub(crate) AnyVecTyped<'a, T, M>);
925impl<'a, T: 'static, M: MemBuilder + 'a> Deref for AnyVecMut<'a, T, M>{
926    type Target = AnyVecTyped<'a, T, M>;
927
928    #[inline]
929    fn deref(&self) -> &Self::Target {
930        &self.0
931    }
932}
933impl<'a, T: 'static, M: MemBuilder + 'a> DerefMut for AnyVecMut<'a, T, M>{
934    #[inline]
935    fn deref_mut(&mut self) -> &mut Self::Target {
936        &mut self.0
937    }
938}
939impl<'a, T: 'static, M: MemBuilder + 'a> IntoIterator for AnyVecMut<'a, T, M>{
940    type Item = &'a mut T;
941    type IntoIter = slice::IterMut<'a, T>;
942
943    #[inline]
944    fn into_iter(mut self) -> Self::IntoIter {
945        self.iter_mut()
946    }
947}
948impl<'a, T: 'static + Debug, M: MemBuilder + 'a> Debug for AnyVecMut<'a, T, M>{
949    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
950        self.0.fmt(f)
951    }
952}
953impl<'a, T: 'static, M: MemBuilder + 'a> Extend<T> for AnyVecMut<'a, T, M>{
954    #[inline]
955    fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
956        self.0.extend(iter)
957    }
958}