typed_index_collections/
vec.rs

1use alloc::borrow::Cow;
2use alloc::boxed::Box;
3use alloc::collections::TryReserveError;
4use alloc::ffi::CString;
5use alloc::string::String;
6use alloc::vec::{self, Drain, Splice, Vec};
7use core::borrow::{Borrow, BorrowMut};
8use core::cmp::Ordering;
9use core::hash::{Hash, Hasher};
10use core::iter::FromIterator;
11use core::marker::PhantomData;
12use core::mem::MaybeUninit;
13use core::ops::{Deref, DerefMut, Index, IndexMut, RangeBounds};
14use core::{fmt, slice};
15#[cfg(feature = "std")]
16use std::io::{IoSlice, Result as IoResult, Write};
17
18#[cfg(feature = "bincode")]
19use bincode::de::{BorrowDecode, BorrowDecoder, Decode, Decoder};
20#[cfg(feature = "bincode")]
21use bincode::enc::{Encode, Encoder};
22#[cfg(feature = "bincode")]
23use bincode::error::{DecodeError, EncodeError};
24#[cfg(all(feature = "alloc", feature = "serde"))]
25use serde::de::{Deserialize, Deserializer};
26#[cfg(feature = "serde")]
27use serde::ser::{Serialize, Serializer};
28
29use crate::{TiEnumerated, TiRangeBounds, TiSlice, TiSliceIndex};
30
31/// A contiguous growable array type
32/// that only accepts keys of the type `K`.
33///
34/// `TiVec<K, V>` is a wrapper around Rust container type [`std::vec::Vec`].
35/// The struct mirrors the stable API of Rust [`std::vec::Vec`]
36/// and forwards to it as much as possible.
37///
38/// `TiVec<K, V>` uses `K` instead of `usize` for element indices and
39/// require the index to implement
40/// [`From<usize>`][`From`] and [`Into<usize>`][`Into`] traits.
41/// Their implementation can be easily done
42/// with [`derive_more`] crate and `#[derive(From, Into)]`.
43///
44/// `TiVec<K, V>` can be converted to [`std::vec::Vec<V>`][`std::vec::Vec`] and
45/// back using [`From`] and [`Into`].
46///
47/// There are also zero-cost conversions available between references:
48/// - [`&std::vec::Vec<V>`][`std::vec::Vec`] and `&TiVec<K, V>` with [`AsRef`],
49/// - [`&mut std::vec::Vec<V>`][`std::vec::Vec`] and `&mut TiVec<K, V>` with
50///   [`AsMut`],
51///
52/// Added methods:
53/// - [`from_ref`] - Converts a [`&std::vec::Vec<V>`][`std::vec::Vec`] into a
54///   `&TiVec<K, V>`.
55/// - [`from_mut`] - Converts a [`&mut std::vec::Vec<V>`][`std::vec::Vec`] into
56///   a `&mut TiVec<K, V>`.
57/// - [`push_and_get_key`] - Appends an element to the back of a collection and
58///   returns its index of type `K`.
59/// - [`pop_key_value`] - Removes the last element from a vector and returns it
60///   with its index of type `K`, or [`None`] if the vector is empty.
61/// - [`drain_enumerated`] - Creates a draining iterator that removes the
62///   specified range in the vector and yields the current count and the removed
63///   items. It acts like `self.drain(range).enumerate()`, but instead of
64///   `usize` it returns index of type `K`.
65/// - [`into_iter_enumerated`] - Converts the vector into iterator over all
66///   key-value pairs with `K` used for iteration indices. It acts like
67///   `self.into_iter().enumerate()`, but use `K` instead of `usize` for
68///   iteration indices.
69///
70/// # Example
71///
72/// ```
73/// use derive_more::{From, Into};
74/// use typed_index_collections::TiVec;
75///
76/// #[derive(From, Into)]
77/// struct FooId(usize);
78///
79/// let mut foos: TiVec<FooId, usize> = std::vec![10, 11, 13].into();
80/// foos.insert(FooId(2), 12);
81/// assert_eq!(foos[FooId(2)], 12);
82/// ```
83///
84/// [`from_ref`]: #method.from_ref
85/// [`from_mut`]: #method.from_mut
86/// [`push_and_get_key`]: #method.push_and_get_key
87/// [`pop_key_value`]: #method.pop_key_value
88/// [`drain_enumerated`]: #method.drain_enumerated
89/// [`into_iter_enumerated`]: #method.into_iter_enumerated
90/// [`std::vec::Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
91/// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
92/// [`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html
93/// [`AsRef`]: https://doc.rust-lang.org/std/convert/trait.AsRef.html
94/// [`AsMut`]: https://doc.rust-lang.org/std/convert/trait.AsMut.html
95/// [`derive_more`]: https://crates.io/crates/derive_more
96#[repr(transparent)]
97pub struct TiVec<K, V> {
98    /// Raw slice property
99    pub raw: Vec<V>,
100
101    /// Tied slice index type
102    ///
103    /// `fn(T) -> T` is *[PhantomData pattern][phantomdata patterns]*
104    /// used to relax auto trait implementations bounds for
105    /// [`Send`], [`Sync`], [`Unpin`], [`UnwindSafe`] and [`RefUnwindSafe`].
106    ///
107    /// Derive attribute is not used for trait implementations because it also
108    /// requires the same trait implemented for K that is an unnecessary
109    /// requirement.
110    ///
111    /// [phantomdata patterns]: https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns
112    /// [`Send`]: https://doc.rust-lang.org/core/marker/trait.Send.html
113    /// [`Sync`]: https://doc.rust-lang.org/core/marker/trait.Sync.html
114    /// [`Unpin`]: https://doc.rust-lang.org/core/marker/trait.Unpin.html
115    /// [`UnwindSafe`]: https://doc.rust-lang.org/core/std/panic/trait.UnwindSafe.html
116    /// [`RefUnwindSafe`]: https://doc.rust-lang.org/core/std/panic/trait.RefUnwindSafe.html
117    _marker: PhantomData<fn(K) -> K>,
118}
119
120impl<K, V> TiVec<K, V> {
121    /// Constructs a new, empty `TiVec<K, V>`.
122    ///
123    /// See [`Vec::new`] for more details.
124    ///
125    /// [`Vec::new`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.new
126    #[inline]
127    #[must_use]
128    pub const fn new() -> Self {
129        Self {
130            raw: Vec::new(),
131            _marker: PhantomData,
132        }
133    }
134
135    /// Constructs a new, empty `TiVec<K, V>` with the specified capacity.
136    ///
137    /// See [`Vec::with_capacity`] for more details.
138    ///
139    /// [`Vec::with_capacity`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.with_capacity
140    #[inline]
141    #[must_use]
142    pub fn with_capacity(capacity: usize) -> Self {
143        Self {
144            raw: Vec::with_capacity(capacity),
145            _marker: PhantomData,
146        }
147    }
148
149    /// Creates a `TiVec<K, V>` directly from the raw components of another
150    /// vector.
151    ///
152    /// See [`Vec::from_raw_parts`] for more details.
153    ///
154    /// # Safety
155    ///
156    /// This is highly unsafe, due to the number of invariants that aren't
157    /// checked.
158    /// See [`Vec::from_raw_parts`] for more details.
159    ///
160    /// [`Vec::from_raw_parts`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.from_raw_parts
161    #[inline]
162    pub unsafe fn from_raw_parts(ptr: *mut V, length: usize, capacity: usize) -> Self {
163        Self {
164            // SAFETY: Guaranteed by the caller.
165            raw: unsafe { Vec::from_raw_parts(ptr, length, capacity) },
166            _marker: PhantomData,
167        }
168    }
169
170    /// Converts a [`&std::vec::Vec<V>`] into a `&TiVec<K, V>`.
171    ///
172    /// Vector reference is intentionally used in the argument
173    /// instead of slice reference for conversion with no-op.
174    ///
175    /// # Example
176    ///
177    /// ```
178    /// # use typed_index_collections::TiVec;
179    /// pub struct Id(usize);
180    /// let vec: &TiVec<Id, usize> = TiVec::from_ref(&vec![1, 2, 4]);
181    /// ```
182    ///
183    /// [`&std::vec::Vec<V>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
184    #[inline]
185    #[must_use]
186    pub const fn from_ref(raw: &Vec<V>) -> &Self {
187        // SAFETY: `TiVec<K, V>` is `repr(transparent)` over a `Vec<V>` type.
188        unsafe { &*core::ptr::from_ref::<Vec<V>>(raw).cast::<Self>() }
189    }
190
191    /// Converts a [`&mut std::vec::Vec<V>`] into a `&mut TiVec<K, V>`.
192    ///
193    /// # Example
194    ///
195    /// ```
196    /// # use typed_index_collections::TiVec;
197    /// pub struct Id(usize);
198    /// let vec: &mut TiVec<Id, usize> = TiVec::from_mut(&mut vec![1, 2, 4]);
199    /// ```
200    ///
201    /// [`&mut std::vec::Vec<V>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
202    #[inline]
203    pub fn from_mut(raw: &mut Vec<V>) -> &mut Self {
204        // SAFETY: `TiVec<K, V>` is `repr(transparent)` over a `Vec<V>` type.
205        unsafe { &mut *core::ptr::from_mut::<Vec<V>>(raw).cast::<Self>() }
206    }
207
208    /// Returns the number of elements the vector can hold without
209    /// reallocating.
210    ///
211    /// See [`Vec::capacity`] for more details.
212    ///
213    /// [`Vec::capacity`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.capacity
214    #[inline]
215    #[must_use]
216    pub fn capacity(&self) -> usize {
217        self.raw.capacity()
218    }
219
220    /// Reserves capacity for at least `additional` more elements to be inserted
221    /// in the given `TiVec<K, V>`. The collection may reserve more space to
222    /// avoid frequent reallocations. After calling `reserve`, capacity will
223    /// be greater than or equal to `self.len() + additional`. Does nothing
224    /// if capacity is already sufficient.
225    ///
226    /// See [`Vec::reserve`] for more details.
227    ///
228    /// [`Vec::reserve`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.reserve
229    #[inline]
230    pub fn reserve(&mut self, additional: usize) {
231        self.raw.reserve(additional);
232    }
233
234    /// Reserves the minimum capacity for exactly `additional` more elements to
235    /// be inserted in the given `TiVec<K, V>`. After calling `reserve_exact`,
236    /// capacity will be greater than or equal to `self.len() + additional`.
237    /// Does nothing if the capacity is already sufficient.
238    ///
239    /// See [`Vec::reserve_exact`] for more details.
240    ///
241    /// [`Vec::reserve_exact`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.reserve_exact
242    #[inline]
243    pub fn reserve_exact(&mut self, additional: usize) {
244        self.raw.reserve_exact(additional);
245    }
246
247    /// Tries to reserve capacity for at least `additional` more elements to be
248    /// inserted in the given `Vec<T>`.
249    ///
250    /// See [`Vec::try_reserve`] for more details.
251    ///
252    /// # Errors
253    ///
254    /// If the capacity overflows, or the allocator reports a failure, then an
255    /// error is returned.
256    ///
257    /// [`Vec::try_reserve`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.try_reserve
258    #[inline]
259    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
260        self.raw.try_reserve(additional)
261    }
262
263    /// Tries to reserve the minimum capacity for at least `additional`
264    /// elements to be inserted in the given `Vec<T>`.
265    ///
266    /// See [`Vec::try_reserve_exact`] for more details.
267    ///
268    /// # Errors
269    ///
270    /// If the capacity overflows, or the allocator reports a failure, then an
271    /// error is returned.
272    ///
273    /// [`Vec::try_reserve_exact`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.try_reserve_exact
274    #[inline]
275    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
276        self.raw.try_reserve_exact(additional)
277    }
278
279    /// Shrinks the capacity of the vector as much as possible.
280    ///
281    /// See [`Vec::shrink_to_fit`] for more details.
282    ///
283    /// [`Vec::shrink_to_fit`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.shrink_to_fit
284    #[inline]
285    pub fn shrink_to_fit(&mut self) {
286        self.raw.shrink_to_fit();
287    }
288
289    /// Shrinks the capacity of the vector with a lower bound.
290    ///
291    /// See [`Vec::shrink_to`] for more details.
292    ///
293    /// [`Vec::shrink_to`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.shrink_to
294    #[inline]
295    pub fn shrink_to(&mut self, min_capacity: usize) {
296        self.raw.shrink_to(min_capacity);
297    }
298    /// Converts the vector into [`Box<TiSlice<K, V>>`][`Box`].
299    ///
300    /// See [`Vec::into_boxed_slice`] for more details.
301    ///
302    /// [`Vec::into_boxed_slice`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.into_boxed_slice
303    /// [`Box`]: https://doc.rust-lang.org/std/boxed/struct.Box.html
304    #[inline]
305    #[must_use]
306    pub fn into_boxed_slice(self) -> Box<TiSlice<K, V>> {
307        self.raw.into_boxed_slice().into()
308    }
309
310    /// Shortens the vector, keeping the first `len` elements and dropping
311    /// the rest.
312    ///
313    /// See [`Vec::truncate`] for more details.
314    ///
315    /// [`Vec::truncate`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.truncate
316    #[inline]
317    pub fn truncate(&mut self, len: usize) {
318        self.raw.truncate(len);
319    }
320
321    /// Extracts a slice containing the entire vector.
322    ///
323    /// See [`Vec::as_slice`] for more details.
324    ///
325    /// [`Vec::as_slice`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_slice
326    #[inline]
327    #[must_use]
328    pub fn as_slice(&self) -> &TiSlice<K, V> {
329        self.raw.as_slice().as_ref()
330    }
331
332    /// Extracts a mutable slice of the entire vector.
333    ///
334    /// See [`Vec::as_mut_slice`] for more details.
335    ///
336    /// [`Vec::as_mut_slice`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_mut_slice
337    #[inline]
338    pub fn as_mut_slice(&mut self) -> &mut TiSlice<K, V> {
339        self.raw.as_mut_slice().as_mut()
340    }
341
342    /// Returns a raw pointer to the vector's buffer.
343    ///
344    /// See [`Vec::as_ptr`] for more details.
345    ///
346    /// [`Vec::as_ptr`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_ptr
347    #[inline]
348    #[must_use]
349    pub fn as_ptr(&self) -> *const V {
350        self.raw.as_ptr()
351    }
352
353    /// Returns an unsafe mutable pointer to the vector's buffer.
354    ///
355    /// See [`Vec::as_mut_ptr`] for more details.
356    ///
357    /// [`Vec::as_mut_ptr`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_mut_ptr
358    #[inline]
359    pub fn as_mut_ptr(&mut self) -> *mut V {
360        self.raw.as_mut_ptr()
361    }
362
363    /// Forces the length of the vector to `new_len`.
364    ///
365    /// See [`Vec::set_len`] for more details.
366    ///
367    /// # Safety
368    ///
369    /// - `new_len` must be less than or equal to [`capacity()`].
370    /// - The elements at `old_len..new_len` must be initialized.
371    ///
372    /// [`Vec::set_len`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.set_len
373    /// [`capacity()`]: #method.capacity
374    #[inline]
375    pub unsafe fn set_len(&mut self, new_len: usize) {
376        // SAFETY: Guaranteed by the caller.
377        unsafe { self.raw.set_len(new_len) };
378    }
379
380    /// Removes an element from the vector and returns it.
381    ///
382    /// The removed element is replaced by the last element of the vector.
383    ///
384    /// See [`Vec::swap_remove`] for more details.
385    ///
386    /// [`Vec::swap_remove`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.swap_remove
387    #[inline]
388    pub fn swap_remove(&mut self, index: K) -> V
389    where
390        usize: From<K>,
391    {
392        self.raw.swap_remove(index.into())
393    }
394
395    /// Inserts an element at position `index` within the vector, shifting all
396    /// elements after it to the right.
397    ///
398    /// See [`Vec::insert`] for more details.
399    ///
400    /// [`Vec::insert`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.insert
401    #[inline]
402    pub fn insert(&mut self, index: K, element: V)
403    where
404        usize: From<K>,
405    {
406        self.raw.insert(index.into(), element);
407    }
408
409    /// Removes and returns the element at position `index` within the vector,
410    /// shifting all elements after it to the left.
411    ///
412    /// See [`Vec::remove`] for more details.
413    ///
414    /// [`Vec::remove`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.remove
415    #[inline]
416    pub fn remove(&mut self, index: K) -> V
417    where
418        usize: From<K>,
419    {
420        self.raw.remove(index.into())
421    }
422
423    /// Retains only the elements specified by the predicate.
424    ///
425    /// See [`Vec::retain`] for more details.
426    ///
427    /// [`Vec::retain`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.retain
428    #[inline]
429    pub fn retain<F>(&mut self, f: F)
430    where
431        F: FnMut(&V) -> bool,
432    {
433        self.raw.retain(f);
434    }
435
436    /// Retains only the elements specified by the predicate, passing a mutable
437    /// reference to it.
438    ///
439    /// See [`Vec::retain_mut`] for more details.
440    ///
441    /// [`Vec::retain_mut`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.retain_mut
442    #[inline]
443    pub fn retain_mut<F>(&mut self, f: F)
444    where
445        F: FnMut(&mut V) -> bool,
446    {
447        self.raw.retain_mut(f);
448    }
449
450    /// Removes all but the first of consecutive elements in the vector that
451    /// resolve to the same key.
452    ///
453    /// See [`Vec::dedup_by_key`] for more details.
454    ///
455    /// [`Vec::dedup_by_key`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.dedup_by_key
456    #[inline]
457    pub fn dedup_by_key<F, K2>(&mut self, key: F)
458    where
459        F: FnMut(&mut V) -> K2,
460        K2: PartialEq,
461    {
462        self.raw.dedup_by_key(key);
463    }
464
465    /// Removes all but the first of consecutive elements in the vector
466    /// satisfying a given equality relation.
467    ///
468    /// See [`Vec::dedup_by`] for more details.
469    ///
470    /// [`Vec::dedup_by`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.dedup_by
471    #[inline]
472    pub fn dedup_by<F>(&mut self, same_bucket: F)
473    where
474        F: FnMut(&mut V, &mut V) -> bool,
475    {
476        self.raw.dedup_by(same_bucket);
477    }
478
479    /// Appends an element to the back of a collection.
480    ///
481    /// See [`Vec::push`] for more details.
482    ///
483    /// [`Vec::push`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.push
484    #[inline]
485    pub fn push(&mut self, value: V) {
486        self.raw.push(value);
487    }
488
489    /// Appends an element to the back of a collection and returns its index of
490    /// type `K`.
491    ///
492    /// It acts like `{ vec.push(...); vec.last_key().unwrap() }`,
493    /// but is optimized better.
494    ///
495    /// See [`Vec::push`] for more details.
496    ///
497    /// # Example
498    ///
499    /// ```
500    /// # use derive_more::{From, Into};
501    /// # use typed_index_collections::TiVec;
502    /// #[derive(Eq, Debug, From, Into, PartialEq)]
503    /// pub struct Id(usize);
504    /// let mut vec: TiVec<Id, usize> = vec![1, 2, 4].into();
505    /// assert_eq!(vec.push_and_get_key(8), Id(3));
506    /// assert_eq!(vec.push_and_get_key(16), Id(4));
507    /// assert_eq!(vec.push_and_get_key(32), Id(5));
508    /// ```
509    ///
510    /// [`Vec::push`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.push
511    #[inline]
512    pub fn push_and_get_key(&mut self, value: V) -> K
513    where
514        K: From<usize>,
515    {
516        let key = self.next_key();
517        self.raw.push(value);
518        key
519    }
520
521    /// Removes the last element from a vector and returns it, or [`None`] if it
522    /// is empty.
523    ///
524    /// See [`Vec::pop`] for more details.
525    ///
526    /// [`Vec::pop`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.pop
527    #[inline]
528    pub fn pop(&mut self) -> Option<V> {
529        self.raw.pop()
530    }
531
532    /// Removes the last element from a vector and returns it with
533    /// its index of type `K`, or [`None`] if the vector is empty.
534    ///
535    /// See [`Vec::pop`] for more details.
536    ///
537    /// [`Vec::pop`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.pop
538    ///
539    /// # Example
540    ///
541    /// ```
542    /// # use derive_more::{From, Into};
543    /// # use typed_index_collections::TiVec;
544    /// #[derive(Eq, Debug, From, Into, PartialEq)]
545    /// pub struct Id(usize);
546    /// let mut vec: TiVec<Id, usize> = vec![1, 2, 4].into();
547    /// assert_eq!(vec.pop_key_value(), Some((Id(2), 4)));
548    /// assert_eq!(vec.pop_key_value(), Some((Id(1), 2)));
549    /// assert_eq!(vec.pop_key_value(), Some((Id(0), 1)));
550    /// assert_eq!(vec.pop_key_value(), None);
551    /// ```
552    ///
553    /// [`Vec::push`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.push
554    #[inline]
555    pub fn pop_key_value(&mut self) -> Option<(K, V)>
556    where
557        K: From<usize>,
558    {
559        self.raw.pop().map(|value| (self.raw.len().into(), value))
560    }
561
562    /// Moves all the elements of `other` into `Self`, leaving `other` empty.
563    ///
564    /// See [`Vec::append`] for more details.
565    ///
566    /// [`Vec::append`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.append
567    #[inline]
568    pub fn append(&mut self, other: &mut Self) {
569        self.raw.append(&mut other.raw);
570    }
571
572    /// Creates a draining iterator that removes the specified range in the
573    /// vector and yields the removed items.
574    ///
575    /// See [`Vec::drain`] for more details.
576    ///
577    /// [`Vec::drain`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.drain
578    #[inline]
579    pub fn drain<R>(&mut self, range: R) -> Drain<'_, V>
580    where
581        R: TiRangeBounds<K>,
582    {
583        self.raw.drain(range.into_range())
584    }
585
586    /// Creates a draining iterator that removes the specified
587    /// range in the vector and yields the current count and the removed items.
588    ///
589    /// It acts like `self.drain(range).enumerate()`,
590    /// but instead of `usize` it returns index of type `K`.
591    ///
592    /// Note that the indices started from `K::from_usize(0)`,
593    /// regardless of the range starting point.
594    ///
595    /// See [`Vec::drain`] for more details.
596    ///
597    /// # Example
598    ///
599    /// ```
600    /// # use derive_more::{From, Into};
601    /// # use typed_index_collections::{TiSlice, TiVec};
602    /// #[derive(Eq, Debug, From, Into, PartialEq)]
603    /// pub struct Id(usize);
604    /// let mut vec: TiVec<Id, usize> = vec![1, 2, 4].into();
605    /// {
606    ///     let mut iterator = vec.drain_enumerated(Id(1)..);
607    ///     assert_eq!(iterator.next(), Some((Id(0), 2)));
608    ///     assert_eq!(iterator.next(), Some((Id(1), 4)));
609    ///     assert_eq!(iterator.next(), None);
610    /// }
611    /// assert_eq!(vec.as_slice(), TiSlice::from_ref(&[1]));
612    /// ```
613    ///
614    /// [`Vec::drain`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.drain
615    #[inline]
616    pub fn drain_enumerated<R>(&mut self, range: R) -> TiEnumerated<Drain<'_, V>, K, V>
617    where
618        K: From<usize>,
619        R: TiRangeBounds<K>,
620    {
621        self.raw
622            .drain(range.into_range())
623            .enumerate()
624            .map(|(key, value)| (key.into(), value))
625    }
626
627    /// Clears the vector, removing all values.
628    ///
629    /// See [`Vec::clear`] for more details.
630    ///
631    /// [`Vec::clear`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.clear
632    #[inline]
633    pub fn clear(&mut self) {
634        self.raw.clear();
635    }
636
637    /// Returns the number of elements in the vector, also referred to
638    /// as its 'length'.
639    ///
640    /// See [`Vec::len`] for more details.
641    ///
642    /// [`Vec::len`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.len
643    #[inline]
644    #[must_use]
645    pub fn len(&self) -> usize {
646        self.raw.len()
647    }
648
649    /// Returns `true` if the vector contains no elements.
650    ///
651    /// See [`Vec::is_empty`] for more details.
652    ///
653    /// [`Vec::is_empty`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.is_empty
654    #[inline]
655    #[must_use]
656    pub fn is_empty(&self) -> bool {
657        self.raw.is_empty()
658    }
659
660    /// Splits the collection into two at the given index.
661    ///
662    /// See [`Vec::split_off`] for more details.
663    ///
664    /// [`Vec::split_off`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.split_off
665    #[inline]
666    #[must_use = "use `.truncate()` if you don't need the other half"]
667    pub fn split_off(&mut self, at: K) -> Self
668    where
669        usize: From<K>,
670    {
671        self.raw.split_off(at.into()).into()
672    }
673
674    /// Resizes the `TiVec` in-place so that `len` is equal to `new_len`.
675    ///
676    /// See [`Vec::resize_with`] for more details.
677    ///
678    /// [`Vec::resize_with`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.resize_with
679    #[inline]
680    pub fn resize_with<F>(&mut self, new_len: usize, f: F)
681    where
682        F: FnMut() -> V,
683    {
684        self.raw.resize_with(new_len, f);
685    }
686
687    /// Resizes the `TiVec` in-place so that `len` is equal to `new_len`.
688    ///
689    /// See [`Vec::resize`] for more details.
690    ///
691    /// [`Vec::resize`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.resize
692    #[inline]
693    pub fn resize(&mut self, new_len: usize, value: V)
694    where
695        V: Clone,
696    {
697        self.raw.resize(new_len, value);
698    }
699
700    /// Consumes and leaks the `Vec`, returning a mutable reference to the
701    /// contents, `&'a mut [T]`. Note that the type `T` must outlive the
702    /// chosen lifetime `'a`. If the type has only static references, or
703    /// none at all, then this may be chosen to be `'static`.
704    ///
705    /// See [`Vec::leak`] for more details.
706    ///
707    /// [`Vec::leak`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.leak
708    #[expect(clippy::must_use_candidate, reason = "not used in `Vec::leak`")]
709    #[inline]
710    pub fn leak<'a>(self) -> &'a mut TiSlice<K, V> {
711        self.raw.leak().as_mut()
712    }
713
714    /// Returns the remaining spare capacity of the vector as a slice of
715    /// `MaybeUninit<T>`.
716    ///
717    /// See [`Vec::spare_capacity_mut`] for more details.
718    ///
719    /// [`Vec::spare_capacity_mut`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.spare_capacity_mut
720    #[inline]
721    pub fn spare_capacity_mut(&mut self) -> &mut TiSlice<K, MaybeUninit<V>> {
722        self.raw.spare_capacity_mut().as_mut()
723    }
724
725    /// Clones and appends all elements in a slice to the `TiVec`.
726    ///
727    /// See [`Vec::extend_from_slice`] for more details.
728    ///
729    /// [`Vec::extend_from_slice`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.extend_from_slice
730    #[inline]
731    pub fn extend_from_slice(&mut self, other: &TiSlice<K, V>)
732    where
733        V: Clone,
734    {
735        self.raw.extend_from_slice(&other.raw);
736    }
737
738    /// Copies elements from `src` range to the end of the vector.
739    ///
740    /// See [`Vec::extend_from_within`] for more details.
741    ///
742    /// # Panics
743    ///
744    /// Panics if the starting point is greater than the end point or if
745    /// the end point is greater than the length of the vector.
746    ///
747    /// [`Vec::extend_from_within`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.extend_from_within
748    #[inline]
749    pub fn extend_from_within<R>(&mut self, src: R)
750    where
751        V: Clone,
752        R: RangeBounds<usize>,
753    {
754        self.raw.extend_from_within(src);
755    }
756
757    /// Removes consecutive repeated elements in the vector according to the
758    /// [`PartialEq`] trait implementation.
759    ///
760    /// See [`Vec::dedup`] for more details.
761    ///
762    /// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
763    /// [`Vec::dedup`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.dedup
764    #[inline]
765    pub fn dedup(&mut self)
766    where
767        V: PartialEq,
768    {
769        self.raw.dedup();
770    }
771
772    /// Creates a splicing iterator that replaces the specified range in the
773    /// vector with the given `replace_with` iterator and yields the removed
774    /// items. `replace_with` does not need to be the same length as
775    /// `range`.
776    ///
777    /// See [`Vec::splice`] for more details.
778    ///
779    /// [`Vec::splice`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.splice
780    #[inline]
781    pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
782    where
783        R: TiRangeBounds<K>,
784        I: IntoIterator<Item = V>,
785    {
786        self.raw.splice(range.into_range(), replace_with)
787    }
788
789    /// Converts the vector into iterator over all key-value pairs
790    /// with `K` used for iteration indices.
791    ///
792    /// It acts like `self.into_iter().enumerate()`,
793    /// but use `K` instead of `usize` for iteration indices.
794    ///
795    /// # Example
796    ///
797    /// ```
798    /// # use derive_more::{From, Into};
799    /// # use typed_index_collections::TiVec;
800    /// #[derive(Eq, Debug, From, Into, PartialEq)]
801    /// pub struct Id(usize);
802    /// let vec: TiVec<Id, usize> = vec![1, 2, 4].into();
803    /// let mut iterator = vec.into_iter_enumerated();
804    /// assert_eq!(iterator.next(), Some((Id(0), 1)));
805    /// assert_eq!(iterator.next(), Some((Id(1), 2)));
806    /// assert_eq!(iterator.next(), Some((Id(2), 4)));
807    /// assert_eq!(iterator.next(), None);
808    /// ```
809    #[inline]
810    pub fn into_iter_enumerated(self) -> TiEnumerated<vec::IntoIter<V>, K, V>
811    where
812        K: From<usize>,
813    {
814        self.raw
815            .into_iter()
816            .enumerate()
817            .map(|(key, value)| (key.into(), value))
818    }
819}
820
821impl<K, V> fmt::Debug for TiVec<K, V>
822where
823    K: fmt::Debug + From<usize>,
824    V: fmt::Debug,
825{
826    #[allow(clippy::allow_attributes, reason = "rust-lang/rust#130021")]
827    #[allow(
828        clippy::missing_inline_in_public_items,
829        reason = "use default inlining behavior"
830    )]
831    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
832        f.debug_map().entries(self.iter_enumerated()).finish()
833    }
834}
835
836impl<K, V> AsRef<Self> for TiVec<K, V> {
837    #[inline]
838    fn as_ref(&self) -> &Self {
839        self
840    }
841}
842
843impl<K, V> AsMut<Self> for TiVec<K, V> {
844    #[inline]
845    fn as_mut(&mut self) -> &mut Self {
846        self
847    }
848}
849
850impl<K, V> AsRef<TiSlice<K, V>> for TiVec<K, V> {
851    #[inline]
852    fn as_ref(&self) -> &TiSlice<K, V> {
853        self
854    }
855}
856
857impl<K, V> AsMut<TiSlice<K, V>> for TiVec<K, V> {
858    #[inline]
859    fn as_mut(&mut self) -> &mut TiSlice<K, V> {
860        self
861    }
862}
863
864impl<K, V> AsRef<Vec<V>> for TiVec<K, V> {
865    #[inline]
866    fn as_ref(&self) -> &Vec<V> {
867        &self.raw
868    }
869}
870
871impl<K, V> AsMut<Vec<V>> for TiVec<K, V> {
872    #[inline]
873    fn as_mut(&mut self) -> &mut Vec<V> {
874        &mut self.raw
875    }
876}
877
878impl<K, V> AsRef<[V]> for TiVec<K, V> {
879    #[inline]
880    fn as_ref(&self) -> &[V] {
881        &self.raw
882    }
883}
884
885impl<K, V> AsMut<[V]> for TiVec<K, V> {
886    #[inline]
887    fn as_mut(&mut self) -> &mut [V] {
888        &mut self.raw
889    }
890}
891
892impl<K, V> AsRef<TiVec<K, V>> for Vec<V> {
893    #[inline]
894    fn as_ref(&self) -> &TiVec<K, V> {
895        TiVec::from_ref(self)
896    }
897}
898
899impl<K, V> AsMut<TiVec<K, V>> for Vec<V> {
900    #[inline]
901    fn as_mut(&mut self) -> &mut TiVec<K, V> {
902        TiVec::from_mut(self)
903    }
904}
905
906impl<K, V> Borrow<TiSlice<K, V>> for TiVec<K, V> {
907    #[inline]
908    fn borrow(&self) -> &TiSlice<K, V> {
909        self.as_slice()
910    }
911}
912
913impl<K, V> BorrowMut<TiSlice<K, V>> for TiVec<K, V> {
914    #[inline]
915    fn borrow_mut(&mut self) -> &mut TiSlice<K, V> {
916        self.as_mut_slice()
917    }
918}
919
920impl<K, V> Deref for TiVec<K, V> {
921    type Target = TiSlice<K, V>;
922
923    #[inline]
924    fn deref(&self) -> &TiSlice<K, V> {
925        Self::Target::from_ref(&self.raw)
926    }
927}
928
929impl<K, V> DerefMut for TiVec<K, V> {
930    #[inline]
931    fn deref_mut(&mut self) -> &mut TiSlice<K, V> {
932        Self::Target::from_mut(&mut self.raw)
933    }
934}
935
936impl<K, V> From<Vec<V>> for TiVec<K, V> {
937    #[inline]
938    fn from(vec: Vec<V>) -> Self {
939        Self {
940            raw: vec,
941            _marker: PhantomData,
942        }
943    }
944}
945
946impl<K, V> From<TiVec<K, V>> for Vec<V> {
947    #[inline]
948    fn from(vec: TiVec<K, V>) -> Self {
949        vec.raw
950    }
951}
952
953impl<K, V> From<&TiSlice<K, V>> for TiVec<K, V>
954where
955    V: Clone,
956{
957    #[inline]
958    fn from(slice: &TiSlice<K, V>) -> Self {
959        slice.to_vec()
960    }
961}
962
963impl<K, V> From<&mut TiSlice<K, V>> for TiVec<K, V>
964where
965    V: Clone,
966{
967    #[inline]
968    fn from(slice: &mut TiSlice<K, V>) -> Self {
969        slice.to_vec()
970    }
971}
972
973impl<K, V> From<Cow<'_, TiSlice<K, V>>> for TiVec<K, V>
974where
975    V: Clone,
976{
977    #[inline]
978    fn from(slice: Cow<'_, TiSlice<K, V>>) -> Self {
979        slice.into_owned()
980    }
981}
982
983impl<K, V> From<TiVec<K, V>> for Cow<'_, TiSlice<K, V>>
984where
985    V: Clone,
986{
987    #[inline]
988    fn from(vec: TiVec<K, V>) -> Self {
989        Cow::Owned(vec)
990    }
991}
992
993impl<K> From<&str> for TiVec<K, u8> {
994    #[inline]
995    fn from(s: &str) -> Self {
996        s.as_bytes().to_vec().into()
997    }
998}
999
1000impl<K> From<String> for TiVec<K, u8> {
1001    #[inline]
1002    fn from(s: String) -> Self {
1003        s.into_bytes().into()
1004    }
1005}
1006
1007impl<K> From<CString> for TiVec<K, u8> {
1008    #[inline]
1009    fn from(s: CString) -> Self {
1010        s.into_bytes().into()
1011    }
1012}
1013
1014impl<K, V> Clone for TiVec<K, V>
1015where
1016    V: Clone,
1017{
1018    #[inline]
1019    fn clone(&self) -> Self {
1020        self.raw.clone().into()
1021    }
1022}
1023
1024impl<K, V> Eq for TiVec<K, V> where V: Eq {}
1025
1026impl<K, A, B> PartialEq<TiVec<K, B>> for TiVec<K, A>
1027where
1028    A: PartialEq<B>,
1029{
1030    #[inline]
1031    fn eq(&self, other: &TiVec<K, B>) -> bool {
1032        self.raw == other.raw
1033    }
1034}
1035
1036impl<K, A, B> PartialEq<TiSlice<K, B>> for TiVec<K, A>
1037where
1038    A: PartialEq<B>,
1039{
1040    #[inline]
1041    fn eq(&self, other: &TiSlice<K, B>) -> bool {
1042        *self.raw == other.raw
1043    }
1044}
1045
1046impl<K, A, B> PartialEq<TiVec<K, B>> for TiSlice<K, A>
1047where
1048    A: PartialEq<B>,
1049{
1050    #[inline]
1051    fn eq(&self, other: &TiVec<K, B>) -> bool {
1052        self.raw == *other.raw
1053    }
1054}
1055
1056impl<'a, K, A, B> PartialEq<&'a TiSlice<K, B>> for TiVec<K, A>
1057where
1058    A: PartialEq<B>,
1059{
1060    #[inline]
1061    fn eq(&self, other: &&'a TiSlice<K, B>) -> bool {
1062        *self.raw == other.raw
1063    }
1064}
1065
1066impl<K, A, B> PartialEq<TiVec<K, B>> for &TiSlice<K, A>
1067where
1068    A: PartialEq<B>,
1069{
1070    #[inline]
1071    fn eq(&self, other: &TiVec<K, B>) -> bool {
1072        self.raw == *other.raw
1073    }
1074}
1075
1076impl<'a, K, A, B> PartialEq<&'a mut TiSlice<K, B>> for TiVec<K, A>
1077where
1078    A: PartialEq<B>,
1079{
1080    #[inline]
1081    fn eq(&self, other: &&'a mut TiSlice<K, B>) -> bool {
1082        *self.raw == other.raw
1083    }
1084}
1085
1086impl<K, A, B> PartialEq<TiVec<K, B>> for &mut TiSlice<K, A>
1087where
1088    A: PartialEq<B>,
1089{
1090    #[inline]
1091    fn eq(&self, other: &TiVec<K, B>) -> bool {
1092        self.raw == *other.raw
1093    }
1094}
1095
1096impl<K, V> Ord for TiVec<K, V>
1097where
1098    V: Ord,
1099{
1100    #[inline]
1101    fn cmp(&self, other: &Self) -> Ordering {
1102        self.raw.cmp(&other.raw)
1103    }
1104}
1105
1106impl<K, V> PartialOrd<Self> for TiVec<K, V>
1107where
1108    V: PartialOrd<V>,
1109{
1110    #[inline]
1111    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1112        self.raw.partial_cmp(&other.raw)
1113    }
1114}
1115
1116impl<K, V> Hash for TiVec<K, V>
1117where
1118    V: Hash,
1119{
1120    #[inline]
1121    fn hash<H: Hasher>(&self, state: &mut H) {
1122        self.raw.hash(state);
1123    }
1124}
1125
1126impl<K, V> Default for TiVec<K, V> {
1127    #[inline]
1128    fn default() -> Self {
1129        Vec::default().into()
1130    }
1131}
1132
1133impl<I, K, V> Index<I> for TiVec<K, V>
1134where
1135    I: TiSliceIndex<K, V>,
1136{
1137    type Output = I::Output;
1138
1139    #[inline]
1140    fn index(&self, index: I) -> &Self::Output {
1141        index.index(self)
1142    }
1143}
1144
1145impl<I, K, V> IndexMut<I> for TiVec<K, V>
1146where
1147    I: TiSliceIndex<K, V>,
1148{
1149    #[inline]
1150    fn index_mut(&mut self, index: I) -> &mut Self::Output {
1151        index.index_mut(self)
1152    }
1153}
1154
1155impl<K, V> Extend<V> for TiVec<K, V> {
1156    #[inline]
1157    fn extend<I: IntoIterator<Item = V>>(&mut self, iter: I) {
1158        self.raw.extend(iter);
1159    }
1160}
1161
1162impl<'a, K, V: 'a + Copy> Extend<&'a V> for TiVec<K, V> {
1163    #[inline]
1164    fn extend<I: IntoIterator<Item = &'a V>>(&mut self, iter: I) {
1165        self.raw.extend(iter);
1166    }
1167}
1168
1169impl<K, V> FromIterator<V> for TiVec<K, V> {
1170    #[inline]
1171    fn from_iter<I: IntoIterator<Item = V>>(iter: I) -> Self {
1172        Self {
1173            raw: Vec::from_iter(iter),
1174            _marker: PhantomData,
1175        }
1176    }
1177}
1178
1179impl<K, V> IntoIterator for TiVec<K, V> {
1180    type Item = V;
1181    type IntoIter = vec::IntoIter<V>;
1182
1183    #[inline]
1184    fn into_iter(self) -> vec::IntoIter<V> {
1185        self.raw.into_iter()
1186    }
1187}
1188
1189impl<'a, K, V> IntoIterator for &'a TiVec<K, V> {
1190    type Item = &'a V;
1191    type IntoIter = slice::Iter<'a, V>;
1192
1193    #[inline]
1194    fn into_iter(self) -> slice::Iter<'a, V> {
1195        self.raw.iter()
1196    }
1197}
1198
1199impl<'a, K, V> IntoIterator for &'a mut TiVec<K, V> {
1200    type Item = &'a mut V;
1201    type IntoIter = slice::IterMut<'a, V>;
1202
1203    #[inline]
1204    fn into_iter(self) -> slice::IterMut<'a, V> {
1205        self.raw.iter_mut()
1206    }
1207}
1208
1209/// Write is implemented for `Vec<u8>` by appending to the vector.
1210/// The vector will grow as needed.
1211#[cfg(feature = "std")]
1212#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1213impl<K> Write for TiVec<K, u8> {
1214    #[inline]
1215    fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
1216        self.raw.write(buf)
1217    }
1218
1219    #[inline]
1220    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> IoResult<usize> {
1221        self.raw.write_vectored(bufs)
1222    }
1223
1224    #[inline]
1225    fn write_all(&mut self, buf: &[u8]) -> IoResult<()> {
1226        self.raw.write_all(buf)
1227    }
1228
1229    #[inline]
1230    fn flush(&mut self) -> IoResult<()> {
1231        self.raw.flush()
1232    }
1233}
1234
1235#[cfg(feature = "serde")]
1236#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1237impl<K, V> Serialize for TiVec<K, V>
1238where
1239    V: Serialize,
1240{
1241    #[inline]
1242    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1243    where
1244        S: Serializer,
1245    {
1246        self.raw.as_slice().serialize(serializer)
1247    }
1248}
1249
1250#[cfg(feature = "serde")]
1251#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1252impl<'de, K, V> Deserialize<'de> for TiVec<K, V>
1253where
1254    V: Deserialize<'de>,
1255{
1256    #[inline]
1257    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1258    where
1259        D: Deserializer<'de>,
1260    {
1261        Vec::deserialize(deserializer).map(Into::into)
1262    }
1263}
1264
1265#[cfg(feature = "bincode")]
1266#[cfg_attr(docsrs, doc(cfg(feature = "bincode")))]
1267impl<K, V> Encode for TiVec<K, V>
1268where
1269    V: Encode,
1270{
1271    #[inline]
1272    fn encode<E>(&self, encoder: &mut E) -> Result<(), EncodeError>
1273    where
1274        E: Encoder,
1275    {
1276        self.raw.encode(encoder)
1277    }
1278}
1279
1280#[cfg(feature = "bincode")]
1281#[cfg_attr(docsrs, doc(cfg(feature = "bincode")))]
1282impl<K, V, Context> Decode<Context> for TiVec<K, V>
1283where
1284    V: Decode<Context>,
1285{
1286    #[inline]
1287    fn decode<D>(decoder: &mut D) -> Result<Self, DecodeError>
1288    where
1289        D: Decoder<Context = Context>,
1290    {
1291        Vec::decode(decoder).map(Into::into)
1292    }
1293}
1294
1295#[cfg(feature = "bincode")]
1296#[cfg_attr(docsrs, doc(cfg(feature = "bincode")))]
1297impl<'de, K, V, Context> BorrowDecode<'de, Context> for TiVec<K, V>
1298where
1299    V: BorrowDecode<'de, Context>,
1300{
1301    #[inline]
1302    fn borrow_decode<D>(decoder: &mut D) -> Result<Self, DecodeError>
1303    where
1304        D: BorrowDecoder<'de, Context = Context>,
1305    {
1306        Vec::borrow_decode(decoder).map(Into::into)
1307    }
1308}
1309
1310#[expect(
1311    dead_code,
1312    unused_imports,
1313    unused_mut,
1314    clippy::into_iter_on_ref,
1315    clippy::op_ref,
1316    clippy::too_many_lines,
1317    clippy::undocumented_unsafe_blocks,
1318    clippy::unwrap_used,
1319    reason = "okay in tests"
1320)]
1321#[cfg(test)]
1322mod test {
1323    use alloc::borrow::{Cow, ToOwned};
1324    use alloc::boxed::Box;
1325    use alloc::ffi::CString;
1326    use alloc::string::ToString;
1327    use alloc::vec::Vec;
1328    use core::borrow::{Borrow, BorrowMut};
1329    use core::hash::{Hash, Hasher};
1330    use core::ops::Bound;
1331    #[cfg(feature = "std")]
1332    use std::hash::DefaultHasher;
1333    #[cfg(feature = "std")]
1334    use std::io::{IoSlice, Write};
1335
1336    use crate::test_util::{AsSliceAndCapacity, Id};
1337    use crate::{TiSlice, TiVec};
1338
1339    #[test]
1340    fn test_vec_read_api_compatibility() {
1341        assert_eq!(
1342            TiVec::<Id, u32>::new().as_slice_and_capacity(),
1343            Vec::<u32>::new().as_slice_and_capacity(),
1344        );
1345        for c in [0, 1, 2, 4] {
1346            assert_eq!(
1347                TiVec::<Id, u32>::with_capacity(c).as_slice_and_capacity(),
1348                Vec::<u32>::with_capacity(c).as_slice_and_capacity(),
1349            );
1350        }
1351
1352        for v in [
1353            &[0_u32; 0][..],
1354            &[1],
1355            &[1, 1234],
1356            &[1, 2, 4],
1357            &[1, 5, 3, 2],
1358            &[1, 1, 9, 2, 4, 1, 12345, 12],
1359        ] {
1360            let cv = (v.to_vec(), TiVec::<Id, _>::from(v.to_vec()));
1361            let mut cv = (&cv.0, &cv.1);
1362
1363            let mut mv = (v.to_vec(), TiVec::<Id, _>::from(v.to_vec()));
1364            let mut mv = (&mut mv.0, &mut mv.1);
1365
1366            assert_eq_api!(cv, v => AsRef::<[_]>::as_ref(v));
1367            assert_eq_api!(mv, v => AsMut::<[_]>::as_mut(v));
1368            assert_eq_api!(cv, v => AsRef::<Vec<_>>::as_ref(v));
1369            assert_eq_api!(mv, v => AsMut::<Vec<_>>::as_mut(v));
1370            assert_eq_api!(cv, v => AsRef::<TiVec<_, _>>::as_ref(v));
1371            assert_eq_api!(mv, v => AsMut::<TiVec<_, _>>::as_mut(v));
1372            assert_eq!(
1373                AsRef::<[_]>::as_ref(cv.0),
1374                AsRef::<[_]>::as_ref(AsRef::<TiSlice<_, _>>::as_ref(cv.1))
1375            );
1376            assert_eq!(
1377                AsMut::<[_]>::as_mut(mv.0),
1378                AsMut::<[_]>::as_mut(AsMut::<TiSlice<_, _>>::as_mut(mv.1))
1379            );
1380            assert_eq!(
1381                Borrow::<[_]>::borrow(cv.0),
1382                AsRef::<[_]>::as_ref(Borrow::<TiSlice<_, _>>::borrow(cv.1))
1383            );
1384            assert_eq!(
1385                BorrowMut::<[_]>::borrow_mut(mv.0),
1386                AsMut::<[_]>::as_mut(BorrowMut::<TiSlice<_, _>>::borrow_mut(mv.1))
1387            );
1388
1389            assert_eq_api!(cv, v => v.len());
1390            assert_eq_api!(cv, v => v.is_empty());
1391            assert_eq_api!(cv, v => v.capacity());
1392            assert_eq_api!(cv, v => v.as_slice().into_std());
1393            assert_eq_api!(mv, v => v.as_mut_slice().into_std());
1394            assert_eq_api!(cv, v => TheVec::from(v.as_slice()).into_std());
1395            assert_eq_api!(mv, v => TheVec::from(v.as_mut_slice()).into_std());
1396            assert_eq_api!(cv, v => TheVec::from(Cow::Borrowed(v.as_slice())).into_std());
1397            assert_eq_api!(mv, v => Cow::from(v.clone()).into_std());
1398
1399            if !v.is_empty() {
1400                assert_ne!(cv.0.as_ptr(), cv.1.as_ptr());
1401                assert_ne!(cv.0.as_ptr_range(), cv.1.as_ptr_range());
1402                assert_ne!(mv.0.as_mut_ptr(), mv.1.as_mut_ptr());
1403                assert_ne!(mv.0.as_mut_ptr_range(), mv.1.as_mut_ptr_range());
1404            }
1405
1406            assert_eq_api!(cv, v => *v == TheVec::<u32>::default());
1407            assert_eq_api!(cv, v => v == v.as_slice());
1408            assert_eq_api!(cv, v => v.as_slice() == v);
1409            assert_eq_api!(cv, v => v == &v.as_slice());
1410            assert_eq_api!(cv, v => &v.as_slice() == v);
1411            assert_eq_api!(mv, v => v == &(&mut [1_u32, 1234][..]).into_tic());
1412            assert_eq_api!(mv, v => &(&mut [1_u32, 1234][..]).into_tic() == v);
1413            assert_eq_api!(cv, v => v.cmp(&alloc::vec![1, 1234].into_tic()));
1414            assert_eq_api!(cv, v => v.partial_cmp(&alloc::vec![1, 1234].into_tic()));
1415
1416            for i in 0..v.len() {
1417                assert_eq_api!(cv, v => v[i.into_tic()]);
1418                assert_eq_api!(mv, v => v[i.into_tic()] = v[i.into_tic()]);
1419            }
1420
1421            unsafe {
1422                assert_eq_api!(cv, v => {
1423                    let mut v = core::mem::ManuallyDrop::new(v.clone());
1424                    TheVec::from_raw_parts(v.as_mut_ptr(), v.len(), v.capacity()).into_std()
1425                });
1426            }
1427        }
1428    }
1429
1430    #[test]
1431    fn test_vec_write_api_compatibility() {
1432        for v in [
1433            &[0_u32; 0][..],
1434            &[1],
1435            &[1, 1234],
1436            &[1, 2, 4],
1437            &[1, 5, 3, 2],
1438            &[1, 1, 9, 2, 4, 1, 12345, 12],
1439        ] {
1440            let mut mv = (v.to_vec(), TiVec::<Id, _>::from(v.to_vec()));
1441            let mut mv = (&mut mv.0, &mut mv.1);
1442
1443            let restore = |mv: &mut (&mut Vec<u32>, &mut TiVec<Id, u32>)| {
1444                *mv.0 = v.to_vec();
1445                *mv.1 = TiVec::from(v.to_vec());
1446            };
1447
1448            restore(&mut mv);
1449            assert_eq_api!(mv, v => v.try_reserve(usize::MAX));
1450            restore(&mut mv);
1451            assert_eq_api!(mv, v => v.try_reserve_exact(usize::MAX));
1452
1453            for i in 0..8 {
1454                restore(&mut mv);
1455                assert_eq_api!(mv, v => v.resize(i, 123));
1456                restore(&mut mv);
1457                assert_eq_api!(mv, v => { let mut a = 1; v.resize_with(i, || { a *= 2; a }) });
1458                restore(&mut mv);
1459                assert_eq_api!(mv, v => v.reserve(i));
1460                assert_eq_api!(mv, v => v.spare_capacity_mut().len());
1461                restore(&mut mv);
1462                assert_eq_api!(mv, v => v.try_reserve(i));
1463                restore(&mut mv);
1464                assert_eq_api!(mv, v => v.reserve_exact(i));
1465                restore(&mut mv);
1466                assert_eq_api!(mv, v => v.try_reserve_exact(i));
1467                restore(&mut mv);
1468                assert_eq_api!(mv, v => v.reserve_exact(i));
1469                assert_eq_api!(mv, v => v.shrink_to_fit());
1470                restore(&mut mv);
1471                assert_eq_api!(mv, v => v.reserve_exact(i * 2));
1472                assert_eq_api!(mv, v => v.shrink_to(i));
1473                restore(&mut mv);
1474                assert_eq_api!(mv, v => v.truncate(i));
1475            }
1476
1477            let l1: Vec<_> = mv.0.clone();
1478            let l1c = l1.capacity();
1479            let l1 = l1.leak();
1480            let l2: TiVec<_, _> = mv.1.clone();
1481            let l2c = l2.capacity();
1482            let l2 = l2.leak();
1483            assert_eq!(l1, &l2.raw);
1484            drop(unsafe { Vec::from_raw_parts(l1.as_mut_ptr(), l1.len(), l1c) });
1485            drop(unsafe { TiVec::<Id, _>::from_raw_parts(l2.as_mut_ptr(), l2.len(), l2c) });
1486
1487            restore(&mut mv);
1488            assert_eq_api!(mv, v => (&*v).into_iter().copied().collect::<Vec<_>>());
1489            assert_eq_api!(mv, v => v.iter_mut().collect::<Vec<_>>());
1490            assert_eq_api!(mv, v => v.clone().into_iter().collect::<Vec<_>>());
1491
1492            restore(&mut mv);
1493            assert_eq_api!(mv, v => v.pop());
1494            assert_eq_api!(mv, v => v.push(123));
1495            assert_eq_api!(mv, v => v.pop());
1496            assert_eq_api!(mv, v => v.append(&mut v.clone()));
1497            restore(&mut mv);
1498            assert_eq_api!(mv, v => v.extend(v.clone().as_slice()));
1499            restore(&mut mv);
1500            assert_eq_api!(mv, v => v.extend(v.clone().iter().copied()));
1501            restore(&mut mv);
1502            assert_eq_api!(mv, v => v.extend_from_slice(&v.clone()));
1503            restore(&mut mv);
1504            assert_eq_api!(mv, v => v.into_iter().collect::<TheVec<_>>().into_std());
1505
1506            restore(&mut mv);
1507            assert_eq_api!(mv, v => v.retain(|value| value % 3 == 0 || value % 4 == 0));
1508
1509            restore(&mut mv);
1510            assert_eq_api!(mv, v => v.retain_mut(|value| {
1511                *value += 1;
1512                *value % 3 == 0 || *value % 4 == 0
1513            }));
1514
1515            restore(&mut mv);
1516            assert_eq_api!(mv, v => v.dedup());
1517
1518            restore(&mut mv);
1519            assert_eq_api!(mv, v => v.dedup_by(|lhs, rhs| lhs < rhs));
1520
1521            restore(&mut mv);
1522            assert_eq_api!(mv, v => v.dedup_by_key(|value| *value % 3));
1523
1524            for i in 0..v.len() {
1525                restore(&mut mv);
1526                assert_eq_api!(mv, v => v.swap_remove(i.into_tic()));
1527                restore(&mut mv);
1528                assert_eq_api!(mv, v => v.insert(i.into_tic(), 123));
1529                restore(&mut mv);
1530                assert_eq_api!(mv, v => v.remove(i.into_tic()));
1531                restore(&mut mv);
1532                unsafe { assert_eq_api!(mv, v => v.set_len(i)) };
1533                restore(&mut mv);
1534                assert_eq_api!(mv, v => v.split_off(i.into_tic()).into_std());
1535            }
1536
1537            for a in 0..v.len() {
1538                for b in a..v.len() {
1539                    restore(&mut mv);
1540                    assert_eq_api!(mv, v => v.drain((a..b).into_tic()).collect::<Vec<_>>());
1541                    restore(&mut mv);
1542                    assert_eq_api!(mv, v => v.extend_from_within(a..b));
1543                    restore(&mut mv);
1544                    assert_eq_api!(
1545                        mv, v => v.splice((a..b).into_tic(), [1, 2, 3]).collect::<Vec<_>>()
1546                    );
1547                }
1548            }
1549            restore(&mut mv);
1550            assert_eq_api!(mv, v => v.splice(.., [1, 2, 3]).collect::<Vec<_>>());
1551
1552            restore(&mut mv);
1553            assert_eq_api!(mv, v => v.clear());
1554        }
1555    }
1556
1557    #[cfg(feature = "std")]
1558    #[test]
1559    fn test_vec_hash_compatibility() {
1560        for v in [
1561            &[0_u32; 0][..],
1562            &[1],
1563            &[1, 1234],
1564            &[1, 2, 4],
1565            &[1, 5, 3, 2],
1566            &[1, 1, 9, 2, 4, 1, 12345, 12],
1567        ] {
1568            let cv = (v.to_vec(), TiVec::<Id, _>::from(v.to_vec()));
1569            let mut cv = (&cv.0, &cv.1);
1570            assert_eq_api!(cv, v => {
1571                let mut hasher = DefaultHasher::new();
1572                v.hash(&mut hasher);
1573                hasher.finish()
1574            });
1575        }
1576    }
1577
1578    #[test]
1579    fn test_u8_vec_api_compatibility() {
1580        assert_eq!(
1581            Vec::from(TiVec::<Id, u8>::from("abc")),
1582            Vec::<u8>::from("abc"),
1583        );
1584        assert_eq!(
1585            Vec::from(TiVec::<Id, u8>::from("abc".to_owned())),
1586            Vec::<u8>::from("abc".to_owned()),
1587        );
1588        assert_eq!(
1589            Vec::from(TiVec::<Id, u8>::from(CString::new("abc").unwrap())),
1590            Vec::<u8>::from(CString::new("abc").unwrap()),
1591        );
1592
1593        for v in [&b"abc"[..], b"aBc", b"ABC", b"abd", b"a\x80\x81b"] {
1594            let cv = (v.to_vec(), TiVec::<Id, _>::from(v.to_vec()));
1595            let mut cv = (&cv.0, &cv.1);
1596
1597            assert_eq_api!(cv, v => TheVec::from(v.as_slice()).into_std());
1598        }
1599    }
1600
1601    #[test]
1602    fn test_vec_debug() {
1603        let s0: TiVec<Id, u32> = TiVec::from(alloc::vec![]);
1604        let s1: TiVec<Id, u32> = TiVec::from(alloc::vec![12]);
1605        let s2: TiVec<Id, u32> = TiVec::from(alloc::vec![23, 34]);
1606        assert_eq!(&alloc::format!("{s0:?}"), "{}");
1607        assert_eq!(&alloc::format!("{s1:?}"), "{Id(0): 12}");
1608        assert_eq!(&alloc::format!("{s2:?}"), "{Id(0): 23, Id(1): 34}");
1609    }
1610
1611    #[cfg(feature = "std")]
1612    #[test]
1613    fn test_vec_write() {
1614        let mut mv = (Vec::<u8>::new(), TiVec::<Id, u8>::new());
1615        let mut mv = (&mut mv.0, &mut mv.1);
1616
1617        assert_eq_api!(mv, v => v.write(&[1, 2, 3]).unwrap());
1618        assert_eq_api!(mv, v => v.write_vectored(
1619            &[IoSlice::new(&[1, 2, 3]), IoSlice::new(&[4, 5])]
1620        ).unwrap());
1621        assert_eq_api!(mv, v => v.write_all(&[1, 2, 3]).unwrap());
1622        assert_eq_api!(mv, v => v.flush().unwrap());
1623    }
1624
1625    #[cfg(feature = "serde")]
1626    #[test]
1627    fn test_vec_serialize() {
1628        let s0: TiVec<Id, u32> = TiVec::from(alloc::vec![]);
1629        let s1: TiVec<Id, u32> = TiVec::from(alloc::vec![12]);
1630        let s2: TiVec<Id, u32> = TiVec::from(alloc::vec![23, 34]);
1631        assert_eq!(&serde_json::to_string(&s0).unwrap(), "[]");
1632        assert_eq!(&serde_json::to_string(&s1).unwrap(), "[12]");
1633        assert_eq!(&serde_json::to_string(&s2).unwrap(), "[23,34]");
1634    }
1635
1636    #[cfg(feature = "serde")]
1637    #[test]
1638    fn test_vec_deserialize() {
1639        let s0: TiVec<Id, u32> = serde_json::from_str("[]").unwrap();
1640        let s1: TiVec<Id, u32> = serde_json::from_str("[12]").unwrap();
1641        let s2: TiVec<Id, u32> = serde_json::from_str("[23, 34]").unwrap();
1642        assert_eq!(s0.as_slice().raw, [0; 0][..]);
1643        assert_eq!(s1.as_slice().raw, [12][..]);
1644        assert_eq!(s2.as_slice().raw, [23, 34][..]);
1645    }
1646
1647    #[cfg(feature = "bincode")]
1648    #[test]
1649    fn test_vec_encode() {
1650        let config = bincode::config::standard();
1651        let s0: TiVec<Id, u32> = TiVec::from(alloc::vec![]);
1652        let s1: TiVec<Id, u32> = TiVec::from(alloc::vec![12]);
1653        let s2: TiVec<Id, u32> = TiVec::from(alloc::vec![23, 34]);
1654        let s3: TiVec<Id, u32> = TiVec::from(alloc::vec![0x1234_5678, 0x2345_6789]);
1655        assert_eq!(&bincode::encode_to_vec(s0, config).unwrap(), &[0]);
1656        assert_eq!(&bincode::encode_to_vec(s1, config).unwrap(), &[1, 12]);
1657        assert_eq!(&bincode::encode_to_vec(s2, config).unwrap(), &[2, 23, 34]);
1658        assert_eq!(
1659            &bincode::encode_to_vec(s3, config).unwrap(),
1660            &[2, 252, 0x78, 0x56, 0x34, 0x12, 252, 0x89, 0x67, 0x45, 0x23]
1661        );
1662    }
1663
1664    #[cfg(feature = "bincode")]
1665    #[test]
1666    fn test_vec_decode() {
1667        fn decode_whole(bytes: &[u8]) -> TiVec<Id, u32> {
1668            let config = bincode::config::standard();
1669            let (decoded, len) = bincode::decode_from_slice(bytes, config).unwrap();
1670            assert_eq!(len, bytes.len());
1671            decoded
1672        }
1673
1674        let s0: TiVec<Id, u32> = decode_whole(&[0]);
1675        let s1: TiVec<Id, u32> = decode_whole(&[1, 12]);
1676        let s2: TiVec<Id, u32> = decode_whole(&[2, 23, 34]);
1677        let s3: TiVec<Id, u32> =
1678            decode_whole(&[2, 252, 0x78, 0x56, 0x34, 0x12, 252, 0x89, 0x67, 0x45, 0x23]);
1679        assert_eq!(s0.as_slice().raw, [0; 0][..]);
1680        assert_eq!(s1.as_slice().raw, [12][..]);
1681        assert_eq!(s2.as_slice().raw, [23, 34][..]);
1682        assert_eq!(s3.as_slice().raw, [0x1234_5678, 0x2345_6789][..]);
1683    }
1684
1685    #[cfg(feature = "bincode")]
1686    #[test]
1687    fn test_boxed_slice_borrow_decode() {
1688        fn decode_whole(bytes: &[u8]) -> TiVec<Id, &str> {
1689            let config = bincode::config::standard();
1690            let (decoded, len) = bincode::borrow_decode_from_slice(bytes, config).unwrap();
1691            assert_eq!(len, bytes.len());
1692            decoded
1693        }
1694
1695        let s0: TiVec<Id, &str> = decode_whole(&[0]);
1696        let s1: TiVec<Id, &str> = decode_whole(&[1, 1, b'a']);
1697        let s2: TiVec<Id, &str> = decode_whole(&[2, 2, b'b', b'c', 3, b'd', b'e', b'f']);
1698        assert_eq!(s0.as_slice().raw, [""; 0][..]);
1699        assert_eq!(s1.as_slice().raw, ["a"][..]);
1700        assert_eq!(s2.as_slice().raw, ["bc", "def"][..]);
1701    }
1702}