tinyvec/
slicevec.rs

1#![allow(unused_variables)]
2#![allow(missing_docs)]
3
4use super::*;
5
6/// A slice-backed vector-like data structure.
7///
8/// This is a very similar concept to `ArrayVec`, but instead
9/// of the backing memory being an owned array, the backing
10/// memory is a unique-borrowed slice. You can thus create
11/// one of these structures "around" some slice that you're
12/// working with to make it easier to manipulate.
13///
14/// * Has a fixed capacity (the initial slice size).
15/// * Has a variable length.
16pub struct SliceVec<'s, T> {
17  data: &'s mut [T],
18  len: usize,
19}
20
21impl<'s, T> Default for SliceVec<'s, T> {
22  #[inline(always)]
23  fn default() -> Self {
24    Self { data: &mut [], len: 0 }
25  }
26}
27
28impl<'s, T> Deref for SliceVec<'s, T> {
29  type Target = [T];
30  #[inline(always)]
31  fn deref(&self) -> &Self::Target {
32    &self.data[..self.len]
33  }
34}
35
36impl<'s, T> DerefMut for SliceVec<'s, T> {
37  #[inline(always)]
38  fn deref_mut(&mut self) -> &mut Self::Target {
39    &mut self.data[..self.len]
40  }
41}
42
43impl<'s, T, I> Index<I> for SliceVec<'s, T>
44where
45  I: SliceIndex<[T]>,
46{
47  type Output = <I as SliceIndex<[T]>>::Output;
48  #[inline(always)]
49  fn index(&self, index: I) -> &Self::Output {
50    &self.deref()[index]
51  }
52}
53
54impl<'s, T, I> IndexMut<I> for SliceVec<'s, T>
55where
56  I: SliceIndex<[T]>,
57{
58  #[inline(always)]
59  fn index_mut(&mut self, index: I) -> &mut Self::Output {
60    &mut self.deref_mut()[index]
61  }
62}
63
64impl<'s, T> SliceVec<'s, T> {
65  #[inline]
66  pub fn append(&mut self, other: &mut Self)
67  where
68    T: Default,
69  {
70    for item in other.drain(..) {
71      self.push(item)
72    }
73  }
74
75  /// A `*mut` pointer to the backing slice.
76  ///
77  /// ## Safety
78  ///
79  /// This pointer has provenance over the _entire_ backing slice.
80  #[inline(always)]
81  #[must_use]
82  pub fn as_mut_ptr(&mut self) -> *mut T {
83    self.data.as_mut_ptr()
84  }
85
86  /// Performs a `deref_mut`, into unique slice form.
87  #[inline(always)]
88  #[must_use]
89  pub fn as_mut_slice(&mut self) -> &mut [T] {
90    self.deref_mut()
91  }
92
93  /// A `*const` pointer to the backing slice.
94  ///
95  /// ## Safety
96  ///
97  /// This pointer has provenance over the _entire_ backing slice.
98  #[inline(always)]
99  #[must_use]
100  pub fn as_ptr(&self) -> *const T {
101    self.data.as_ptr()
102  }
103
104  /// Performs a `deref`, into shared slice form.
105  #[inline(always)]
106  #[must_use]
107  pub fn as_slice(&self) -> &[T] {
108    self.deref()
109  }
110
111  /// The capacity of the `SliceVec`.
112  ///
113  /// This the length of the initial backing slice.
114  #[inline(always)]
115  #[must_use]
116  pub fn capacity(&self) -> usize {
117    self.data.len()
118  }
119
120  /// Truncates the `SliceVec` down to length 0.
121  #[inline(always)]
122  pub fn clear(&mut self)
123  where
124    T: Default,
125  {
126    self.truncate(0)
127  }
128
129  /// Creates a draining iterator that removes the specified range in the vector
130  /// and yields the removed items.
131  ///
132  /// ## Panics
133  /// * If the start is greater than the end
134  /// * If the end is past the edge of the vec.
135  ///
136  /// ## Example
137  /// ```rust
138  /// # use tinyvec::*;
139  /// let mut arr = [6, 7, 8];
140  /// let mut sv = SliceVec::from(&mut arr);
141  /// let drained_values: ArrayVec<[i32; 4]> = sv.drain(1..).collect();
142  /// assert_eq!(sv.as_slice(), &[6][..]);
143  /// assert_eq!(drained_values.as_slice(), &[7, 8][..]);
144  ///
145  /// sv.drain(..);
146  /// assert_eq!(sv.as_slice(), &[]);
147  /// ```
148  #[inline]
149  pub fn drain<'p, R: RangeBounds<usize>>(
150    &'p mut self, range: R,
151  ) -> SliceVecDrain<'p, 's, T>
152  where
153    T: Default,
154  {
155    use core::ops::Bound;
156    let start = match range.start_bound() {
157      Bound::Included(x) => *x,
158      Bound::Excluded(x) => x.saturating_add(1),
159      Bound::Unbounded => 0,
160    };
161    let end = match range.end_bound() {
162      Bound::Included(x) => x.saturating_add(1),
163      Bound::Excluded(x) => *x,
164      Bound::Unbounded => self.len,
165    };
166    assert!(
167      start <= end,
168      "SliceVec::drain> Illegal range, {} to {}",
169      start,
170      end
171    );
172    assert!(
173      end <= self.len,
174      "SliceVec::drain> Range ends at {} but length is only {}!",
175      end,
176      self.len
177    );
178    SliceVecDrain {
179      parent: self,
180      target_start: start,
181      target_index: start,
182      target_end: end,
183    }
184  }
185
186  #[inline]
187  pub fn extend_from_slice(&mut self, sli: &[T])
188  where
189    T: Clone,
190  {
191    if sli.is_empty() {
192      return;
193    }
194
195    let new_len = self.len + sli.len();
196    if new_len > self.capacity() {
197      panic!(
198        "SliceVec::extend_from_slice> total length {} exceeds capacity {}",
199        new_len,
200        self.capacity()
201      )
202    }
203
204    let target = &mut self.data[self.len..new_len];
205    target.clone_from_slice(sli);
206    self.set_len(new_len);
207  }
208
209  /// Fill the vector until its capacity has been reached.
210  ///
211  /// Successively fills unused space in the spare slice of the vector with
212  /// elements from the iterator. It then returns the remaining iterator
213  /// without exhausting it. This also allows appending the head of an
214  /// infinite iterator.
215  ///
216  /// This is an alternative to `Extend::extend` method for cases where the
217  /// length of the iterator can not be checked. Since this vector can not
218  /// reallocate to increase its capacity, it is unclear what to do with
219  /// remaining elements in the iterator and the iterator itself. The
220  /// interface also provides no way to communicate this to the caller.
221  ///
222  /// ## Panics
223  /// * If the `next` method of the provided iterator panics.
224  ///
225  /// ## Example
226  ///
227  /// ```rust
228  /// # use tinyvec::*;
229  /// let mut arr = [7, 7, 7, 7];
230  /// let mut sv = SliceVec::from_slice_len(&mut arr, 0);
231  /// let mut to_inf = sv.fill(0..);
232  /// assert_eq!(&sv[..], [0, 1, 2, 3]);
233  /// assert_eq!(to_inf.next(), Some(4));
234  /// ```
235  #[inline]
236  pub fn fill<I: IntoIterator<Item = T>>(&mut self, iter: I) -> I::IntoIter {
237    let mut iter = iter.into_iter();
238    for element in iter.by_ref().take(self.capacity() - self.len()) {
239      self.push(element);
240    }
241    iter
242  }
243
244  /// Wraps up a slice and uses the given length as the initial length.
245  ///
246  /// If you want to simply use the full slice, use `from` instead.
247  ///
248  /// ## Panics
249  ///
250  /// * The length specified must be less than or equal to the capacity of the
251  ///   slice.
252  #[inline]
253  #[must_use]
254  #[allow(clippy::match_wild_err_arm)]
255  pub fn from_slice_len(data: &'s mut [T], len: usize) -> Self {
256    assert!(len <= data.len());
257    Self { data, len }
258  }
259
260  /// Inserts an item at the position given, moving all following elements +1
261  /// index.
262  ///
263  /// ## Panics
264  /// * If `index` > `len`
265  /// * If the capacity is exhausted
266  ///
267  /// ## Example
268  /// ```rust
269  /// # use tinyvec::*;
270  /// let mut arr = [1, 2, 3, 0, 0];
271  /// let mut sv = SliceVec::from_slice_len(&mut arr, 3);
272  /// sv.insert(1, 4);
273  /// assert_eq!(sv.as_slice(), &[1, 4, 2, 3]);
274  /// sv.insert(4, 5);
275  /// assert_eq!(sv.as_slice(), &[1, 4, 2, 3, 5]);
276  /// ```
277  #[inline]
278  pub fn insert(&mut self, index: usize, item: T) {
279    if index > self.len {
280      panic!("SliceVec::insert> index {} is out of bounds {}", index, self.len);
281    }
282
283    // Try to push the element.
284    self.push(item);
285    // And move it into its place.
286    self.as_mut_slice()[index..].rotate_right(1);
287  }
288
289  /// Checks if the length is 0.
290  #[inline(always)]
291  #[must_use]
292  pub fn is_empty(&self) -> bool {
293    self.len == 0
294  }
295
296  /// The length of the `SliceVec` (in elements).
297  #[inline(always)]
298  #[must_use]
299  pub fn len(&self) -> usize {
300    self.len
301  }
302
303  /// Remove and return the last element of the vec, if there is one.
304  ///
305  /// ## Failure
306  /// * If the vec is empty you get `None`.
307  ///
308  /// ## Example
309  /// ```rust
310  /// # use tinyvec::*;
311  /// let mut arr = [1, 2];
312  /// let mut sv = SliceVec::from(&mut arr);
313  /// assert_eq!(sv.pop(), Some(2));
314  /// assert_eq!(sv.pop(), Some(1));
315  /// assert_eq!(sv.pop(), None);
316  /// ```
317  #[inline]
318  pub fn pop(&mut self) -> Option<T>
319  where
320    T: Default,
321  {
322    if self.len > 0 {
323      self.len -= 1;
324      let out = core::mem::take(&mut self.data[self.len]);
325      Some(out)
326    } else {
327      None
328    }
329  }
330
331  /// Place an element onto the end of the vec.
332  ///
333  /// ## Panics
334  /// * If the length of the vec would overflow the capacity.
335  ///
336  /// ## Example
337  /// ```rust
338  /// # use tinyvec::*;
339  /// let mut arr = [0, 0];
340  /// let mut sv = SliceVec::from_slice_len(&mut arr, 0);
341  /// assert_eq!(&sv[..], []);
342  /// sv.push(1);
343  /// assert_eq!(&sv[..], [1]);
344  /// sv.push(2);
345  /// assert_eq!(&sv[..], [1, 2]);
346  /// // sv.push(3); this would overflow the ArrayVec and panic!
347  /// ```
348  #[inline(always)]
349  pub fn push(&mut self, val: T) {
350    if self.len < self.capacity() {
351      self.data[self.len] = val;
352      self.len += 1;
353    } else {
354      panic!("SliceVec::push> capacity overflow")
355    }
356  }
357
358  /// Removes the item at `index`, shifting all others down by one index.
359  ///
360  /// Returns the removed element.
361  ///
362  /// ## Panics
363  ///
364  /// * If the index is out of bounds.
365  ///
366  /// ## Example
367  ///
368  /// ```rust
369  /// # use tinyvec::*;
370  /// let mut arr = [1, 2, 3];
371  /// let mut sv = SliceVec::from(&mut arr);
372  /// assert_eq!(sv.remove(1), 2);
373  /// assert_eq!(&sv[..], [1, 3]);
374  /// ```
375  #[inline]
376  pub fn remove(&mut self, index: usize) -> T
377  where
378    T: Default,
379  {
380    let targets: &mut [T] = &mut self.deref_mut()[index..];
381    let item = core::mem::take(&mut targets[0]);
382    targets.rotate_left(1);
383    self.len -= 1;
384    item
385  }
386
387  /// As [`resize_with`](SliceVec::resize_with)
388  /// and it clones the value as the closure.
389  ///
390  /// ## Example
391  ///
392  /// ```rust
393  /// # use tinyvec::*;
394  /// // bigger
395  /// let mut arr = ["hello", "", "", "", ""];
396  /// let mut sv = SliceVec::from_slice_len(&mut arr, 1);
397  /// sv.resize(3, "world");
398  /// assert_eq!(&sv[..], ["hello", "world", "world"]);
399  ///
400  /// // smaller
401  /// let mut arr = ['a', 'b', 'c', 'd'];
402  /// let mut sv = SliceVec::from(&mut arr);
403  /// sv.resize(2, 'z');
404  /// assert_eq!(&sv[..], ['a', 'b']);
405  /// ```
406  #[inline]
407  pub fn resize(&mut self, new_len: usize, new_val: T)
408  where
409    T: Clone,
410  {
411    self.resize_with(new_len, || new_val.clone())
412  }
413
414  /// Resize the vec to the new length.
415  ///
416  /// * If it needs to be longer, it's filled with repeated calls to the
417  ///   provided function.
418  /// * If it needs to be shorter, it's truncated.
419  ///   * If the type needs to drop the truncated slots are filled with calls to
420  ///     the provided function.
421  ///
422  /// ## Example
423  ///
424  /// ```rust
425  /// # use tinyvec::*;
426  /// let mut arr = [1, 2, 3, 7, 7, 7, 7];
427  /// let mut sv = SliceVec::from_slice_len(&mut arr, 3);
428  /// sv.resize_with(5, Default::default);
429  /// assert_eq!(&sv[..], [1, 2, 3, 0, 0]);
430  ///
431  /// let mut arr = [0, 0, 0, 0];
432  /// let mut sv = SliceVec::from_slice_len(&mut arr, 0);
433  /// let mut p = 1;
434  /// sv.resize_with(4, || {
435  ///   p *= 2;
436  ///   p
437  /// });
438  /// assert_eq!(&sv[..], [2, 4, 8, 16]);
439  /// ```
440  #[inline]
441  pub fn resize_with<F: FnMut() -> T>(&mut self, new_len: usize, mut f: F) {
442    match new_len.checked_sub(self.len) {
443      None => {
444        if needs_drop::<T>() {
445          while self.len() > new_len {
446            self.len -= 1;
447            self.data[self.len] = f();
448          }
449        } else {
450          self.len = new_len;
451        }
452      }
453      Some(new_elements) => {
454        for _ in 0..new_elements {
455          self.push(f());
456        }
457      }
458    }
459  }
460
461  /// Walk the vec and keep only the elements that pass the predicate given.
462  ///
463  /// ## Example
464  ///
465  /// ```rust
466  /// # use tinyvec::*;
467  ///
468  /// let mut arr = [1, 1, 2, 3, 3, 4];
469  /// let mut sv = SliceVec::from(&mut arr);
470  /// sv.retain(|&x| x % 2 == 0);
471  /// assert_eq!(&sv[..], [2, 4]);
472  /// ```
473  #[inline]
474  pub fn retain<F: FnMut(&T) -> bool>(&mut self, mut acceptable: F)
475  where
476    T: Default,
477  {
478    // Drop guard to contain exactly the remaining elements when the test
479    // panics.
480    struct JoinOnDrop<'vec, Item> {
481      items: &'vec mut [Item],
482      done_end: usize,
483      // Start of tail relative to `done_end`.
484      tail_start: usize,
485    }
486
487    impl<Item> Drop for JoinOnDrop<'_, Item> {
488      fn drop(&mut self) {
489        self.items[self.done_end..].rotate_left(self.tail_start);
490      }
491    }
492
493    let mut rest = JoinOnDrop { items: self.data, done_end: 0, tail_start: 0 };
494
495    for idx in 0..self.len {
496      // Loop start invariant: idx = rest.done_end + rest.tail_start
497      if !acceptable(&rest.items[idx]) {
498        let _ = core::mem::take(&mut rest.items[idx]);
499        self.len -= 1;
500        rest.tail_start += 1;
501      } else {
502        rest.items.swap(rest.done_end, idx);
503        rest.done_end += 1;
504      }
505    }
506  }
507
508  /// Forces the length of the vector to `new_len`.
509  ///
510  /// ## Panics
511  /// * If `new_len` is greater than the vec's capacity.
512  ///
513  /// ## Safety
514  /// * This is a fully safe operation! The inactive memory already counts as
515  ///   "initialized" by Rust's rules.
516  /// * Other than "the memory is initialized" there are no other guarantees
517  ///   regarding what you find in the inactive portion of the vec.
518  #[inline(always)]
519  pub fn set_len(&mut self, new_len: usize) {
520    if new_len > self.capacity() {
521      // Note(Lokathor): Technically we don't have to panic here, and we could
522      // just let some other call later on trigger a panic on accident when the
523      // length is wrong. However, it's a lot easier to catch bugs when things
524      // are more "fail-fast".
525      panic!(
526        "SliceVec::set_len> new length {} exceeds capacity {}",
527        new_len,
528        self.capacity()
529      )
530    } else {
531      self.len = new_len;
532    }
533  }
534
535  /// Splits the collection at the point given.
536  ///
537  /// * `[0, at)` stays in this vec (and this vec is now full).
538  /// * `[at, len)` ends up in the new vec (with any spare capacity).
539  ///
540  /// ## Panics
541  /// * if `at` > `self.len()`
542  ///
543  /// ## Example
544  ///
545  /// ```rust
546  /// # use tinyvec::*;
547  /// let mut arr = [1, 2, 3];
548  /// let mut sv = SliceVec::from(&mut arr);
549  /// let sv2 = sv.split_off(1);
550  /// assert_eq!(&sv[..], [1]);
551  /// assert_eq!(&sv2[..], [2, 3]);
552  /// ```
553  #[inline]
554  pub fn split_off<'a>(&'a mut self, at: usize) -> SliceVec<'s, T> {
555    let mut new = Self::default();
556    let backing: &'s mut [T] = core::mem::take(&mut self.data);
557    let (me, other) = backing.split_at_mut(at);
558    new.len = self.len - at;
559    new.data = other;
560    self.len = me.len();
561    self.data = me;
562    new
563  }
564
565  /// Remove an element, swapping the end of the vec into its place.
566  ///
567  /// ## Panics
568  /// * If the index is out of bounds.
569  ///
570  /// ## Example
571  /// ```rust
572  /// # use tinyvec::*;
573  /// let mut arr = ["foo", "bar", "quack", "zap"];
574  /// let mut sv = SliceVec::from(&mut arr);
575  ///
576  /// assert_eq!(sv.swap_remove(1), "bar");
577  /// assert_eq!(&sv[..], ["foo", "zap", "quack"]);
578  ///
579  /// assert_eq!(sv.swap_remove(0), "foo");
580  /// assert_eq!(&sv[..], ["quack", "zap"]);
581  /// ```
582  #[inline]
583  pub fn swap_remove(&mut self, index: usize) -> T
584  where
585    T: Default,
586  {
587    assert!(
588      index < self.len,
589      "SliceVec::swap_remove> index {} is out of bounds {}",
590      index,
591      self.len
592    );
593    if index == self.len - 1 {
594      self.pop().unwrap()
595    } else {
596      let i = self.pop().unwrap();
597      replace(&mut self[index], i)
598    }
599  }
600
601  /// Reduces the vec's length to the given value.
602  ///
603  /// If the vec is already shorter than the input, nothing happens.
604  #[inline]
605  pub fn truncate(&mut self, new_len: usize)
606  where
607    T: Default,
608  {
609    if needs_drop::<T>() {
610      while self.len > new_len {
611        self.pop();
612      }
613    } else {
614      self.len = self.len.min(new_len);
615    }
616  }
617
618  /// Wraps a slice, using the given length as the starting length.
619  ///
620  /// If you want to use the whole length of the slice, you can just use the
621  /// `From` impl.
622  ///
623  /// ## Failure
624  ///
625  /// If the given length is greater than the length of the slice you get
626  /// `None`.
627  #[inline]
628  pub fn try_from_slice_len(data: &'s mut [T], len: usize) -> Option<Self> {
629    if len <= data.len() {
630      Some(Self { data, len })
631    } else {
632      None
633    }
634  }
635}
636
637#[cfg(feature = "grab_spare_slice")]
638impl<'s, T> SliceVec<'s, T> {
639  /// Obtain the shared slice of the array _after_ the active memory.
640  ///
641  /// ## Example
642  /// ```rust
643  /// # use tinyvec::*;
644  /// let mut arr = [0; 4];
645  /// let mut sv = SliceVec::from_slice_len(&mut arr, 0);
646  /// assert_eq!(sv.grab_spare_slice().len(), 4);
647  /// sv.push(10);
648  /// sv.push(11);
649  /// sv.push(12);
650  /// sv.push(13);
651  /// assert_eq!(sv.grab_spare_slice().len(), 0);
652  /// ```
653  #[must_use]
654  #[inline(always)]
655  pub fn grab_spare_slice(&self) -> &[T] {
656    &self.data[self.len..]
657  }
658
659  /// Obtain the mutable slice of the array _after_ the active memory.
660  ///
661  /// ## Example
662  /// ```rust
663  /// # use tinyvec::*;
664  /// let mut arr = [0; 4];
665  /// let mut sv = SliceVec::from_slice_len(&mut arr, 0);
666  /// assert_eq!(sv.grab_spare_slice_mut().len(), 4);
667  /// sv.push(10);
668  /// sv.push(11);
669  /// assert_eq!(sv.grab_spare_slice_mut().len(), 2);
670  /// ```
671  #[inline(always)]
672  pub fn grab_spare_slice_mut(&mut self) -> &mut [T] {
673    &mut self.data[self.len..]
674  }
675}
676
677impl<'s, T> From<&'s mut [T]> for SliceVec<'s, T> {
678  /// Uses the full slice as the initial length.
679  /// ## Example
680  /// ```rust
681  /// # use tinyvec::*;
682  /// let mut arr = [0_i32; 2];
683  /// let mut sv = SliceVec::from(&mut arr[..]);
684  /// ```
685  #[inline]
686  fn from(data: &'s mut [T]) -> Self {
687    let len = data.len();
688    Self { data, len }
689  }
690}
691
692impl<'s, T, A> From<&'s mut A> for SliceVec<'s, T>
693where
694  A: AsMut<[T]>,
695{
696  /// Calls `AsRef::as_mut` then uses the full slice as the initial length.
697  /// ## Example
698  /// ```rust
699  /// # use tinyvec::*;
700  /// let mut arr = [0, 0];
701  /// let mut sv = SliceVec::from(&mut arr);
702  /// ```
703  #[inline]
704  fn from(a: &'s mut A) -> Self {
705    let data = a.as_mut();
706    let len = data.len();
707    Self { data, len }
708  }
709}
710
711/// Draining iterator for [`SliceVec`]
712///
713/// See [`SliceVec::drain`](SliceVec::drain)
714pub struct SliceVecDrain<'p, 's, T: Default> {
715  parent: &'p mut SliceVec<'s, T>,
716  target_start: usize,
717  target_index: usize,
718  target_end: usize,
719}
720impl<'p, 's, T: Default> Iterator for SliceVecDrain<'p, 's, T> {
721  type Item = T;
722  #[inline]
723  fn next(&mut self) -> Option<Self::Item> {
724    if self.target_index != self.target_end {
725      let out = core::mem::take(&mut self.parent[self.target_index]);
726      self.target_index += 1;
727      Some(out)
728    } else {
729      None
730    }
731  }
732}
733impl<'p, 's, T: Default> FusedIterator for SliceVecDrain<'p, 's, T> {}
734impl<'p, 's, T: Default> Drop for SliceVecDrain<'p, 's, T> {
735  #[inline]
736  fn drop(&mut self) {
737    // Changed because it was moving `self`, it's also more clear and the std
738    // does the same
739    self.for_each(drop);
740    // Implementation very similar to [`SliceVec::remove`](SliceVec::remove)
741    let count = self.target_end - self.target_start;
742    let targets: &mut [T] = &mut self.parent.deref_mut()[self.target_start..];
743    targets.rotate_left(count);
744    self.parent.len -= count;
745  }
746}
747
748impl<'s, T> AsMut<[T]> for SliceVec<'s, T> {
749  #[inline(always)]
750  fn as_mut(&mut self) -> &mut [T] {
751    &mut *self
752  }
753}
754
755impl<'s, T> AsRef<[T]> for SliceVec<'s, T> {
756  #[inline(always)]
757  fn as_ref(&self) -> &[T] {
758    &*self
759  }
760}
761
762impl<'s, T> Borrow<[T]> for SliceVec<'s, T> {
763  #[inline(always)]
764  fn borrow(&self) -> &[T] {
765    &*self
766  }
767}
768
769impl<'s, T> BorrowMut<[T]> for SliceVec<'s, T> {
770  #[inline(always)]
771  fn borrow_mut(&mut self) -> &mut [T] {
772    &mut *self
773  }
774}
775
776impl<'s, T> Extend<T> for SliceVec<'s, T> {
777  #[inline]
778  fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
779    for t in iter {
780      self.push(t)
781    }
782  }
783}
784
785impl<'s, T> IntoIterator for SliceVec<'s, T> {
786  type Item = &'s mut T;
787  type IntoIter = core::slice::IterMut<'s, T>;
788  #[inline(always)]
789  fn into_iter(self) -> Self::IntoIter {
790    self.data.iter_mut()
791  }
792}
793
794impl<'s, T> PartialEq for SliceVec<'s, T>
795where
796  T: PartialEq,
797{
798  #[inline]
799  fn eq(&self, other: &Self) -> bool {
800    self.as_slice().eq(other.as_slice())
801  }
802}
803impl<'s, T> Eq for SliceVec<'s, T> where T: Eq {}
804
805impl<'s, T> PartialOrd for SliceVec<'s, T>
806where
807  T: PartialOrd,
808{
809  #[inline]
810  fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
811    self.as_slice().partial_cmp(other.as_slice())
812  }
813}
814impl<'s, T> Ord for SliceVec<'s, T>
815where
816  T: Ord,
817{
818  #[inline]
819  fn cmp(&self, other: &Self) -> core::cmp::Ordering {
820    self.as_slice().cmp(other.as_slice())
821  }
822}
823
824impl<'s, T> PartialEq<&[T]> for SliceVec<'s, T>
825where
826  T: PartialEq,
827{
828  #[inline]
829  fn eq(&self, other: &&[T]) -> bool {
830    self.as_slice().eq(*other)
831  }
832}
833
834impl<'s, T> Hash for SliceVec<'s, T>
835where
836  T: Hash,
837{
838  #[inline]
839  fn hash<H: Hasher>(&self, state: &mut H) {
840    self.as_slice().hash(state)
841  }
842}
843
844#[cfg(feature = "experimental_write_impl")]
845impl<'s> core::fmt::Write for SliceVec<'s, u8> {
846  fn write_str(&mut self, s: &str) -> core::fmt::Result {
847    let my_len = self.len();
848    let str_len = s.as_bytes().len();
849    if my_len + str_len <= self.capacity() {
850      let remainder = &mut self.data[my_len..];
851      let target = &mut remainder[..str_len];
852      target.copy_from_slice(s.as_bytes());
853      Ok(())
854    } else {
855      Err(core::fmt::Error)
856    }
857  }
858}
859
860// // // // // // // //
861// Formatting impls
862// // // // // // // //
863
864impl<'s, T> Binary for SliceVec<'s, T>
865where
866  T: Binary,
867{
868  #[allow(clippy::missing_inline_in_public_items)]
869  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
870    write!(f, "[")?;
871    if f.alternate() {
872      write!(f, "\n    ")?;
873    }
874    for (i, elem) in self.iter().enumerate() {
875      if i > 0 {
876        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
877      }
878      Binary::fmt(elem, f)?;
879    }
880    if f.alternate() {
881      write!(f, ",\n")?;
882    }
883    write!(f, "]")
884  }
885}
886
887impl<'s, T> Debug for SliceVec<'s, T>
888where
889  T: Debug,
890{
891  #[allow(clippy::missing_inline_in_public_items)]
892  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
893    write!(f, "[")?;
894    if f.alternate() && !self.is_empty() {
895      write!(f, "\n    ")?;
896    }
897    for (i, elem) in self.iter().enumerate() {
898      if i > 0 {
899        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
900      }
901      Debug::fmt(elem, f)?;
902    }
903    if f.alternate() && !self.is_empty() {
904      write!(f, ",\n")?;
905    }
906    write!(f, "]")
907  }
908}
909
910impl<'s, T> Display for SliceVec<'s, T>
911where
912  T: Display,
913{
914  #[allow(clippy::missing_inline_in_public_items)]
915  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
916    write!(f, "[")?;
917    if f.alternate() {
918      write!(f, "\n    ")?;
919    }
920    for (i, elem) in self.iter().enumerate() {
921      if i > 0 {
922        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
923      }
924      Display::fmt(elem, f)?;
925    }
926    if f.alternate() {
927      write!(f, ",\n")?;
928    }
929    write!(f, "]")
930  }
931}
932
933impl<'s, T> LowerExp for SliceVec<'s, T>
934where
935  T: LowerExp,
936{
937  #[allow(clippy::missing_inline_in_public_items)]
938  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
939    write!(f, "[")?;
940    if f.alternate() {
941      write!(f, "\n    ")?;
942    }
943    for (i, elem) in self.iter().enumerate() {
944      if i > 0 {
945        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
946      }
947      LowerExp::fmt(elem, f)?;
948    }
949    if f.alternate() {
950      write!(f, ",\n")?;
951    }
952    write!(f, "]")
953  }
954}
955
956impl<'s, T> LowerHex for SliceVec<'s, T>
957where
958  T: LowerHex,
959{
960  #[allow(clippy::missing_inline_in_public_items)]
961  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
962    write!(f, "[")?;
963    if f.alternate() {
964      write!(f, "\n    ")?;
965    }
966    for (i, elem) in self.iter().enumerate() {
967      if i > 0 {
968        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
969      }
970      LowerHex::fmt(elem, f)?;
971    }
972    if f.alternate() {
973      write!(f, ",\n")?;
974    }
975    write!(f, "]")
976  }
977}
978
979impl<'s, T> Octal for SliceVec<'s, T>
980where
981  T: Octal,
982{
983  #[allow(clippy::missing_inline_in_public_items)]
984  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
985    write!(f, "[")?;
986    if f.alternate() {
987      write!(f, "\n    ")?;
988    }
989    for (i, elem) in self.iter().enumerate() {
990      if i > 0 {
991        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
992      }
993      Octal::fmt(elem, f)?;
994    }
995    if f.alternate() {
996      write!(f, ",\n")?;
997    }
998    write!(f, "]")
999  }
1000}
1001
1002impl<'s, T> Pointer for SliceVec<'s, T>
1003where
1004  T: Pointer,
1005{
1006  #[allow(clippy::missing_inline_in_public_items)]
1007  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1008    write!(f, "[")?;
1009    if f.alternate() {
1010      write!(f, "\n    ")?;
1011    }
1012    for (i, elem) in self.iter().enumerate() {
1013      if i > 0 {
1014        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1015      }
1016      Pointer::fmt(elem, f)?;
1017    }
1018    if f.alternate() {
1019      write!(f, ",\n")?;
1020    }
1021    write!(f, "]")
1022  }
1023}
1024
1025impl<'s, T> UpperExp for SliceVec<'s, T>
1026where
1027  T: UpperExp,
1028{
1029  #[allow(clippy::missing_inline_in_public_items)]
1030  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1031    write!(f, "[")?;
1032    if f.alternate() {
1033      write!(f, "\n    ")?;
1034    }
1035    for (i, elem) in self.iter().enumerate() {
1036      if i > 0 {
1037        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1038      }
1039      UpperExp::fmt(elem, f)?;
1040    }
1041    if f.alternate() {
1042      write!(f, ",\n")?;
1043    }
1044    write!(f, "]")
1045  }
1046}
1047
1048impl<'s, T> UpperHex for SliceVec<'s, T>
1049where
1050  T: UpperHex,
1051{
1052  #[allow(clippy::missing_inline_in_public_items)]
1053  fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
1054    write!(f, "[")?;
1055    if f.alternate() {
1056      write!(f, "\n    ")?;
1057    }
1058    for (i, elem) in self.iter().enumerate() {
1059      if i > 0 {
1060        write!(f, ",{}", if f.alternate() { "\n    " } else { " " })?;
1061      }
1062      UpperHex::fmt(elem, f)?;
1063    }
1064    if f.alternate() {
1065      write!(f, ",\n")?;
1066    }
1067    write!(f, "]")
1068  }
1069}