rs_matter/utils/storage/vec.rs
1/*
2 *
3 * Copyright (c) 2024-2026 Project CHIP Authors
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18//! A modification of `heapless::Vec` that provides the following extra features:
19//! - In-place initialization of the vec itself with `Vec::init() -> impl Init<Self>`
20//! - In-place initialization of the vec members with `Vec::push_init(init: I) -> Result<(), ()>`
21
22#![allow(clippy::unnecessary_cast)]
23#![allow(clippy::redundant_slicing)]
24#![allow(clippy::result_unit_err)]
25#![allow(clippy::should_implement_trait)]
26
27use core::{
28 cmp::Ordering,
29 fmt, hash,
30 iter::FromIterator,
31 mem::MaybeUninit,
32 ops,
33 ptr::{self, addr_of_mut},
34 slice,
35};
36
37use crate::utils::init::{init_from_closure, Init, InitDefault};
38
39/// A fixed capacity [`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html)
40///
41/// # Examples
42///
43/// ```
44/// use heapless::Vec;
45///
46/// // A vector with a fixed capacity of 8 elements allocated on the stack
47/// let mut vec = Vec::<_, 8>::new();
48/// vec.push(1);
49/// vec.push(2);
50///
51/// assert_eq!(vec.len(), 2);
52/// assert_eq!(vec[0], 1);
53///
54/// assert_eq!(vec.pop(), Some(2));
55/// assert_eq!(vec.len(), 1);
56///
57/// vec[0] = 7;
58/// assert_eq!(vec[0], 7);
59///
60/// vec.extend([1, 2, 3].iter().cloned());
61///
62/// for x in &vec {
63/// println!("{}", x);
64/// }
65/// assert_eq!(*vec, [7, 1, 2, 3]);
66/// ```
67pub struct Vec<T, const N: usize> {
68 // NOTE order is important for optimizations. the `len` first layout lets the compiler optimize
69 // `new` to: reserve stack space and zero the first word. With the fields in the reverse order
70 // the compiler optimizes `new` to `memclr`-ing the *entire* stack space, including the `buffer`
71 // field which should be left uninitialized. Optimizations were last checked with Rust 1.60
72 len: usize,
73
74 buffer: [MaybeUninit<T>; N],
75}
76
77impl<T, const N: usize> Vec<T, N> {
78 const ELEM: MaybeUninit<T> = MaybeUninit::uninit();
79 const INIT: [MaybeUninit<T>; N] = [Self::ELEM; N]; // important for optimization of `new`
80
81 /// Constructs a new, empty vector with a fixed capacity of `N`
82 ///
83 /// # Examples
84 ///
85 /// ```
86 /// use heapless::Vec;
87 ///
88 /// // allocate the vector on the stack
89 /// let mut x: Vec<u8, 16> = Vec::new();
90 ///
91 /// // allocate the vector in a static variable
92 /// static mut X: Vec<u8, 16> = Vec::new();
93 /// ```
94 /// `Vec` `const` constructor; wrap the returned value in [`Vec`].
95 pub const fn new() -> Self {
96 Self {
97 len: 0,
98 buffer: Self::INIT,
99 }
100 }
101
102 /// Returns an in-place initializer for a new, empty vector.
103 pub fn init() -> impl Init<Self> {
104 unsafe {
105 init_from_closure(move |slot: *mut Self| {
106 addr_of_mut!((*slot).len).write(0);
107
108 Ok(())
109 })
110 }
111 }
112
113 /// Constructs a new vector with a fixed capacity of `N` and fills it
114 ///
115 /// This is equivalent to the following code:
116 ///
117 /// ```
118 /// use heapless::Vec;
119 ///
120 /// let mut v: Vec<u8, 16> = Vec::new();
121 /// v.extend_from_slice(&[1, 2, 3]).unwrap();
122 /// ```
123 #[inline]
124 pub fn from_slice(other: &[T]) -> Result<Self, ()>
125 where
126 T: Clone,
127 {
128 let mut v = Vec::new();
129 v.extend_from_slice(other)?;
130 Ok(v)
131 }
132
133 /// Clones a vec into a new vec
134 pub(crate) fn clone(&self) -> Self
135 where
136 T: Clone,
137 {
138 let mut new = Self::new();
139 // avoid `extend_from_slice` as that introduces a runtime check / panicking branch
140 for elem in self {
141 unsafe {
142 new.push_unchecked(elem.clone());
143 }
144 }
145 new
146 }
147
148 /// Returns a raw pointer to the vector’s buffer.
149 pub fn as_ptr(&self) -> *const T {
150 self.buffer.as_ptr() as *const T
151 }
152
153 /// Returns a raw pointer to the vector’s buffer, which may be mutated through.
154 pub fn as_mut_ptr(&mut self) -> *mut T {
155 self.buffer.as_mut_ptr() as *mut T
156 }
157
158 /// Extracts a slice containing the entire vector.
159 ///
160 /// Equivalent to `&s[..]`.
161 ///
162 /// # Examples
163 ///
164 /// ```
165 /// use heapless::Vec;
166 /// let buffer: Vec<u8, 5> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
167 /// assert_eq!(buffer.as_slice(), &[1, 2, 3, 5, 8]);
168 /// ```
169 pub fn as_slice(&self) -> &[T] {
170 // NOTE(unsafe) avoid bound checks in the slicing operation
171 // &buffer[..self.len]
172 unsafe { slice::from_raw_parts(self.buffer.as_ptr() as *const T, self.len) }
173 }
174
175 /// Returns the contents of the vector as an array of length `M` if the length
176 /// of the vector is exactly `M`, otherwise returns `Err(self)`.
177 ///
178 /// # Examples
179 ///
180 /// ```
181 /// use heapless::Vec;
182 /// let buffer: Vec<u8, 42> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
183 /// let array: [u8; 5] = buffer.into_array().unwrap();
184 /// assert_eq!(array, [1, 2, 3, 5, 8]);
185 /// ```
186 pub fn into_array<const M: usize>(self) -> Result<[T; M], Self> {
187 if self.len() == M {
188 // This is how the unstable `MaybeUninit::array_assume_init` method does it
189 let array = unsafe { (&self.buffer as *const _ as *const [T; M]).read() };
190
191 // We don't want `self`'s destructor to be called because that would drop all the
192 // items in the array
193 core::mem::forget(self);
194
195 Ok(array)
196 } else {
197 Err(self)
198 }
199 }
200
201 /// Extracts a mutable slice containing the entire vector.
202 ///
203 /// Equivalent to `&mut s[..]`.
204 ///
205 /// # Examples
206 ///
207 /// ```
208 /// use heapless::Vec;
209 /// let mut buffer: Vec<u8, 5> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
210 /// buffer[0] = 9;
211 /// assert_eq!(buffer.as_slice(), &[9, 2, 3, 5, 8]);
212 /// ```
213 pub fn as_mut_slice(&mut self) -> &mut [T] {
214 // NOTE(unsafe) avoid bound checks in the slicing operation
215 // &mut buffer[..self.len]
216 unsafe { slice::from_raw_parts_mut(self.buffer.as_mut_ptr() as *mut T, self.len) }
217 }
218
219 /// Returns the maximum number of elements the vector can hold.
220 pub const fn capacity(&self) -> usize {
221 N
222 }
223
224 /// Clears the vector, removing all values.
225 pub fn clear(&mut self) {
226 self.truncate(0);
227 }
228
229 /// Extends the vec from an iterator.
230 ///
231 /// # Panic
232 ///
233 /// Panics if the vec cannot hold all elements of the iterator.
234 pub fn extend<I>(&mut self, iter: I)
235 where
236 I: IntoIterator<Item = T>,
237 {
238 for elem in iter {
239 self.push(elem).ok().unwrap()
240 }
241 }
242
243 /// Clones and appends all elements in a slice to the `Vec`.
244 ///
245 /// Iterates over the slice `other`, clones each element, and then appends
246 /// it to this `Vec`. The `other` vector is traversed in-order.
247 ///
248 /// # Examples
249 ///
250 /// ```
251 /// use heapless::Vec;
252 ///
253 /// let mut vec = Vec::<u8, 8>::new();
254 /// vec.push(1).unwrap();
255 /// vec.extend_from_slice(&[2, 3, 4]).unwrap();
256 /// assert_eq!(*vec, [1, 2, 3, 4]);
257 /// ```
258 pub fn extend_from_slice(&mut self, other: &[T]) -> Result<(), ()>
259 where
260 T: Clone,
261 {
262 if self.len + other.len() > self.capacity() {
263 // won't fit in the `Vec`; don't modify anything and return an error
264 Err(())
265 } else {
266 for elem in other {
267 unsafe {
268 self.push_unchecked(elem.clone());
269 }
270 }
271 Ok(())
272 }
273 }
274
275 /// Removes the last element from a vector and returns it, or `None` if it's empty
276 pub fn pop(&mut self) -> Option<T> {
277 if self.len != 0 {
278 Some(unsafe { self.pop_unchecked() })
279 } else {
280 None
281 }
282 }
283
284 /// Appends an `item` to the back of the collection
285 ///
286 /// Returns back the `item` if the vector is full
287 pub fn push(&mut self, item: T) -> Result<(), T> {
288 if self.len < self.capacity() {
289 unsafe { self.push_unchecked(item) }
290 Ok(())
291 } else {
292 Err(item)
293 }
294 }
295
296 /// Appends an item with the provided item initializer - `init`
297 /// to the back of the collection
298 ///
299 /// Returns an error generated by `f` if the vector is full
300 pub fn push_init<I: Init<T, E>, E, F: FnOnce() -> E>(
301 &mut self,
302 init: I,
303 f: F,
304 ) -> Result<(), E> {
305 if self.len < self.capacity() {
306 self.push_init_unchecked(init)
307 } else {
308 Err(f())
309 }
310 }
311
312 /// Removes the last element from a vector and returns it
313 ///
314 /// # Safety
315 ///
316 /// This assumes the vec to have at least one element.
317 pub unsafe fn pop_unchecked(&mut self) -> T {
318 debug_assert!(!self.is_empty());
319
320 self.len -= 1;
321 (self.buffer.get_unchecked_mut(self.len).as_ptr() as *const T).read()
322 }
323
324 /// Appends an `item` to the back of the collection
325 ///
326 /// # Safety
327 ///
328 /// This assumes the vec is not full.
329 pub unsafe fn push_unchecked(&mut self, item: T) {
330 // NOTE(ptr::write) the memory slot that we are about to write to is uninitialized. We
331 // use `ptr::write` to avoid running `T`'s destructor on the uninitialized memory
332 debug_assert!(!self.is_full());
333
334 *self.buffer.get_unchecked_mut(self.len) = MaybeUninit::new(item);
335
336 self.len += 1;
337 }
338
339 /// Appends an item with the provided item initializer - `init`
340 /// to the back of the collection
341 ///
342 /// Panics if the vec is full.
343 pub fn push_init_unchecked<I: Init<T, E>, E>(&mut self, init: I) -> Result<(), E> {
344 if self.is_full() {
345 panic!("Vec::push_init_unchecked: vec is full");
346 }
347
348 unsafe {
349 // NOTE(ptr::write) the memory slot that we are about to write to is uninitialized. We
350 // use `ptr::write` to avoid running `T`'s destructor on the uninitialized memory
351 let buffer: *mut T = self.buffer.as_mut_ptr().add(self.len) as _;
352
353 init.__init(buffer)?;
354 }
355
356 self.len += 1;
357
358 Ok(())
359 }
360
361 /// Shortens the vector, keeping the first `len` elements and dropping the rest.
362 pub fn truncate(&mut self, len: usize) {
363 // This is safe because:
364 //
365 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
366 // case avoids creating an invalid slice, and
367 // * the `len` of the vector is shrunk before calling `drop_in_place`,
368 // such that no value will be dropped twice in case `drop_in_place`
369 // were to panic once (if it panics twice, the program aborts).
370 unsafe {
371 // Note: It's intentional that this is `>` and not `>=`.
372 // Changing it to `>=` has negative performance
373 // implications in some cases. See rust-lang/rust#78884 for more.
374 if len > self.len {
375 return;
376 }
377 let remaining_len = self.len - len;
378 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
379 self.len = len;
380 ptr::drop_in_place(s);
381 }
382 }
383
384 /// Resizes the Vec in-place so that len is equal to new_len.
385 ///
386 /// If new_len is greater than len, the Vec is extended by the
387 /// difference, with each additional slot filled with value. If
388 /// new_len is less than len, the Vec is simply truncated.
389 ///
390 /// See also [`resize_default`](Self::resize_default).
391 pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), ()>
392 where
393 T: Clone,
394 {
395 if new_len > self.capacity() {
396 return Err(());
397 }
398
399 if new_len > self.len {
400 while self.len < new_len {
401 self.push(value.clone()).ok();
402 }
403 } else {
404 self.truncate(new_len);
405 }
406
407 Ok(())
408 }
409
410 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
411 ///
412 /// If `new_len` is greater than `len`, the `Vec` is extended by the
413 /// difference, with each additional slot filled with `Default::default()`.
414 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
415 ///
416 /// See also [`resize`](Self::resize).
417 pub fn resize_default(&mut self, new_len: usize) -> Result<(), ()>
418 where
419 T: Clone + Default,
420 {
421 self.resize(new_len, T::default())
422 }
423
424 /// Forces the length of the vector to `new_len`.
425 ///
426 /// This is a low-level operation that maintains none of the normal
427 /// invariants of the type. Normally changing the length of a vector
428 /// is done using one of the safe operations instead, such as
429 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
430 ///
431 /// [`truncate`]: Self::truncate
432 /// [`resize`]: Self::resize
433 /// [`extend`]: core::iter::Extend
434 /// [`clear`]: Self::clear
435 ///
436 /// # Safety
437 ///
438 /// - `new_len` must be less than or equal to [`capacity()`].
439 /// - The elements at `old_len..new_len` must be initialized.
440 ///
441 /// [`capacity()`]: Self::capacity
442 ///
443 /// # Examples
444 ///
445 /// This method can be useful for situations in which the vector
446 /// is serving as a buffer for other code, particularly over FFI:
447 ///
448 /// ```no_run
449 /// # #![allow(dead_code)]
450 /// use heapless::Vec;
451 ///
452 /// # // This is just a minimal skeleton for the doc example;
453 /// # // don't use this as a starting point for a real library.
454 /// # pub struct StreamWrapper { strm: *mut core::ffi::c_void }
455 /// # const Z_OK: i32 = 0;
456 /// # extern "C" {
457 /// # fn deflateGetDictionary(
458 /// # strm: *mut core::ffi::c_void,
459 /// # dictionary: *mut u8,
460 /// # dictLength: *mut usize,
461 /// # ) -> i32;
462 /// # }
463 /// # impl StreamWrapper {
464 /// pub fn get_dictionary(&self) -> Option<Vec<u8, 32768>> {
465 /// // Per the FFI method's docs, "32768 bytes is always enough".
466 /// let mut dict = Vec::new();
467 /// let mut dict_length = 0;
468 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
469 /// // 1. `dict_length` elements were initialized.
470 /// // 2. `dict_length` <= the capacity (32_768)
471 /// // which makes `set_len` safe to call.
472 /// unsafe {
473 /// // Make the FFI call...
474 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
475 /// if r == Z_OK {
476 /// // ...and update the length to what was initialized.
477 /// dict.set_len(dict_length);
478 /// Some(dict)
479 /// } else {
480 /// None
481 /// }
482 /// }
483 /// }
484 /// # }
485 /// ```
486 ///
487 /// While the following example is sound, there is a memory leak since
488 /// the inner vectors were not freed prior to the `set_len` call:
489 ///
490 /// ```
491 /// use core::iter::FromIterator;
492 /// use heapless::Vec;
493 ///
494 /// let mut vec = Vec::<Vec<u8, 3>, 3>::from_iter(
495 /// [
496 /// Vec::from_iter([1, 0, 0].iter().cloned()),
497 /// Vec::from_iter([0, 1, 0].iter().cloned()),
498 /// Vec::from_iter([0, 0, 1].iter().cloned()),
499 /// ]
500 /// .iter()
501 /// .cloned()
502 /// );
503 /// // SAFETY:
504 /// // 1. `old_len..0` is empty so no elements need to be initialized.
505 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
506 /// unsafe {
507 /// vec.set_len(0);
508 /// }
509 /// ```
510 ///
511 /// Normally, here, one would use [`clear`] instead to correctly drop
512 /// the contents and thus not leak memory.
513 pub unsafe fn set_len(&mut self, new_len: usize) {
514 debug_assert!(new_len <= self.capacity());
515
516 self.len = new_len
517 }
518
519 /// Removes an element from the vector and returns it.
520 ///
521 /// The removed element is replaced by the last element of the vector.
522 ///
523 /// This does not preserve ordering, but is O(1).
524 ///
525 /// # Panics
526 ///
527 /// Panics if `index` is out of bounds.
528 ///
529 /// # Examples
530 ///
531 /// ```
532 /// use heapless::Vec;
533 ///// use heapless::consts::*;
534 ///
535 /// let mut v: Vec<_, 8> = Vec::new();
536 /// v.push("foo").unwrap();
537 /// v.push("bar").unwrap();
538 /// v.push("baz").unwrap();
539 /// v.push("qux").unwrap();
540 ///
541 /// assert_eq!(v.swap_remove(1), "bar");
542 /// assert_eq!(&*v, ["foo", "qux", "baz"]);
543 ///
544 /// assert_eq!(v.swap_remove(0), "foo");
545 /// assert_eq!(&*v, ["baz", "qux"]);
546 /// ```
547 pub fn swap_remove(&mut self, index: usize) -> T {
548 assert!(index < self.len);
549 unsafe { self.swap_remove_unchecked(index) }
550 }
551
552 /// Removes an element from the vector and returns it.
553 ///
554 /// The removed element is replaced by the last element of the vector.
555 ///
556 /// This does not preserve ordering, but is O(1).
557 ///
558 /// # Safety
559 ///
560 /// Assumes `index` within bounds.
561 ///
562 /// # Examples
563 ///
564 /// ```
565 /// use heapless::Vec;
566 ///
567 /// let mut v: Vec<_, 8> = Vec::new();
568 /// v.push("foo").unwrap();
569 /// v.push("bar").unwrap();
570 /// v.push("baz").unwrap();
571 /// v.push("qux").unwrap();
572 ///
573 /// assert_eq!(unsafe { v.swap_remove_unchecked(1) }, "bar");
574 /// assert_eq!(&*v, ["foo", "qux", "baz"]);
575 ///
576 /// assert_eq!(unsafe { v.swap_remove_unchecked(0) }, "foo");
577 /// assert_eq!(&*v, ["baz", "qux"]);
578 /// ```
579 pub unsafe fn swap_remove_unchecked(&mut self, index: usize) -> T {
580 let length = self.len();
581 debug_assert!(index < length);
582 let value = ptr::read(self.as_ptr().add(index));
583 let base_ptr = self.as_mut_ptr();
584 ptr::copy(base_ptr.add(length - 1), base_ptr.add(index), 1);
585 self.len -= 1;
586 value
587 }
588
589 /// Returns true if the vec is full
590 #[inline]
591 pub fn is_full(&self) -> bool {
592 self.len == self.capacity()
593 }
594
595 /// Returns true if the vec is empty
596 #[inline]
597 pub fn is_empty(&self) -> bool {
598 self.len == 0
599 }
600
601 /// Returns `true` if `needle` is a prefix of the Vec.
602 ///
603 /// Always returns `true` if `needle` is an empty slice.
604 ///
605 /// # Examples
606 ///
607 /// ```
608 /// use heapless::Vec;
609 ///
610 /// let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
611 /// assert_eq!(v.starts_with(b""), true);
612 /// assert_eq!(v.starts_with(b"ab"), true);
613 /// assert_eq!(v.starts_with(b"bc"), false);
614 /// ```
615 #[inline]
616 pub fn starts_with(&self, needle: &[T]) -> bool
617 where
618 T: PartialEq,
619 {
620 let n = needle.len();
621 self.len >= n && needle == &self[..n]
622 }
623
624 /// Returns `true` if `needle` is a suffix of the Vec.
625 ///
626 /// Always returns `true` if `needle` is an empty slice.
627 ///
628 /// # Examples
629 ///
630 /// ```
631 /// use heapless::Vec;
632 ///
633 /// let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
634 /// assert_eq!(v.ends_with(b""), true);
635 /// assert_eq!(v.ends_with(b"ab"), false);
636 /// assert_eq!(v.ends_with(b"bc"), true);
637 /// ```
638 #[inline]
639 pub fn ends_with(&self, needle: &[T]) -> bool
640 where
641 T: PartialEq,
642 {
643 let (v, n) = (self.len(), needle.len());
644 v >= n && needle == &self[v - n..]
645 }
646
647 /// Inserts an element at position `index` within the vector, shifting all
648 /// elements after it to the right.
649 ///
650 /// Returns back the `element` if the vector is full.
651 ///
652 /// # Panics
653 ///
654 /// Panics if `index > len`.
655 ///
656 /// # Examples
657 ///
658 /// ```
659 /// use heapless::Vec;
660 ///
661 /// let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3]).unwrap();
662 /// vec.insert(1, 4);
663 /// assert_eq!(vec, [1, 4, 2, 3]);
664 /// vec.insert(4, 5);
665 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
666 /// ```
667 pub fn insert(&mut self, index: usize, element: T) -> Result<(), T> {
668 let len = self.len();
669 if index > len {
670 panic!(
671 "insertion index (is {}) should be <= len (is {})",
672 index, len
673 );
674 }
675
676 // check there's space for the new element
677 if self.is_full() {
678 return Err(element);
679 }
680
681 unsafe {
682 // infallible
683 // The spot to put the new value
684 {
685 let p = self.as_mut_ptr().add(index);
686 // Shift everything over to make space. (Duplicating the
687 // `index`th element into two consecutive places.)
688 ptr::copy(p, p.offset(1), len - index);
689 // Write it in, overwriting the first copy of the `index`th
690 // element.
691 ptr::write(p, element);
692 }
693 self.set_len(len + 1);
694 }
695
696 Ok(())
697 }
698
699 /// Removes and returns the element at position `index` within the vector,
700 /// shifting all elements after it to the left.
701 ///
702 /// Note: Because this shifts over the remaining elements, it has a
703 /// worst-case performance of *O*(*n*). If you don't need the order of
704 /// elements to be preserved, use [`swap_remove`] instead. If you'd like to
705 /// remove elements from the beginning of the `Vec`, consider using
706 /// [`Deque::pop_front`] instead.
707 ///
708 /// [`swap_remove`]: Vec::swap_remove
709 /// [`Deque::pop_front`]: crate::Deque::pop_front
710 ///
711 /// # Panics
712 ///
713 /// Panics if `index` is out of bounds.
714 ///
715 /// # Examples
716 ///
717 /// ```
718 /// use heapless::Vec;
719 ///
720 /// let mut v: Vec<_, 8> = Vec::from_slice(&[1, 2, 3]).unwrap();
721 /// assert_eq!(v.remove(1), 2);
722 /// assert_eq!(v, [1, 3]);
723 /// ```
724 pub fn remove(&mut self, index: usize) -> T {
725 let len = self.len();
726 if index >= len {
727 panic!("removal index (is {}) should be < len (is {})", index, len);
728 }
729 unsafe {
730 // infallible
731 let ret;
732 {
733 // the place we are taking from.
734 let ptr = self.as_mut_ptr().add(index);
735 // copy it out, unsafely having a copy of the value on
736 // the stack and in the vector at the same time.
737 ret = ptr::read(ptr);
738
739 // Shift everything down to fill in that spot.
740 ptr::copy(ptr.offset(1), ptr, len - index - 1);
741 }
742 self.set_len(len - 1);
743 ret
744 }
745 }
746
747 /// Retains only the elements specified by the predicate.
748 ///
749 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
750 /// This method operates in place, visiting each element exactly once in the
751 /// original order, and preserves the order of the retained elements.
752 ///
753 /// # Examples
754 ///
755 /// ```
756 /// use heapless::Vec;
757 ///
758 /// let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
759 /// vec.retain(|&x| x % 2 == 0);
760 /// assert_eq!(vec, [2, 4]);
761 /// ```
762 ///
763 /// Because the elements are visited exactly once in the original order,
764 /// external state may be used to decide which elements to keep.
765 ///
766 /// ```
767 /// use heapless::Vec;
768 ///
769 /// let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4, 5]).unwrap();
770 /// let keep = [false, true, true, false, true];
771 /// let mut iter = keep.iter();
772 /// vec.retain(|_| *iter.next().unwrap());
773 /// assert_eq!(vec, [2, 3, 5]);
774 /// ```
775 pub fn retain<F>(&mut self, mut f: F)
776 where
777 F: FnMut(&T) -> bool,
778 {
779 self.retain_mut(|elem| f(elem));
780 }
781
782 /// Retains only the elements specified by the predicate, passing a mutable reference to it.
783 ///
784 /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
785 /// This method operates in place, visiting each element exactly once in the
786 /// original order, and preserves the order of the retained elements.
787 ///
788 /// # Examples
789 ///
790 /// ```
791 /// use heapless::Vec;
792 ///
793 /// let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
794 /// vec.retain_mut(|x| if *x <= 3 {
795 /// *x += 1;
796 /// true
797 /// } else {
798 /// false
799 /// });
800 /// assert_eq!(vec, [2, 3, 4]);
801 /// ```
802 pub fn retain_mut<F>(&mut self, mut f: F)
803 where
804 F: FnMut(&mut T) -> bool,
805 {
806 let original_len = self.len();
807 // Avoid double drop if the drop guard is not executed,
808 // since we may make some holes during the process.
809 unsafe { self.set_len(0) };
810
811 // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
812 // |<- processed len ->| ^- next to check
813 // |<- deleted cnt ->|
814 // |<- original_len ->|
815 // Kept: Elements which predicate returns true on.
816 // Hole: Moved or dropped element slot.
817 // Unchecked: Unchecked valid elements.
818 //
819 // This drop guard will be invoked when predicate or `drop` of element panicked.
820 // It shifts unchecked elements to cover holes and `set_len` to the correct length.
821 // In cases when predicate and `drop` never panick, it will be optimized out.
822 struct BackshiftOnDrop<'a, T, const N: usize> {
823 v: &'a mut Vec<T, N>,
824 processed_len: usize,
825 deleted_cnt: usize,
826 original_len: usize,
827 }
828
829 impl<T, const N: usize> Drop for BackshiftOnDrop<'_, T, N> {
830 fn drop(&mut self) {
831 if self.deleted_cnt > 0 {
832 // SAFETY: Trailing unchecked items must be valid since we never touch them.
833 unsafe {
834 ptr::copy(
835 self.v.as_ptr().add(self.processed_len),
836 self.v
837 .as_mut_ptr()
838 .add(self.processed_len - self.deleted_cnt),
839 self.original_len - self.processed_len,
840 );
841 }
842 }
843 // SAFETY: After filling holes, all items are in contiguous memory.
844 unsafe {
845 self.v.set_len(self.original_len - self.deleted_cnt);
846 }
847 }
848 }
849
850 let mut g = BackshiftOnDrop {
851 v: self,
852 processed_len: 0,
853 deleted_cnt: 0,
854 original_len,
855 };
856
857 fn process_loop<F, T, const N: usize, const DELETED: bool>(
858 original_len: usize,
859 f: &mut F,
860 g: &mut BackshiftOnDrop<'_, T, N>,
861 ) where
862 F: FnMut(&mut T) -> bool,
863 {
864 while g.processed_len != original_len {
865 let p = g.v.as_mut_ptr();
866 // SAFETY: Unchecked element must be valid.
867 let cur = unsafe { &mut *p.add(g.processed_len) };
868 if !f(cur) {
869 // Advance early to avoid double drop if `drop_in_place` panicked.
870 g.processed_len += 1;
871 g.deleted_cnt += 1;
872 // SAFETY: We never touch this element again after dropped.
873 unsafe { ptr::drop_in_place(cur) };
874 // We already advanced the counter.
875 if DELETED {
876 continue;
877 } else {
878 break;
879 }
880 }
881 if DELETED {
882 // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element.
883 // We use copy for move, and never touch this element again.
884 unsafe {
885 let hole_slot = p.add(g.processed_len - g.deleted_cnt);
886 ptr::copy_nonoverlapping(cur, hole_slot, 1);
887 }
888 }
889 g.processed_len += 1;
890 }
891 }
892
893 // Stage 1: Nothing was deleted.
894 process_loop::<F, T, N, false>(original_len, &mut f, &mut g);
895
896 // Stage 2: Some elements were deleted.
897 process_loop::<F, T, N, true>(original_len, &mut f, &mut g);
898
899 // All item are processed. This can be optimized to `set_len` by LLVM.
900 drop(g);
901 }
902}
903
904// Trait implementations
905
906impl<T, const N: usize> Default for Vec<T, N> {
907 fn default() -> Self {
908 Self::new()
909 }
910}
911
912impl<T, const N: usize> InitDefault for Vec<T, N> {
913 fn init_default() -> impl Init<Self> {
914 Self::init()
915 }
916}
917
918impl<T, const N: usize> fmt::Debug for Vec<T, N>
919where
920 T: fmt::Debug,
921{
922 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
923 <[T] as fmt::Debug>::fmt(self, f)
924 }
925}
926
927#[cfg(feature = "defmt")]
928impl<T, const N: usize> defmt::Format for Vec<T, N>
929where
930 T: defmt::Format,
931{
932 fn format(&self, f: defmt::Formatter<'_>) {
933 <[T] as defmt::Format>::format(self, f)
934 }
935}
936
937impl<const N: usize> fmt::Write for Vec<u8, N> {
938 fn write_str(&mut self, s: &str) -> fmt::Result {
939 match self.extend_from_slice(s.as_bytes()) {
940 Ok(()) => Ok(()),
941 Err(_) => Err(fmt::Error),
942 }
943 }
944}
945
946impl<T, const N: usize> Drop for Vec<T, N> {
947 fn drop(&mut self) {
948 // We drop each element used in the vector by turning into a &mut[T]
949 unsafe {
950 ptr::drop_in_place(self.as_mut_slice());
951 }
952 }
953}
954
955impl<'a, T: Clone, const N: usize> TryFrom<&'a [T]> for Vec<T, N> {
956 type Error = ();
957
958 fn try_from(slice: &'a [T]) -> Result<Self, Self::Error> {
959 Vec::from_slice(slice)
960 }
961}
962
963impl<T, const N: usize> Extend<T> for Vec<T, N> {
964 fn extend<I>(&mut self, iter: I)
965 where
966 I: IntoIterator<Item = T>,
967 {
968 self.extend(iter)
969 }
970}
971
972impl<'a, T, const N: usize> Extend<&'a T> for Vec<T, N>
973where
974 T: 'a + Copy,
975{
976 fn extend<I>(&mut self, iter: I)
977 where
978 I: IntoIterator<Item = &'a T>,
979 {
980 self.extend(iter.into_iter().cloned())
981 }
982}
983
984impl<T, const N: usize> hash::Hash for Vec<T, N>
985where
986 T: core::hash::Hash,
987{
988 fn hash<H: hash::Hasher>(&self, state: &mut H) {
989 <[T] as hash::Hash>::hash(self, state)
990 }
991}
992
993impl<'a, T, const N: usize> IntoIterator for &'a Vec<T, N> {
994 type Item = &'a T;
995 type IntoIter = slice::Iter<'a, T>;
996
997 fn into_iter(self) -> Self::IntoIter {
998 self.iter()
999 }
1000}
1001
1002impl<'a, T, const N: usize> IntoIterator for &'a mut Vec<T, N> {
1003 type Item = &'a mut T;
1004 type IntoIter = slice::IterMut<'a, T>;
1005
1006 fn into_iter(self) -> Self::IntoIter {
1007 self.iter_mut()
1008 }
1009}
1010
1011impl<T, const N: usize> FromIterator<T> for Vec<T, N> {
1012 fn from_iter<I>(iter: I) -> Self
1013 where
1014 I: IntoIterator<Item = T>,
1015 {
1016 let mut vec = Vec::new();
1017 for i in iter {
1018 unwrap!(vec.push(i).ok(), "Vec::from_iter overflow");
1019 }
1020 vec
1021 }
1022}
1023
1024/// An iterator that moves out of an [`Vec`][`Vec`].
1025///
1026/// This struct is created by calling the `into_iter` method on [`Vec`][`Vec`].
1027pub struct IntoIter<T, const N: usize> {
1028 vec: Vec<T, N>,
1029 next: usize,
1030}
1031
1032impl<T, const N: usize> Iterator for IntoIter<T, N> {
1033 type Item = T;
1034 fn next(&mut self) -> Option<Self::Item> {
1035 if self.next < self.vec.len() {
1036 let item = unsafe {
1037 (self.vec.buffer.get_unchecked_mut(self.next).as_ptr() as *const T).read()
1038 };
1039 self.next += 1;
1040 Some(item)
1041 } else {
1042 None
1043 }
1044 }
1045}
1046
1047impl<T, const N: usize> Clone for IntoIter<T, N>
1048where
1049 T: Clone,
1050{
1051 fn clone(&self) -> Self {
1052 let mut vec = Vec::new();
1053
1054 if self.next < self.vec.len() {
1055 let s = unsafe {
1056 slice::from_raw_parts(
1057 (self.vec.buffer.as_ptr() as *const T).add(self.next),
1058 self.vec.len() - self.next,
1059 )
1060 };
1061 vec.extend_from_slice(s).ok();
1062 }
1063
1064 Self { vec, next: 0 }
1065 }
1066}
1067
1068impl<T, const N: usize> Drop for IntoIter<T, N> {
1069 fn drop(&mut self) {
1070 unsafe {
1071 // Drop all the elements that have not been moved out of vec
1072 ptr::drop_in_place(&mut self.vec.as_mut_slice()[self.next..]);
1073 // Prevent dropping of other elements
1074 self.vec.len = 0;
1075 }
1076 }
1077}
1078
1079impl<T, const N: usize> IntoIterator for Vec<T, N> {
1080 type Item = T;
1081 type IntoIter = IntoIter<T, N>;
1082
1083 fn into_iter(self) -> Self::IntoIter {
1084 IntoIter { vec: self, next: 0 }
1085 }
1086}
1087
1088impl<A, B, const N1: usize, const N2: usize> PartialEq<Vec<B, N2>> for Vec<A, N1>
1089where
1090 A: PartialEq<B>,
1091{
1092 fn eq(&self, other: &Vec<B, N2>) -> bool {
1093 <[A]>::eq(self, &**other)
1094 }
1095}
1096
1097// Vec<A, N> == [B]
1098impl<A, B, const N: usize> PartialEq<[B]> for Vec<A, N>
1099where
1100 A: PartialEq<B>,
1101{
1102 fn eq(&self, other: &[B]) -> bool {
1103 <[A]>::eq(self, &other[..])
1104 }
1105}
1106
1107// [B] == Vec<A, N>
1108impl<A, B, const N: usize> PartialEq<Vec<A, N>> for [B]
1109where
1110 A: PartialEq<B>,
1111{
1112 fn eq(&self, other: &Vec<A, N>) -> bool {
1113 <[A]>::eq(other, &self[..])
1114 }
1115}
1116
1117// Vec<A, N> == &[B]
1118impl<A, B, const N: usize> PartialEq<&[B]> for Vec<A, N>
1119where
1120 A: PartialEq<B>,
1121{
1122 fn eq(&self, other: &&[B]) -> bool {
1123 <[A]>::eq(self, &other[..])
1124 }
1125}
1126
1127// &[B] == Vec<A, N>
1128impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &[B]
1129where
1130 A: PartialEq<B>,
1131{
1132 fn eq(&self, other: &Vec<A, N>) -> bool {
1133 <[A]>::eq(other, &self[..])
1134 }
1135}
1136
1137// Vec<A, N> == &mut [B]
1138impl<A, B, const N: usize> PartialEq<&mut [B]> for Vec<A, N>
1139where
1140 A: PartialEq<B>,
1141{
1142 fn eq(&self, other: &&mut [B]) -> bool {
1143 <[A]>::eq(self, &other[..])
1144 }
1145}
1146
1147// &mut [B] == Vec<A, N>
1148impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &mut [B]
1149where
1150 A: PartialEq<B>,
1151{
1152 fn eq(&self, other: &Vec<A, N>) -> bool {
1153 <[A]>::eq(other, &self[..])
1154 }
1155}
1156
1157// Vec<A, N> == [B; M]
1158// Equality does not require equal capacity
1159impl<A, B, const N: usize, const M: usize> PartialEq<[B; M]> for Vec<A, N>
1160where
1161 A: PartialEq<B>,
1162{
1163 fn eq(&self, other: &[B; M]) -> bool {
1164 <[A]>::eq(self, &other[..])
1165 }
1166}
1167
1168// [B; M] == Vec<A, N>
1169// Equality does not require equal capacity
1170impl<A, B, const N: usize, const M: usize> PartialEq<Vec<A, N>> for [B; M]
1171where
1172 A: PartialEq<B>,
1173{
1174 fn eq(&self, other: &Vec<A, N>) -> bool {
1175 <[A]>::eq(other, &self[..])
1176 }
1177}
1178
1179// Vec<A, N> == &[B; M]
1180// Equality does not require equal capacity
1181impl<A, B, const N: usize, const M: usize> PartialEq<&[B; M]> for Vec<A, N>
1182where
1183 A: PartialEq<B>,
1184{
1185 fn eq(&self, other: &&[B; M]) -> bool {
1186 <[A]>::eq(self, &other[..])
1187 }
1188}
1189
1190// &[B; M] == Vec<A, N>
1191// Equality does not require equal capacity
1192impl<A, B, const N: usize, const M: usize> PartialEq<Vec<A, N>> for &[B; M]
1193where
1194 A: PartialEq<B>,
1195{
1196 fn eq(&self, other: &Vec<A, N>) -> bool {
1197 <[A]>::eq(other, &self[..])
1198 }
1199}
1200
1201// Implements Eq if underlying data is Eq
1202impl<T, const N: usize> Eq for Vec<T, N> where T: Eq {}
1203
1204impl<T, const N1: usize, const N2: usize> PartialOrd<Vec<T, N2>> for Vec<T, N1>
1205where
1206 T: PartialOrd,
1207{
1208 fn partial_cmp(&self, other: &Vec<T, N2>) -> Option<Ordering> {
1209 PartialOrd::partial_cmp(&**self, &**other)
1210 }
1211}
1212
1213impl<T, const N: usize> Ord for Vec<T, N>
1214where
1215 T: Ord,
1216{
1217 #[inline]
1218 fn cmp(&self, other: &Self) -> Ordering {
1219 Ord::cmp(&**self, &**other)
1220 }
1221}
1222
1223impl<T, const N: usize> ops::Deref for Vec<T, N> {
1224 type Target = [T];
1225
1226 fn deref(&self) -> &[T] {
1227 self.as_slice()
1228 }
1229}
1230
1231impl<T, const N: usize> ops::DerefMut for Vec<T, N> {
1232 fn deref_mut(&mut self) -> &mut [T] {
1233 self.as_mut_slice()
1234 }
1235}
1236
1237impl<T, const N: usize> AsRef<Vec<T, N>> for Vec<T, N> {
1238 #[inline]
1239 fn as_ref(&self) -> &Self {
1240 self
1241 }
1242}
1243
1244impl<T, const N: usize> AsMut<Vec<T, N>> for Vec<T, N> {
1245 #[inline]
1246 fn as_mut(&mut self) -> &mut Self {
1247 self
1248 }
1249}
1250
1251impl<T, const N: usize> AsRef<[T]> for Vec<T, N> {
1252 #[inline]
1253 fn as_ref(&self) -> &[T] {
1254 self
1255 }
1256}
1257
1258impl<T, const N: usize> AsMut<[T]> for Vec<T, N> {
1259 #[inline]
1260 fn as_mut(&mut self) -> &mut [T] {
1261 self
1262 }
1263}
1264
1265impl<T, const N: usize> Clone for Vec<T, N>
1266where
1267 T: Clone,
1268{
1269 fn clone(&self) -> Self {
1270 self.clone()
1271 }
1272}
1273
1274#[cfg(test)]
1275mod tests {
1276 use core::fmt::Write;
1277
1278 use super::Vec;
1279
1280 macro_rules! droppable {
1281 () => {
1282 static COUNT: core::sync::atomic::AtomicI32 = core::sync::atomic::AtomicI32::new(0);
1283
1284 #[derive(Eq, Ord, PartialEq, PartialOrd)]
1285 struct Droppable(i32);
1286 impl Droppable {
1287 fn new() -> Self {
1288 COUNT.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
1289 Droppable(Self::count())
1290 }
1291
1292 fn count() -> i32 {
1293 COUNT.load(core::sync::atomic::Ordering::Relaxed)
1294 }
1295 }
1296 impl Drop for Droppable {
1297 fn drop(&mut self) {
1298 COUNT.fetch_sub(1, core::sync::atomic::Ordering::Relaxed);
1299 }
1300 }
1301 };
1302 }
1303
1304 #[test]
1305 fn static_new() {
1306 static mut _V: Vec<i32, 4> = Vec::new();
1307 }
1308
1309 #[test]
1310 fn stack_new() {
1311 let mut _v: Vec<i32, 4> = Vec::new();
1312 }
1313
1314 #[test]
1315 fn is_full_empty() {
1316 let mut v: Vec<i32, 4> = Vec::new();
1317
1318 assert!(v.is_empty());
1319 assert!(!v.is_full());
1320
1321 v.push(1).unwrap();
1322 assert!(!v.is_empty());
1323 assert!(!v.is_full());
1324
1325 v.push(1).unwrap();
1326 assert!(!v.is_empty());
1327 assert!(!v.is_full());
1328
1329 v.push(1).unwrap();
1330 assert!(!v.is_empty());
1331 assert!(!v.is_full());
1332
1333 v.push(1).unwrap();
1334 assert!(!v.is_empty());
1335 assert!(v.is_full());
1336 }
1337
1338 #[test]
1339 fn drop() {
1340 droppable!();
1341
1342 {
1343 let mut v: Vec<Droppable, 2> = Vec::new();
1344 v.push(Droppable::new()).ok().unwrap();
1345 v.push(Droppable::new()).ok().unwrap();
1346 v.pop().unwrap();
1347 }
1348
1349 assert_eq!(Droppable::count(), 0);
1350
1351 {
1352 let mut v: Vec<Droppable, 2> = Vec::new();
1353 v.push(Droppable::new()).ok().unwrap();
1354 v.push(Droppable::new()).ok().unwrap();
1355 }
1356
1357 assert_eq!(Droppable::count(), 0);
1358 }
1359
1360 #[test]
1361 fn eq() {
1362 let mut xs: Vec<i32, 4> = Vec::new();
1363 let mut ys: Vec<i32, 8> = Vec::new();
1364
1365 assert_eq!(xs, ys);
1366
1367 xs.push(1).unwrap();
1368 ys.push(1).unwrap();
1369
1370 assert_eq!(xs, ys);
1371 }
1372
1373 #[test]
1374 fn cmp() {
1375 let mut xs: Vec<i32, 4> = Vec::new();
1376 let mut ys: Vec<i32, 4> = Vec::new();
1377
1378 assert_eq!(xs, ys);
1379
1380 xs.push(1).unwrap();
1381 ys.push(2).unwrap();
1382
1383 assert!(xs < ys);
1384 }
1385
1386 #[test]
1387 fn cmp_heterogenous_size() {
1388 let mut xs: Vec<i32, 4> = Vec::new();
1389 let mut ys: Vec<i32, 8> = Vec::new();
1390
1391 assert_eq!(xs, ys);
1392
1393 xs.push(1).unwrap();
1394 ys.push(2).unwrap();
1395
1396 assert!(xs < ys);
1397 }
1398
1399 #[test]
1400 fn cmp_with_arrays_and_slices() {
1401 let mut xs: Vec<i32, 12> = Vec::new();
1402 xs.push(1).unwrap();
1403
1404 let array = [1];
1405
1406 assert_eq!(xs, array);
1407 assert_eq!(array, xs);
1408
1409 assert_eq!(xs, array.as_slice());
1410 assert_eq!(array.as_slice(), xs);
1411
1412 assert_eq!(xs, &array);
1413 assert_eq!(&array, xs);
1414
1415 let longer_array = [1; 20];
1416
1417 assert_ne!(xs, longer_array);
1418 assert_ne!(longer_array, xs);
1419 }
1420
1421 #[test]
1422 fn full() {
1423 let mut v: Vec<i32, 4> = Vec::new();
1424
1425 v.push(0).unwrap();
1426 v.push(1).unwrap();
1427 v.push(2).unwrap();
1428 v.push(3).unwrap();
1429
1430 assert!(v.push(4).is_err());
1431 }
1432
1433 #[test]
1434 fn iter() {
1435 let mut v: Vec<i32, 4> = Vec::new();
1436
1437 v.push(0).unwrap();
1438 v.push(1).unwrap();
1439 v.push(2).unwrap();
1440 v.push(3).unwrap();
1441
1442 let mut items = v.iter();
1443
1444 assert_eq!(items.next(), Some(&0));
1445 assert_eq!(items.next(), Some(&1));
1446 assert_eq!(items.next(), Some(&2));
1447 assert_eq!(items.next(), Some(&3));
1448 assert_eq!(items.next(), None);
1449 }
1450
1451 #[test]
1452 fn iter_mut() {
1453 let mut v: Vec<i32, 4> = Vec::new();
1454
1455 v.push(0).unwrap();
1456 v.push(1).unwrap();
1457 v.push(2).unwrap();
1458 v.push(3).unwrap();
1459
1460 let mut items = v.iter_mut();
1461
1462 assert_eq!(items.next(), Some(&mut 0));
1463 assert_eq!(items.next(), Some(&mut 1));
1464 assert_eq!(items.next(), Some(&mut 2));
1465 assert_eq!(items.next(), Some(&mut 3));
1466 assert_eq!(items.next(), None);
1467 }
1468
1469 #[test]
1470 fn collect_from_iter() {
1471 let slice = &[1, 2, 3];
1472 let vec: Vec<i32, 4> = slice.iter().cloned().collect();
1473 assert_eq!(&vec, slice);
1474 }
1475
1476 #[test]
1477 #[should_panic]
1478 fn collect_from_iter_overfull() {
1479 let slice = &[1, 2, 3];
1480 let _vec = slice.iter().cloned().collect::<Vec<_, 2>>();
1481 }
1482
1483 #[test]
1484 fn iter_move() {
1485 let mut v: Vec<i32, 4> = Vec::new();
1486 v.push(0).unwrap();
1487 v.push(1).unwrap();
1488 v.push(2).unwrap();
1489 v.push(3).unwrap();
1490
1491 let mut items = v.into_iter();
1492
1493 assert_eq!(items.next(), Some(0));
1494 assert_eq!(items.next(), Some(1));
1495 assert_eq!(items.next(), Some(2));
1496 assert_eq!(items.next(), Some(3));
1497 assert_eq!(items.next(), None);
1498 }
1499
1500 #[test]
1501 fn iter_move_drop() {
1502 droppable!();
1503
1504 {
1505 let mut vec: Vec<Droppable, 2> = Vec::new();
1506 vec.push(Droppable::new()).ok().unwrap();
1507 vec.push(Droppable::new()).ok().unwrap();
1508 let mut items = vec.into_iter();
1509 // Move all
1510 let _ = items.next();
1511 let _ = items.next();
1512 }
1513
1514 assert_eq!(Droppable::count(), 0);
1515
1516 {
1517 let mut vec: Vec<Droppable, 2> = Vec::new();
1518 vec.push(Droppable::new()).ok().unwrap();
1519 vec.push(Droppable::new()).ok().unwrap();
1520 let _items = vec.into_iter();
1521 // Move none
1522 }
1523
1524 assert_eq!(Droppable::count(), 0);
1525
1526 {
1527 let mut vec: Vec<Droppable, 2> = Vec::new();
1528 vec.push(Droppable::new()).ok().unwrap();
1529 vec.push(Droppable::new()).ok().unwrap();
1530 let mut items = vec.into_iter();
1531 let _ = items.next(); // Move partly
1532 }
1533
1534 assert_eq!(Droppable::count(), 0);
1535 }
1536
1537 #[test]
1538 fn push_and_pop() {
1539 let mut v: Vec<i32, 4> = Vec::new();
1540 assert_eq!(v.len(), 0);
1541
1542 assert_eq!(v.pop(), None);
1543 assert_eq!(v.len(), 0);
1544
1545 v.push(0).unwrap();
1546 assert_eq!(v.len(), 1);
1547
1548 assert_eq!(v.pop(), Some(0));
1549 assert_eq!(v.len(), 0);
1550
1551 assert_eq!(v.pop(), None);
1552 assert_eq!(v.len(), 0);
1553 }
1554
1555 #[test]
1556 fn resize_size_limit() {
1557 let mut v: Vec<u8, 4> = Vec::new();
1558
1559 v.resize(0, 0).unwrap();
1560 v.resize(4, 0).unwrap();
1561 v.resize(5, 0).expect_err("full");
1562 }
1563
1564 #[test]
1565 fn resize_length_cases() {
1566 let mut v: Vec<u8, 4> = Vec::new();
1567
1568 assert_eq!(v.len(), 0);
1569
1570 // Grow by 1
1571 v.resize(1, 0).unwrap();
1572 assert_eq!(v.len(), 1);
1573
1574 // Grow by 2
1575 v.resize(3, 0).unwrap();
1576 assert_eq!(v.len(), 3);
1577
1578 // Resize to current size
1579 v.resize(3, 0).unwrap();
1580 assert_eq!(v.len(), 3);
1581
1582 // Shrink by 1
1583 v.resize(2, 0).unwrap();
1584 assert_eq!(v.len(), 2);
1585
1586 // Shrink by 2
1587 v.resize(0, 0).unwrap();
1588 assert_eq!(v.len(), 0);
1589 }
1590
1591 #[test]
1592 fn resize_contents() {
1593 let mut v: Vec<u8, 4> = Vec::new();
1594
1595 // New entries take supplied value when growing
1596 v.resize(1, 17).unwrap();
1597 assert_eq!(v[0], 17);
1598
1599 // Old values aren't changed when growing
1600 unwrap!(v.resize(2, 18));
1601 assert_eq!(v[0], 17);
1602 assert_eq!(v[1], 18);
1603
1604 // Old values aren't changed when length unchanged
1605 unwrap!(v.resize(2, 0));
1606 assert_eq!(v[0], 17);
1607 assert_eq!(v[1], 18);
1608
1609 // Old values aren't changed when shrinking
1610 unwrap!(v.resize(1, 0));
1611 assert_eq!(v[0], 17);
1612 }
1613
1614 #[test]
1615 fn resize_default() {
1616 let mut v: Vec<u8, 4> = Vec::new();
1617
1618 // resize_default is implemented using resize, so just check the
1619 // correct value is being written.
1620 unwrap!(v.resize_default(1));
1621 assert_eq!(v[0], 0);
1622 }
1623
1624 #[test]
1625 fn write() {
1626 let mut v: Vec<u8, 4> = Vec::new();
1627 write_unwrap!(v, "{:x}", 1234);
1628 assert_eq!(&v[..], b"4d2");
1629 }
1630
1631 #[test]
1632 fn extend_from_slice() {
1633 let mut v: Vec<u8, 4> = Vec::new();
1634 assert_eq!(v.len(), 0);
1635 unwrap!(v.extend_from_slice(&[1, 2]));
1636 assert_eq!(v.len(), 2);
1637 assert_eq!(v.as_slice(), &[1, 2]);
1638 unwrap!(v.extend_from_slice(&[3]));
1639 assert_eq!(v.len(), 3);
1640 assert_eq!(v.as_slice(), &[1, 2, 3]);
1641 assert!(v.extend_from_slice(&[4, 5]).is_err());
1642 assert_eq!(v.len(), 3);
1643 assert_eq!(v.as_slice(), &[1, 2, 3]);
1644 }
1645
1646 #[test]
1647 fn from_slice() {
1648 // Successful construction
1649 let v: Vec<u8, 4> = unwrap!(Vec::from_slice(&[1, 2, 3]));
1650 assert_eq!(v.len(), 3);
1651 assert_eq!(v.as_slice(), &[1, 2, 3]);
1652
1653 // Slice too large
1654 assert!(Vec::<u8, 2>::from_slice(&[1, 2, 3]).is_err());
1655 }
1656
1657 #[test]
1658 fn starts_with() {
1659 let v: Vec<_, 8> = unwrap!(Vec::from_slice(b"ab"));
1660 assert!(v.starts_with(&[]));
1661 assert!(v.starts_with(b""));
1662 assert!(v.starts_with(b"a"));
1663 assert!(v.starts_with(b"ab"));
1664 assert!(!v.starts_with(b"abc"));
1665 assert!(!v.starts_with(b"ba"));
1666 assert!(!v.starts_with(b"b"));
1667 }
1668
1669 #[test]
1670 fn ends_with() {
1671 let v: Vec<_, 8> = unwrap!(Vec::from_slice(b"ab"));
1672 assert!(v.ends_with(&[]));
1673 assert!(v.ends_with(b""));
1674 assert!(v.ends_with(b"b"));
1675 assert!(v.ends_with(b"ab"));
1676 assert!(!v.ends_with(b"abc"));
1677 assert!(!v.ends_with(b"ba"));
1678 assert!(!v.ends_with(b"a"));
1679 }
1680
1681 #[test]
1682 fn zero_capacity() {
1683 let mut v: Vec<u8, 0> = Vec::new();
1684 // Validate capacity
1685 assert_eq!(v.capacity(), 0);
1686
1687 // Make sure there is no capacity
1688 assert!(v.push(1).is_err());
1689
1690 // Validate length
1691 assert_eq!(v.len(), 0);
1692
1693 // Validate pop
1694 assert_eq!(v.pop(), None);
1695
1696 // Validate slice
1697 const EMPTY_SLICE: &[u8] = &[];
1698 assert_eq!(v.as_slice(), EMPTY_SLICE);
1699
1700 // Validate empty
1701 assert!(v.is_empty());
1702
1703 // Validate full
1704 assert!(v.is_full());
1705 }
1706}