1#![allow(unused_variables)]
2#![allow(missing_docs)]
3
4use super::*;
5
6pub 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  #[inline(always)]
81  #[must_use]
82  pub fn as_mut_ptr(&mut self) -> *mut T {
83    self.data.as_mut_ptr()
84  }
85
86  #[inline(always)]
88  #[must_use]
89  pub fn as_mut_slice(&mut self) -> &mut [T] {
90    self.deref_mut()
91  }
92
93  #[inline(always)]
99  #[must_use]
100  pub fn as_ptr(&self) -> *const T {
101    self.data.as_ptr()
102  }
103
104  #[inline(always)]
106  #[must_use]
107  pub fn as_slice(&self) -> &[T] {
108    self.deref()
109  }
110
111  #[inline(always)]
115  #[must_use]
116  pub fn capacity(&self) -> usize {
117    self.data.len()
118  }
119
120  #[inline(always)]
122  pub fn clear(&mut self)
123  where
124    T: Default,
125  {
126    self.truncate(0)
127  }
128
129  #[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  #[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  #[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  #[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    self.push(item);
285    self.as_mut_slice()[index..].rotate_right(1);
287  }
288
289  #[inline(always)]
291  #[must_use]
292  pub fn is_empty(&self) -> bool {
293    self.len == 0
294  }
295
296  #[inline(always)]
298  #[must_use]
299  pub fn len(&self) -> usize {
300    self.len
301  }
302
303  #[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  #[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  #[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  #[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  #[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  #[inline]
474  pub fn retain<F: FnMut(&T) -> bool>(&mut self, mut acceptable: F)
475  where
476    T: Default,
477  {
478    struct JoinOnDrop<'vec, Item> {
481      items: &'vec mut [Item],
482      done_end: usize,
483      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      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  #[inline(always)]
519  pub fn set_len(&mut self, new_len: usize) {
520    if new_len > self.capacity() {
521      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  #[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  #[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  #[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  #[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  #[must_use]
654  #[inline(always)]
655  pub fn grab_spare_slice(&self) -> &[T] {
656    &self.data[self.len..]
657  }
658
659  #[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  #[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  #[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
711pub 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    self.for_each(drop);
740    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
860impl<'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}