stack_buf/vec.rs
1use std::borrow::{Borrow, BorrowMut};
2use std::cmp::Ordering;
3use std::hash::{Hash, Hasher};
4use std::iter::FromIterator;
5use std::mem::{ManuallyDrop, MaybeUninit};
6use std::ops::{
7 Bound, Deref, DerefMut, Index, IndexMut, Range, RangeBounds, RangeFrom, RangeFull,
8 RangeInclusive, RangeTo, RangeToInclusive,
9};
10use std::ptr::NonNull;
11use std::{fmt, ptr, slice};
12
13type Size = u32;
14
15/// Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
16///
17/// Copied from https://github.com/rust-lang/rust/pull/36355
18struct SetLenOnDrop<'a> {
19 len: &'a mut Size,
20 local_len: Size,
21}
22
23impl<'a> SetLenOnDrop<'a> {
24 #[inline]
25 fn new(len: &'a mut Size) -> Self {
26 SetLenOnDrop {
27 local_len: *len,
28 len,
29 }
30 }
31
32 #[inline(always)]
33 fn increment_len(&mut self, increment: Size) {
34 self.local_len += increment;
35 }
36}
37
38impl Drop for SetLenOnDrop<'_> {
39 #[inline]
40 fn drop(&mut self) {
41 *self.len = self.local_len;
42 }
43}
44
45/// A draining iterator for `StackVec<T, N>`.
46///
47/// This `struct` is created by [`StackVec::drain()`].
48pub struct Drain<'a, T: 'a, const N: usize> {
49 /// Index of tail to preserve
50 tail_start: usize,
51 /// Length of tail
52 tail_len: usize,
53 /// Current remaining range to remove
54 iter: slice::Iter<'a, T>,
55 vec: NonNull<StackVec<T, N>>,
56}
57
58unsafe impl<T: Sync, const N: usize> Sync for Drain<'_, T, N> {}
59unsafe impl<T: Send, const N: usize> Send for Drain<'_, T, N> {}
60
61impl<'a, T: 'a, const N: usize> Iterator for Drain<'a, T, N> {
62 type Item = T;
63
64 #[inline]
65 fn next(&mut self) -> Option<Self::Item> {
66 self.iter
67 .next()
68 .map(|elt| unsafe { ptr::read(elt as *const _) })
69 }
70
71 #[inline]
72 fn size_hint(&self) -> (usize, Option<usize>) {
73 self.iter.size_hint()
74 }
75}
76
77impl<'a, T: 'a, const N: usize> DoubleEndedIterator for Drain<'a, T, N> {
78 #[inline]
79 fn next_back(&mut self) -> Option<Self::Item> {
80 self.iter
81 .next_back()
82 .map(|elt| unsafe { ptr::read(elt as *const _) })
83 }
84}
85
86impl<'a, T: 'a, const N: usize> ExactSizeIterator for Drain<'a, T, N> {}
87
88impl<'a, T: 'a, const N: usize> Drop for Drain<'a, T, N> {
89 fn drop(&mut self) {
90 // len is currently 0 so panicking while dropping will not cause a double drop.
91
92 // exhaust self first
93 for _ in &mut *self {}
94
95 if self.tail_len > 0 {
96 unsafe {
97 let source_vec = self.vec.as_mut();
98 // memmove back untouched tail, update to new length
99 let start = source_vec.len();
100 let tail = self.tail_start;
101 let src = source_vec.as_ptr().add(tail);
102 let dst = source_vec.as_mut_ptr().add(start);
103 ptr::copy(src, dst, self.tail_len);
104 source_vec.set_len(start + self.tail_len);
105 }
106 }
107 }
108}
109
110/// A `Vec`-like container that stores elements on the stack.
111///
112/// The `StackVec` is a vector backed by a fixed size array. It keeps track of
113/// the number of initialized elements. The `StackVec<T, N>` is parameterized
114/// by `T` for the element type and `N` for the maximum capacity.
115///
116/// `N` is of type `usize` but is range limited to `u32::MAX`; attempting to create larger
117/// `StackVec` with larger capacity will panic.
118///
119/// The vector is a contiguous value (storing the elements inline) that you can store directly on
120/// the stack.
121///
122/// It offers a simple API but also dereferences to a slice, so that the full slice API is
123/// available.
124pub struct StackVec<T, const N: usize> {
125 vec: [MaybeUninit<T>; N],
126 len: Size,
127}
128
129impl<T, const N: usize> StackVec<T, N> {
130 /// Creates a new empty `StackVec`.
131 ///
132 /// The maximum capacity is given by the generic parameter `N`.
133 ///
134 /// # Examples
135 ///
136 /// ```
137 /// use stack_buf::StackVec;
138 ///
139 /// let mut vec = StackVec::<_, 16>::new();
140 /// vec.push(1);
141 /// vec.push(2);
142 /// assert_eq!(&vec[..], &[1, 2]);
143 /// assert_eq!(vec.capacity(), 16);
144 /// ```
145 #[inline]
146 pub const fn new() -> Self {
147 assert!(
148 N <= Size::MAX as usize,
149 "StackVec capacity exceeds u32::MAX"
150 );
151 StackVec {
152 vec: [const { MaybeUninit::uninit() }; N],
153 len: 0,
154 }
155 }
156
157 /// Returns the number of elements stored in the `StackVec`.
158 ///
159 /// # Examples
160 ///
161 /// ```
162 /// use stack_buf::StackVec;
163 ///
164 /// let mut vec = StackVec::from([1, 2, 3]);
165 /// vec.pop();
166 /// assert_eq!(vec.len(), 2);
167 /// ```
168 #[inline(always)]
169 pub const fn len(&self) -> usize {
170 self.len as usize
171 }
172
173 /// Returns `true` if the `StackVec` is empty, false otherwise.
174 ///
175 /// # Examples
176 ///
177 /// ```
178 /// use stack_buf::StackVec;
179 ///
180 /// let mut vec = StackVec::from([1]);
181 /// vec.pop();
182 /// assert_eq!(vec.is_empty(), true);
183 /// ```
184 #[inline(always)]
185 pub const fn is_empty(&self) -> bool {
186 self.len() == 0
187 }
188
189 /// Returns `true` if the `StackVec` is completely filled to its capacity, false otherwise.
190 ///
191 /// # Examples
192 ///
193 /// ```
194 /// use stack_buf::StackVec;
195 ///
196 /// let mut vec = StackVec::<_, 1>::new();
197 /// assert!(!vec.is_full());
198 /// vec.push(1);
199 /// assert!(vec.is_full());
200 /// ```
201 #[inline]
202 pub const fn is_full(&self) -> bool {
203 self.len() == self.capacity()
204 }
205
206 /// Returns the capacity of the `StackVec`.
207 ///
208 /// # Examples
209 ///
210 /// ```
211 /// use stack_buf::StackVec;
212 ///
213 /// let vec = StackVec::from([1, 2, 3]);
214 /// assert_eq!(vec.capacity(), 3);
215 /// ```
216 #[inline(always)]
217 pub const fn capacity(&self) -> usize {
218 N
219 }
220
221 /// Returns the capacity left in the `StackVec`.
222 ///
223 /// # Examples
224 ///
225 /// ```
226 /// use stack_buf::StackVec;
227 ///
228 /// let mut vec = StackVec::from([1, 2, 3]);
229 /// vec.pop();
230 /// assert_eq!(vec.remaining_capacity(), 1);
231 /// ```
232 #[inline]
233 pub const fn remaining_capacity(&self) -> usize {
234 self.capacity() - self.len()
235 }
236
237 /// Returns a raw pointer to the `StackVec`'s buffer.
238 #[inline(always)]
239 pub const fn as_ptr(&self) -> *const T {
240 self.vec.as_ptr() as _
241 }
242
243 /// Returns a raw mutable pointer to the `StackVec`'s buffer.
244 #[inline(always)]
245 pub const fn as_mut_ptr(&mut self) -> *mut T {
246 self.vec.as_mut_ptr() as _
247 }
248
249 /// Returns a slice containing all elements of the `StackVec`.
250 #[inline]
251 pub const fn as_slice(&self) -> &[T] {
252 unsafe { slice::from_raw_parts(self.as_ptr(), self.len()) }
253 }
254
255 /// Returns a mutable slice containing all elements of the `StackVec`.
256 #[inline]
257 pub const fn as_mut_slice(&mut self) -> &mut [T] {
258 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len()) }
259 }
260
261 /// Sets the `StackVec`’s length without dropping or moving out elements
262 ///
263 /// # Safety
264 /// This method is `unsafe` because it changes the notion of the
265 /// number of “valid” elements in the vector.
266 ///
267 /// This method uses *debug assertions* to check that `length` is
268 /// not greater than the capacity.
269 #[inline]
270 pub const unsafe fn set_len(&mut self, length: usize) {
271 debug_assert!(length <= self.capacity());
272 self.len = length as Size;
273 }
274
275 /// Appends an `value` to the end of the `StackVec`.
276 ///
277 /// # Panics
278 ///
279 /// This function will panic if the `StackVec` is already full.
280 ///
281 /// # Examples
282 ///
283 /// ```
284 /// use stack_buf::StackVec;
285 ///
286 /// let mut vec = StackVec::<_, 2>::new();
287 ///
288 /// vec.push(1);
289 /// vec.push(2);
290 ///
291 /// assert_eq!(&vec[..], &[1, 2]);
292 /// ```
293 #[inline]
294 pub fn push(&mut self, value: T) {
295 self.vec[self.len()] = MaybeUninit::new(value);
296 self.len += 1;
297 }
298
299 /// Removes the last element of the vector and return it, or None if empty.
300 ///
301 /// # Examples
302 ///
303 /// ```
304 /// use stack_buf::StackVec;
305 ///
306 /// let mut vec = StackVec::<_, 2>::new();
307 ///
308 /// vec.push(1);
309 ///
310 /// assert_eq!(vec.pop(), Some(1));
311 /// assert_eq!(vec.pop(), None);
312 /// ```
313 #[inline]
314 pub fn pop(&mut self) -> Option<T> {
315 if self.is_empty() {
316 return None;
317 }
318 unsafe {
319 self.len -= 1;
320 Some(ptr::read(self.as_ptr().add(self.len())))
321 }
322 }
323
324 /// Shortens the vector, keeping the first `len` elements and dropping
325 /// the rest.
326 ///
327 /// If `len` is greater than the vector’s current length this has no
328 /// effect.
329 ///
330 /// # Examples
331 ///
332 /// ```
333 /// use stack_buf::StackVec;
334 ///
335 /// let mut vec = StackVec::from([1, 2, 3, 4, 5]);
336 /// vec.truncate(3);
337 /// assert_eq!(&vec[..], &[1, 2, 3]);
338 /// vec.truncate(4);
339 /// assert_eq!(&vec[..], &[1, 2, 3]);
340 /// ```
341 #[inline]
342 pub fn truncate(&mut self, len: usize) {
343 if len > self.len() {
344 return;
345 }
346
347 unsafe {
348 let remaining_len = self.len() - len;
349 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
350 self.set_len(len);
351 ptr::drop_in_place(s);
352 }
353 }
354
355 /// Clears the vector, removing all values.
356 ///
357 /// Note that this method has no effect on the allocated capacity
358 /// of the vector.
359 ///
360 /// # Examples
361 ///
362 /// ```
363 /// use stack_buf::StackVec;
364 ///
365 /// let mut vec = StackVec::from([1, 2, 3]);
366 ///
367 /// vec.clear();
368 ///
369 /// assert!(vec.is_empty());
370 /// ```
371 #[inline]
372 pub fn clear(&mut self) {
373 self.truncate(0)
374 }
375
376 /// Inserts an element at position `index` within the vector, shifting all
377 /// elements after it to the right.
378 ///
379 /// # Panics
380 ///
381 /// Panics if `index > len` or the vector is full.
382 ///
383 /// # Examples
384 ///
385 /// ```
386 /// use stack_buf::{StackVec, stack_vec};
387 ///
388 /// let mut vec = stack_vec![5 # 1, 2, 3];
389 /// vec.insert(1, 4);
390 /// assert_eq!(&vec[..], [1, 4, 2, 3]);
391 /// vec.insert(4, 5);
392 /// assert_eq!(&vec[..], [1, 4, 2, 3, 5]);
393 /// ```
394 #[inline]
395 pub fn insert(&mut self, index: usize, element: T) {
396 #[cold]
397 #[inline(never)]
398 fn assert_failed(index: usize, len: usize) -> ! {
399 panic!(
400 "insertion index (is {}) should be <= len (is {})",
401 index, len
402 );
403 }
404
405 let len = self.len();
406 if index > len {
407 assert_failed(index, len);
408 }
409 assert!(len < self.capacity());
410 unsafe {
411 let ptr = self.as_mut_ptr().add(index);
412 ptr::copy(ptr, ptr.offset(1), len - index);
413 ptr::write(ptr, element);
414 self.set_len(len + 1);
415 }
416 }
417
418 /// Removes and returns the element at position `index` within the vector,
419 /// shifting all elements after it to the left.
420 ///
421 /// # Panics
422 ///
423 /// Panics if `index` is out of bounds.
424 ///
425 /// # Examples
426 ///
427 /// ```
428 /// use stack_buf::StackVec;
429 ///
430 /// let mut vec = StackVec::from([1, 2, 3]);
431 /// assert_eq!(vec.remove(1), 2);
432 /// assert_eq!(&vec[..], [1, 3]);
433 /// ```
434 #[inline]
435 pub fn remove(&mut self, index: usize) -> T {
436 #[cold]
437 #[inline(never)]
438 fn assert_failed(index: usize, len: usize) -> ! {
439 panic!("removal index (is {}) should be < len (is {})", index, len);
440 }
441
442 let len = self.len();
443 if index >= len {
444 assert_failed(index, len);
445 }
446 unsafe {
447 let ret;
448 {
449 let ptr = self.as_mut_ptr().add(index);
450 ret = ptr::read(ptr);
451 ptr::copy(ptr.offset(1), ptr, len - index - 1);
452 }
453 self.set_len(len - 1);
454 ret
455 }
456 }
457
458 /// Removes an element from the vector and returns it.
459 ///
460 /// The removed element is replaced by the last element of the vector.
461 ///
462 /// This does not preserve ordering, but is O(1).
463 ///
464 /// # Panics
465 ///
466 /// Panics if `index` is out of bounds.
467 ///
468 /// # Examples
469 ///
470 /// ```
471 /// use stack_buf::StackVec;
472 ///
473 /// let mut v = StackVec::from(["foo", "bar", "baz", "qux"]);
474 ///
475 /// assert_eq!(v.swap_remove(1), "bar");
476 /// assert_eq!(&v[..], ["foo", "qux", "baz"]);
477 ///
478 /// assert_eq!(v.swap_remove(0), "foo");
479 /// assert_eq!(&v[..], ["baz", "qux"]);
480 /// ```
481 #[inline]
482 pub fn swap_remove(&mut self, index: usize) -> T {
483 #[cold]
484 #[inline(never)]
485 fn assert_failed(index: usize, len: usize) -> ! {
486 panic!(
487 "swap_remove index (is {}) should be < len (is {})",
488 index, len
489 );
490 }
491
492 let len = self.len();
493 if index >= len {
494 assert_failed(index, len);
495 }
496 unsafe {
497 // We replace self[index] with the last element. Note that if the
498 // bounds check above succeeds there must be a last element (which
499 // can be self[index] itself).
500 let last = ptr::read(self.as_ptr().add(len - 1));
501 let hole = self.as_mut_ptr().add(index);
502 self.set_len(len - 1);
503 ptr::replace(hole, last)
504 }
505 }
506
507 /// Create a draining iterator that removes the specified range in the vector
508 /// and yields the removed items from start to end. The element range is
509 /// removed even if the iterator is not consumed until the end.
510 ///
511 /// Note: It is unspecified how many elements are removed from the vector,
512 /// if the `Drain` value is leaked.
513 ///
514 /// # Panics
515 /// If the starting point is greater than the end point or if
516 /// the end point is greater than the length of the vector.
517 ///
518 /// # Examples
519 ///
520 /// ```
521 /// use stack_buf::StackVec;
522 ///
523 /// let mut v1 = StackVec::from([1, 2, 3]);
524 /// let v2: StackVec<_, 3> = v1.drain(0..2).collect();
525 /// assert_eq!(&v1[..], &[3]);
526 /// assert_eq!(&v2[..], &[1, 2]);
527 /// ```
528 #[inline]
529 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, N>
530 where
531 R: RangeBounds<usize>,
532 {
533 // Memory safety
534 //
535 // When the Drain is first created, it shortens the length of
536 // the source vector to make sure no uninitialized or moved-from elements
537 // are accessible at all if the Drain's destructor never gets to run.
538 //
539 // Drain will ptr::read out the values to remove.
540 // When finished, remaining tail of the vec is copied back to cover
541 // the hole, and the vector length is restored to the new length.
542 //
543 let len = self.len();
544 let start = match range.start_bound() {
545 Bound::Unbounded => 0,
546 Bound::Included(&i) => i,
547 Bound::Excluded(&i) => i.saturating_add(1),
548 };
549 let end = match range.end_bound() {
550 Bound::Excluded(&j) => j,
551 Bound::Included(&j) => j.saturating_add(1),
552 Bound::Unbounded => len,
553 };
554
555 // bounds check happens here (before length is changed!)
556 let range_slice: *const _ = &self[start..end];
557
558 // Calling `set_len` creates a fresh and thus unique mutable references, making all
559 // older aliases we created invalid. So we cannot call that function.
560 self.len = start as Size;
561
562 unsafe {
563 Drain {
564 tail_start: end,
565 tail_len: len - end,
566 iter: (*range_slice).iter(),
567 vec: NonNull::new_unchecked(self as *mut _),
568 }
569 }
570 }
571
572 /// Retains only the elements specified by the predicate.
573 ///
574 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
575 /// This method operates in place and preserves the order of the retained
576 /// elements.
577 ///
578 /// # Examples
579 ///
580 /// ```
581 /// use stack_buf::StackVec;
582 ///
583 /// let mut vec = StackVec::from([1, 2, 3, 4]);
584 /// vec.retain(|x| *x & 1 != 0 );
585 /// assert_eq!(&vec[..], &[1, 3]);
586 /// ```
587 #[inline]
588 pub fn retain<F>(&mut self, mut f: F)
589 where
590 F: FnMut(&mut T) -> bool,
591 {
592 let mut del = 0;
593 let len = self.len();
594 for i in 0..len {
595 if !f(&mut self[i]) {
596 del += 1;
597 } else if del > 0 {
598 self.swap(i - del, i);
599 }
600 }
601 self.truncate(len - del);
602 }
603
604 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
605 /// relation.
606 ///
607 /// The `same_bucket` function is passed references to two elements from the vector and
608 /// must determine if the elements compare equal. The elements are passed in opposite order
609 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
610 ///
611 /// If the vector is sorted, this removes all duplicates.
612 ///
613 /// # Examples
614 ///
615 /// ```
616 /// use stack_buf::stack_vec;
617 ///
618 /// let mut vec = stack_vec!["foo", "bar", "Bar", "baz", "bar"];
619 ///
620 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
621 ///
622 /// assert_eq!(&vec[..], ["foo", "bar", "baz", "bar"]);
623 /// ```
624 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
625 where
626 F: FnMut(&mut T, &mut T) -> bool,
627 {
628 // See the implementation of Vec::dedup_by in the
629 // standard library for an explanation of this algorithm.
630 let len = self.len();
631 if len <= 1 {
632 return;
633 }
634
635 let ptr = self.as_mut_ptr();
636 let mut w: usize = 1;
637
638 unsafe {
639 for r in 1..len {
640 let p_r = ptr.add(r);
641 let p_wm1 = ptr.add(w - 1);
642 if !same_bucket(&mut *p_r, &mut *p_wm1) {
643 if r != w {
644 let p_w = p_wm1.add(1);
645 ptr::swap(p_r, p_w);
646 }
647 w += 1;
648 }
649 }
650 }
651
652 self.truncate(w);
653 }
654
655 /// Removes all but the first of consecutive elements in the vector that resolve to the same
656 /// key.
657 ///
658 /// If the vector is sorted, this removes all duplicates.
659 ///
660 /// # Examples
661 ///
662 /// ```
663 /// use stack_buf::stack_vec;
664 ///
665 /// let mut vec = stack_vec![10, 20, 21, 30, 20];
666 ///
667 /// vec.dedup_by_key(|i| *i / 10);
668 ///
669 /// assert_eq!(&vec[..], [10, 20, 30, 20]);
670 /// ```
671 #[inline]
672 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
673 where
674 F: FnMut(&mut T) -> K,
675 K: PartialEq,
676 {
677 self.dedup_by(|a, b| key(a) == key(b))
678 }
679}
680
681impl<T: Clone, const N: usize> StackVec<T, N> {
682 /// Creates a `StackVec` with `n` copies of `elem`.
683 ///
684 /// # Panics
685 ///
686 /// This function will panic if the `n > N`.
687 ///
688 /// # Examples
689 ///
690 /// ```
691 /// use stack_buf::StackVec;
692 ///
693 /// let vec = StackVec::<char, 128>::from_elem('d', 2);
694 /// assert_eq!(&vec[..], ['d', 'd']);
695 /// ```
696 #[inline]
697 pub fn from_elem(elem: T, n: usize) -> Self {
698 let mut vec = StackVec::<T, N>::new();
699 vec.push_elem(elem, n);
700 vec
701 }
702
703 /// Appends `n` copies of `elem` to the `StackVec`.
704 ///
705 /// # Panics
706 ///
707 /// This function will panic if the `self.remaining_capacity() < n`.
708 ///
709 /// # Examples
710 ///
711 /// ```
712 /// use stack_buf::StackVec;
713 ///
714 /// let mut vec = StackVec::<char, 10>::new();
715 /// vec.push('a');
716 /// vec.push_elem('d', 2);
717 /// assert_eq!(&vec[..], ['a', 'd', 'd']);
718 /// ```
719 #[inline]
720 pub fn push_elem(&mut self, elem: T, n: usize) {
721 assert!(self.remaining_capacity() >= n);
722 unsafe {
723 let ptr = self.as_mut_ptr();
724 let mut local_len = SetLenOnDrop::new(&mut self.len);
725 for _ in 0..n {
726 ptr::write(ptr.offset(local_len.local_len as isize), elem.clone());
727 local_len.increment_len(1);
728 }
729 }
730 }
731
732 /// Clones and appends all elements in a slice to the `StackVec`.
733 ///
734 /// Iterates over the slice `other`, clones each element, and then appends
735 /// it to this `StackVec`. The `other` vector is traversed in-order.
736 ///
737 /// # Panics
738 ///
739 /// This function will panic if `self.remaining_capacity() < other.len()`.
740 ///
741 /// # Examples
742 ///
743 /// ```
744 /// use stack_buf::{StackVec, stack_vec};
745 /// let mut vec = stack_vec![10 # 1];
746 /// vec.extend_from_slice(&[2, 3, 4]);
747 /// assert_eq!(&vec[..], [1, 2, 3, 4]);
748 /// ```
749 #[inline]
750 pub fn extend_from_slice(&mut self, other: &[T]) {
751 assert!(self.remaining_capacity() >= other.len());
752 unsafe {
753 let ptr = self.as_mut_ptr();
754 let mut local_len = SetLenOnDrop::new(&mut self.len);
755 for elem in other {
756 ptr::write(ptr.offset(local_len.local_len as isize), elem.clone());
757 local_len.increment_len(1);
758 }
759 }
760 }
761
762 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
763 ///
764 /// If `new_len` is greater than `len`, the `Vec` is extended by the
765 /// difference, with each additional slot filled with `value`.
766 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
767 ///
768 /// This method requires `T` to implement [`Clone`],
769 /// in order to be able to clone the passed value.
770 ///
771 /// # Panics
772 ///
773 /// This function will be panic if `new_len > self.capacity()`.
774 ///
775 /// # Examples
776 ///
777 /// ```
778 /// use stack_buf::{StackVec, stack_vec};
779 ///
780 /// let mut vec = stack_vec![5 # "hello"];
781 /// vec.resize(3, "world");
782 /// assert_eq!(&vec[..], ["hello", "world", "world"]);
783 ///
784 /// let mut vec = stack_vec![1, 2, 3, 4];
785 /// vec.resize(2, 0);
786 /// assert_eq!(&vec[..], [1, 2]);
787 /// ```
788 #[inline]
789 pub fn resize(&mut self, new_len: usize, value: T) {
790 assert!(new_len <= self.capacity());
791 let len = self.len();
792
793 if new_len > len {
794 self.push_elem(value, new_len - len);
795 } else {
796 self.truncate(new_len);
797 }
798 }
799}
800
801impl<T: Copy, const N: usize> StackVec<T, N> {
802 /// Copies all elements from `src` into `self`, using a memcpy.
803 ///
804 /// The length of `src` must be less than or equals `self`'s remaining capacity.
805 ///
806 /// If `T` does not implement `Copy`, use [`StackVec::extend_from_slice()`].
807 ///
808 /// # Panics
809 ///
810 /// This function will panic if the length of `self.remaining_capacity() < src.len()`.
811 ///
812 /// # Examples
813 ///
814 /// Copying two elements from a slice into a `StackVec`:
815 ///
816 /// ```
817 /// use stack_buf::StackVec;
818 ///
819 /// let src = [1, 2, 3, 4];
820 /// let mut dst = StackVec::<_, 8>::new();
821 ///
822 /// dst.copy_from_slice(&src[2..]);
823 ///
824 /// assert_eq!(src, [1, 2, 3, 4]);
825 /// assert_eq!(&dst[..], [3, 4]);
826 /// ```
827 #[inline]
828 pub fn copy_from_slice(&mut self, src: &[T]) {
829 assert!(self.remaining_capacity() >= src.len());
830
831 unsafe {
832 let dest = self.as_mut_ptr().add(self.len());
833 ptr::copy_nonoverlapping(src.as_ptr(), dest, src.len());
834 self.set_len(self.len() + src.len());
835 }
836 }
837}
838
839impl<T, const N: usize> Drop for StackVec<T, N> {
840 #[inline]
841 fn drop(&mut self) {
842 unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len())) }
843 }
844}
845
846/// Creates a `StackVec` from an array.
847///
848/// # Examples
849///
850/// ```
851/// use stack_buf::StackVec;
852///
853/// let mut vec = StackVec::from([1, 2, 3]);
854/// assert_eq!(vec.len(), 3);
855/// assert_eq!(vec.capacity(), 3);
856/// ```
857impl<T, const N: usize> From<[T; N]> for StackVec<T, N> {
858 #[inline]
859 fn from(array: [T; N]) -> Self {
860 let array = ManuallyDrop::new(array);
861 let mut vec = StackVec::<T, N>::new();
862 unsafe {
863 (&*array as *const [T; N] as *const [MaybeUninit<T>; N])
864 .copy_to_nonoverlapping(&mut vec.vec as *mut [MaybeUninit<T>; N], 1);
865 vec.set_len(N);
866 }
867 vec
868 }
869}
870
871impl<T, const N: usize> Clone for StackVec<T, N>
872where
873 T: Clone,
874{
875 #[inline]
876 fn clone(&self) -> Self {
877 self.iter().cloned().collect()
878 }
879
880 #[inline]
881 fn clone_from(&mut self, source: &Self) {
882 self.clear();
883 self.extend_from_slice(source);
884 }
885}
886
887impl<T, const N: usize> Deref for StackVec<T, N> {
888 type Target = [T];
889
890 #[inline(always)]
891 fn deref(&self) -> &[T] {
892 self.as_slice()
893 }
894}
895
896impl<T, const N: usize> DerefMut for StackVec<T, N> {
897 #[inline(always)]
898 fn deref_mut(&mut self) -> &mut [T] {
899 self.as_mut_slice()
900 }
901}
902
903impl<T, const N: usize> AsRef<[T]> for StackVec<T, N> {
904 #[inline(always)]
905 fn as_ref(&self) -> &[T] {
906 self.as_slice()
907 }
908}
909
910impl<T, const N: usize> AsMut<[T]> for StackVec<T, N> {
911 #[inline(always)]
912 fn as_mut(&mut self) -> &mut [T] {
913 self.as_mut_slice()
914 }
915}
916
917impl<T, const N: usize> Borrow<[T]> for StackVec<T, N> {
918 #[inline(always)]
919 fn borrow(&self) -> &[T] {
920 self.as_slice()
921 }
922}
923
924impl<T, const N: usize> BorrowMut<[T]> for StackVec<T, N> {
925 #[inline(always)]
926 fn borrow_mut(&mut self) -> &mut [T] {
927 self.as_mut_slice()
928 }
929}
930
931impl<T, const N: usize> Default for StackVec<T, N> {
932 /// Creates an empty `StackVec<T, N>`.
933 #[inline(always)]
934 fn default() -> StackVec<T, N> {
935 StackVec::new()
936 }
937}
938
939impl<T: fmt::Debug, const N: usize> fmt::Debug for StackVec<T, N> {
940 #[inline]
941 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
942 fmt::Debug::fmt(&**self, f)
943 }
944}
945
946impl<T, const N: usize> Hash for StackVec<T, N>
947where
948 T: Hash,
949{
950 #[inline]
951 fn hash<H: Hasher>(&self, state: &mut H) {
952 Hash::hash(&**self, state)
953 }
954}
955
956impl<T, const N1: usize, const N2: usize> PartialEq<StackVec<T, N2>> for StackVec<T, N1>
957where
958 T: PartialEq,
959{
960 #[inline]
961 fn eq(&self, other: &StackVec<T, N2>) -> bool {
962 **self == **other
963 }
964}
965
966impl<T, const N: usize> PartialEq<[T]> for StackVec<T, N>
967where
968 T: PartialEq,
969{
970 #[inline]
971 fn eq(&self, other: &[T]) -> bool {
972 **self == *other
973 }
974}
975
976impl<T, const N: usize> Eq for StackVec<T, N> where T: Eq {}
977
978impl<T: PartialOrd, const N1: usize, const N2: usize> PartialOrd<StackVec<T, N2>>
979 for StackVec<T, N1>
980{
981 #[inline]
982 fn partial_cmp(&self, other: &StackVec<T, N2>) -> Option<Ordering> {
983 PartialOrd::partial_cmp(&**self, &**other)
984 }
985}
986
987impl<T: Ord, const N: usize> Ord for StackVec<T, N> {
988 #[inline]
989 fn cmp(&self, other: &Self) -> Ordering {
990 Ord::cmp(&**self, &**other)
991 }
992}
993
994#[cfg(feature = "std")]
995#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
996impl<const N: usize> std::io::Write for StackVec<u8, N> {
997 #[inline]
998 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
999 self.copy_from_slice(buf);
1000 Ok(buf.len())
1001 }
1002
1003 #[inline]
1004 fn flush(&mut self) -> std::io::Result<()> {
1005 Ok(())
1006 }
1007}
1008
1009impl<const N: usize> fmt::Write for StackVec<u8, N> {
1010 #[inline]
1011 fn write_str(&mut self, s: &str) -> fmt::Result {
1012 self.copy_from_slice(s.as_bytes());
1013 Ok(())
1014 }
1015}
1016
1017impl<T, const N: usize> Index<usize> for StackVec<T, N> {
1018 type Output = T;
1019
1020 #[inline]
1021 fn index(&self, index: usize) -> &Self::Output {
1022 &self.as_slice()[index]
1023 }
1024}
1025
1026impl<T, const N: usize> IndexMut<usize> for StackVec<T, N> {
1027 #[inline]
1028 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1029 &mut self.as_mut_slice()[index]
1030 }
1031}
1032
1033impl<T, const N: usize> Index<RangeFull> for StackVec<T, N> {
1034 type Output = [T];
1035
1036 #[inline]
1037 fn index(&self, _index: RangeFull) -> &Self::Output {
1038 self.as_slice()
1039 }
1040}
1041
1042impl<T, const N: usize> IndexMut<RangeFull> for StackVec<T, N> {
1043 #[inline]
1044 fn index_mut(&mut self, _index: RangeFull) -> &mut Self::Output {
1045 self.as_mut_slice()
1046 }
1047}
1048
1049macro_rules! impl_range_index {
1050 ($idx_ty: ty) => {
1051 impl<T, const N: usize> Index<$idx_ty> for StackVec<T, N> {
1052 type Output = [T];
1053
1054 #[inline]
1055 fn index(&self, index: $idx_ty) -> &Self::Output {
1056 &self.as_slice()[index]
1057 }
1058 }
1059
1060 impl<T, const N: usize> IndexMut<$idx_ty> for StackVec<T, N> {
1061 #[inline]
1062 fn index_mut(&mut self, index: $idx_ty) -> &mut Self::Output {
1063 &mut self.as_mut_slice()[index]
1064 }
1065 }
1066 };
1067 ($($idx_ty: ty),+ $(,)?) => {
1068 $(impl_range_index!($idx_ty);)+
1069 }
1070}
1071
1072impl_range_index!(
1073 Range<usize>,
1074 RangeFrom<usize>,
1075 RangeInclusive<usize>,
1076 RangeTo<usize>,
1077 RangeToInclusive<usize>,
1078);
1079
1080impl<T, const N: usize> Extend<T> for StackVec<T, N> {
1081 #[inline]
1082 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1083 for elem in iter.into_iter() {
1084 self.push(elem);
1085 }
1086 }
1087}
1088
1089impl<T, const N: usize> FromIterator<T> for StackVec<T, N> {
1090 #[inline]
1091 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1092 let mut vec = StackVec::new();
1093 vec.extend(iter);
1094 vec
1095 }
1096}
1097
1098/// Iterate the `StackVec` with references to each element.
1099///
1100/// ```
1101/// use stack_buf::StackVec;
1102///
1103/// let vec = StackVec::from([1, 2, 3]);
1104///
1105/// for ele in &vec {
1106/// // ...
1107/// }
1108/// ```
1109impl<'a, T, const N: usize> IntoIterator for &'a StackVec<T, N> {
1110 type Item = &'a T;
1111 type IntoIter = slice::Iter<'a, T>;
1112
1113 #[inline]
1114 fn into_iter(self) -> Self::IntoIter {
1115 self.iter()
1116 }
1117}
1118
1119/// Iterate the `StackVec` with mutable references to each element.
1120///
1121/// ```
1122/// use stack_buf::StackVec;
1123///
1124/// let mut vec = StackVec::from([1, 2, 3]);
1125///
1126/// for ele in &mut vec {
1127/// // ...
1128/// }
1129/// ```
1130impl<'a, T, const N: usize> IntoIterator for &'a mut StackVec<T, N> {
1131 type Item = &'a mut T;
1132 type IntoIter = slice::IterMut<'a, T>;
1133
1134 #[inline]
1135 fn into_iter(self) -> Self::IntoIter {
1136 self.iter_mut()
1137 }
1138}
1139
1140/// Iterate the `StackVec` with each element by value.
1141///
1142/// The vector is consumed by this operation.
1143///
1144/// ```
1145/// use stack_buf::StackVec;
1146///
1147/// for ele in StackVec::from([1, 2, 3]) {
1148/// // ...
1149/// }
1150/// ```
1151impl<T, const N: usize> IntoIterator for StackVec<T, N> {
1152 type Item = T;
1153 type IntoIter = IntoIter<T, N>;
1154
1155 #[inline]
1156 fn into_iter(self) -> Self::IntoIter {
1157 IntoIter {
1158 vec: self,
1159 index: 0,
1160 }
1161 }
1162}
1163
1164/// An iterator that consumes a `StackVec` and yields its items by value.
1165///
1166/// Returned from [`StackVec::into_iter()`].
1167pub struct IntoIter<T, const N: usize> {
1168 vec: StackVec<T, N>,
1169 index: usize,
1170}
1171
1172impl<T, const N: usize> Iterator for IntoIter<T, N> {
1173 type Item = T;
1174
1175 #[inline]
1176 fn next(&mut self) -> Option<Self::Item> {
1177 if self.index == self.vec.len() {
1178 None
1179 } else {
1180 unsafe {
1181 let index = self.index;
1182 self.index = index + 1;
1183 Some(ptr::read(self.vec.as_mut_ptr().add(index)))
1184 }
1185 }
1186 }
1187
1188 #[inline]
1189 fn size_hint(&self) -> (usize, Option<usize>) {
1190 let len = self.vec.len() - self.index;
1191 (len, Some(len))
1192 }
1193}
1194
1195impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, N> {
1196 #[inline]
1197 fn next_back(&mut self) -> Option<Self::Item> {
1198 if self.index == self.vec.len() {
1199 None
1200 } else {
1201 unsafe {
1202 let new_len = self.vec.len() - 1;
1203 self.vec.set_len(new_len);
1204 Some(ptr::read(self.vec.as_mut_ptr().add(new_len)))
1205 }
1206 }
1207 }
1208}
1209
1210impl<T, const N: usize> ExactSizeIterator for IntoIter<T, N> {}
1211
1212impl<T, const N: usize> Drop for IntoIter<T, N> {
1213 #[inline]
1214 fn drop(&mut self) {
1215 let index = self.index;
1216 let len = self.vec.len();
1217 unsafe {
1218 self.vec.set_len(0);
1219 let elements = slice::from_raw_parts_mut(self.vec.as_mut_ptr().add(index), len - index);
1220 ptr::drop_in_place(elements);
1221 }
1222 }
1223}
1224
1225impl<T: fmt::Debug, const N: usize> fmt::Debug for IntoIter<T, N> {
1226 #[inline]
1227 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1228 f.debug_list().entries(&self.vec[self.index..]).finish()
1229 }
1230}
1231
1232#[cfg(feature = "serde")]
1233mod impl_serde {
1234 use super::*;
1235 use serde::de::{Error, SeqAccess, Visitor};
1236 use serde::{Deserialize, Deserializer, Serialize, Serializer};
1237 use std::marker::PhantomData;
1238
1239 #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1240 impl<T: Serialize, const N: usize> Serialize for StackVec<T, N> {
1241 #[inline]
1242 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1243 where
1244 S: Serializer,
1245 {
1246 serializer.collect_seq(self.as_slice())
1247 }
1248 }
1249
1250 #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1251 impl<'de, T: Deserialize<'de>, const N: usize> Deserialize<'de> for StackVec<T, N> {
1252 #[inline]
1253 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1254 where
1255 D: Deserializer<'de>,
1256 {
1257 struct StackVecVisitor<'de, T: Deserialize<'de>, const N: usize>(
1258 PhantomData<(&'de (), [T; N])>,
1259 );
1260
1261 impl<'de, T: Deserialize<'de>, const N: usize> Visitor<'de> for StackVecVisitor<'de, T, N> {
1262 type Value = StackVec<T, N>;
1263
1264 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1265 write!(formatter, "an array with no more than {} items", N)
1266 }
1267
1268 #[inline]
1269 fn visit_seq<SA>(self, mut seq: SA) -> Result<Self::Value, SA::Error>
1270 where
1271 SA: SeqAccess<'de>,
1272 {
1273 let mut values = StackVec::<T, N>::new();
1274
1275 while let Some(value) = seq.next_element()? {
1276 if values.is_full() {
1277 return Err(SA::Error::invalid_length(N + 1, &self));
1278 }
1279
1280 values.push(value);
1281 }
1282
1283 Ok(values)
1284 }
1285 }
1286
1287 deserializer.deserialize_seq(StackVecVisitor::<T, N>(PhantomData))
1288 }
1289 }
1290}
1291
1292/// Creates a [`StackVec`] containing the arguments.
1293///
1294/// `stack_vec!` allows `StackVec`s to be defined with the same syntax as array expressions.
1295/// There are two forms of this macro:
1296///
1297/// - Creates a empty [`StackVec`]:
1298///
1299/// ```
1300/// use stack_buf::{StackVec, stack_vec};
1301///
1302/// let vec: StackVec<i32, 8> = stack_vec![];
1303/// assert!(vec.is_empty());
1304/// assert_eq!(vec.capacity(), 8);
1305///
1306/// let vec = stack_vec![i32; 16];
1307/// assert!(vec.is_empty());
1308/// assert_eq!(vec.capacity(), 16);
1309/// ```
1310///
1311/// - Creates a [`StackVec`] containing a given list of elements:
1312///
1313/// ```
1314/// use stack_buf::{StackVec, stack_vec};
1315///
1316/// let vec = stack_vec![128 # 1, 2, 3];
1317/// assert_eq!(vec.capacity(), 128);
1318/// assert_eq!(vec[0], 1);
1319/// assert_eq!(vec[1], 2);
1320/// assert_eq!(vec[2], 3);
1321///
1322/// let vec = stack_vec![1, 2, 3];
1323/// assert_eq!(vec.capacity(), 3);
1324///
1325/// ```
1326///
1327/// - Creates a [`StackVec`] from a given element and size:
1328///
1329/// ```
1330/// use stack_buf::{StackVec, stack_vec};
1331///
1332/// let v = stack_vec![0x8000 # 1; 3];
1333/// assert_eq!(v.as_slice(), [1, 1, 1]);
1334/// assert_eq!(v.capacity(), 0x8000);
1335///
1336/// let v = stack_vec![1; 3];
1337/// assert_eq!(v.capacity(), 3);
1338/// ```
1339///
1340/// Note that unlike array expressions this syntax supports all elements
1341/// which implement [`Clone`] and the number of elements doesn't have to be
1342/// a constant.
1343///
1344/// This will use `clone` to duplicate an expression, so one should be careful
1345/// using this with types having a nonstandard `Clone` implementation. For
1346/// example, `stack_vec![Rc::new(1); 5]` will create a vector of five references
1347/// to the same boxed integer value, not five references pointing to independently
1348/// boxed integers.
1349#[macro_export]
1350macro_rules! stack_vec {
1351 () => ($crate::StackVec::new());
1352 ($ty: ty; $cap: literal) => ($crate::StackVec::<$ty, $cap>::new());
1353 ($elem:expr; $n:expr) => ({
1354 $crate::StackVec::<_, $n>::from_elem($elem, $n)
1355 });
1356 ($cap:literal # $elem:expr; $n:expr) => ({
1357 $crate::StackVec::<_, $cap>::from_elem($elem, $n)
1358 });
1359 ($($x:expr),+ $(,)?) => ({
1360 $crate::StackVec::from([$($x),+])
1361 });
1362 ($cap:literal # $($x:expr),+ $(,)?) => ({
1363 let mut vec = $crate::StackVec::<_, $cap>::new();
1364 $(vec.push($x);)+
1365 vec
1366 });
1367}