bounded_vector/bounded_vec.rs
1#![allow(clippy::let_unit_value)]
2
3use core::fmt;
4use std::{
5 collections::TryReserveError,
6 fmt::Debug,
7 ops::{Bound, Deref, DerefMut, RangeBounds, RangeInclusive},
8};
9use thiserror::Error;
10
11/// Errors used by BoundedVec
12#[derive(Error, Debug, PartialEq, Eq, Hash, Clone, Copy)]
13pub enum Error {
14 #[error("Vector len outside LOW and UPP bounds")]
15 /// Vector len doesn't fit LOW and UPP bounds
16 OutOfBoundsVec,
17}
18
19/// Bounded Vec with minimal (L - lower bound) and maximal (U - upper bound) length
20#[derive(PartialEq, Eq, Hash, Clone)]
21pub struct BoundedVec<T, const LOW: usize, const UPP: usize>(Vec<T>);
22
23impl<T, const LOW: usize, const UPP: usize> BoundedVec<T, LOW, UPP> {
24 #[doc(hidden)]
25 pub const VALID_L_U_TEST: () = assert!(LOW <= UPP);
26 #[doc(hidden)]
27 pub const BOUNDS: RangeInclusive<usize> = LOW..=UPP;
28
29 /// # Safety
30 ///
31 /// This is highly unsafe, due to the number of invariants that aren't
32 /// checked:
33 ///
34 /// * `ptr` must have been allocated using the global allocator, such as via
35 /// the [`alloc::alloc`] function.
36 /// * `T` needs to have the same alignment as what `ptr` was allocated with.
37 /// (`T` having a less strict alignment is not sufficient, the alignment really
38 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
39 /// allocated and deallocated with the same layout.)
40 /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs
41 /// to be the same size as the pointer was allocated with. (Because similar to
42 /// alignment, [`dealloc`] must be called with the same layout `size`.)
43 /// * `length` needs to be less than or equal to `capacity`.
44 /// * The first `length` values must be properly initialized values of type `T`.
45 /// * `capacity` needs to be the capacity that the pointer was allocated with.
46 /// * The allocated size in bytes must be no larger than `isize::MAX`.
47 /// See the safety documentation of pointer::offset.
48 /// * `length` needs to be in range of upper and lower bounds
49 ///
50 /// These requirements are always upheld by any `ptr` that has been allocated
51 /// via `Vec<T>`. Other allocation sources are allowed if the invariants are
52 /// upheld.
53 ///
54 /// Violating these may cause problems like corrupting the allocator's
55 /// internal data structures. For example it is normally **not** safe
56 /// to build a `Vec<u8>` from a pointer to a C `char` array with length
57 /// `size_t`, doing so is only safe if the array was initially allocated by
58 /// a `Vec` or `String`.
59 /// It's also not safe to build one from a `Vec<u16>` and its length, because
60 /// the allocator cares about the alignment, and these two types have different
61 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
62 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid
63 /// these issues, it is often preferable to do casting/transmuting using
64 /// [`std::slice::from_raw_parts`] instead.
65 ///
66 /// The ownership of `ptr` is effectively transferred to the
67 /// `Vec<T>` which may then deallocate, reallocate or change the
68 /// contents of memory pointed to by the pointer at will. Ensure
69 /// that nothing else uses the pointer after calling this
70 /// function.
71 ///
72 /// [`String`]: std::string::String
73 /// [`alloc::alloc`]: std::alloc::alloc
74 /// [`dealloc`]: std::alloc::GlobalAlloc::dealloc
75 ///
76 #[inline]
77 pub unsafe fn from_raw_parts(
78 ptr: *mut T,
79 length: usize,
80 capacity: usize,
81 ) -> Result<Self, Error> {
82 let _ = Self::VALID_L_U_TEST;
83 if !Self::BOUNDS.contains(&length) {
84 return Err(Error::OutOfBoundsVec);
85 }
86
87 Ok(Self(Vec::from_raw_parts(ptr, length, capacity)))
88 }
89
90 /// # Safety
91 /// This function creates BoundedVec without checking length bounds.
92 /// You need to make sure that vec.length() is in LOW..=UPP.
93 #[inline]
94 pub unsafe fn from_vec_unchecked(vec: Vec<T>) -> BoundedVec<T, LOW, UPP> {
95 BoundedVec(vec)
96 }
97
98 /// Returns reference to inner Vector
99 #[inline]
100 pub fn as_vec(&self) -> &Vec<T> {
101 &self.0
102 }
103
104 /// Returns inner Vector
105 #[inline]
106 pub fn to_vec(self) -> Vec<T> {
107 self.0
108 }
109
110 /// # Safety
111 ///
112 /// Vector len must always be in range of upper and lower bounds
113 ///
114 #[inline]
115 pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<T> {
116 &mut self.0
117 }
118
119 /// Reserves capacity for at least `additional` more elements to be inserted
120 /// in the given `BoundedVec<T, LOW, UPP>`. The collection may reserve more space to
121 /// speculatively avoid frequent reallocations. After calling `reserve`,
122 /// capacity will be greater than or equal to `self.len() + additional`.
123 /// Does nothing if capacity is already sufficient.
124 ///
125 /// # Panics
126 ///
127 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
128 ///
129 /// # Examples
130 ///
131 /// ```
132 /// use bounded_vector::{BoundedVec, bvec};
133 ///
134 /// let mut vec: BoundedVec<i32, 0, 10> = bvec![1];
135 /// vec.reserve(10);
136 /// assert!(vec.capacity() >= 11);
137 /// ```
138 #[inline]
139 pub fn reserve(&mut self, additional: usize) {
140 self.0.reserve(additional)
141 }
142
143 /// Returns the total number of elements the vector can hold without
144 /// reallocating.
145 ///
146 /// # Examples
147 ///
148 /// ```
149 /// use bounded_vector::BoundedVec;
150 ///
151 /// let mut vec: BoundedVec<i32, 0, 10> = BoundedVec::with_capacity(10);
152 /// vec.push(42);
153 /// assert!(vec.capacity() >= 10);
154 /// ```
155 #[inline]
156 pub fn capacity(&self) -> usize {
157 self.0.capacity()
158 }
159
160 /// Reserves the minimum capacity for at least `additional` more elements to
161 /// be inserted in the given `BoundedVec<T, LOW, UPP>`. Unlike [`reserve`], this will not
162 /// deliberately over-allocate to speculatively avoid frequent allocations.
163 /// After calling `reserve_exact`, capacity will be greater than or equal to
164 /// `self.len() + additional`. Does nothing if the capacity is already
165 /// sufficient.
166 ///
167 /// Note that the allocator may give the collection more space than it
168 /// requests. Therefore, capacity can not be relied upon to be precisely
169 /// minimal. Prefer [`reserve`] if future insertions are expected.
170 ///
171 /// [`reserve`]: BoundedVec::reserve
172 ///
173 /// # Panics
174 ///
175 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
176 ///
177 /// # Examples
178 ///
179 /// ```
180 /// use bounded_vector::{BoundedVec, bvec};
181 ///
182 /// let mut vec: BoundedVec<i32, 0, 10> = bvec![1];
183 /// vec.reserve_exact(10);
184 /// assert!(vec.capacity() >= 11);
185 /// ```
186 #[inline]
187 pub fn reserve_exact(&mut self, additional: usize) {
188 self.0.reserve_exact(additional)
189 }
190
191 /// Tries to reserve capacity for at least `additional` more elements to be inserted
192 /// in the given `BoundedVec<T, LOW, UPP>`. The collection may reserve more space to speculatively avoid
193 /// frequent reallocations. After calling `try_reserve`, capacity will be
194 /// greater than or equal to `self.len() + additional` if it returns
195 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
196 /// preserves the contents even if an error occurs.
197 ///
198 /// # Errors
199 ///
200 /// If the capacity overflows, or the allocator reports a failure, then an error
201 /// is returned.
202 ///
203 /// # Examples
204 ///
205 /// ```
206 /// use bounded_vector::BoundedVec;
207 /// use std::collections::TryReserveError;
208 ///
209 /// fn process_data<const SIZE: usize>(data: &[u32; SIZE]) -> Result<BoundedVec<u32, 0, SIZE>, TryReserveError> {
210 /// let mut output = BoundedVec::new();
211 ///
212 /// // Pre-reserve the memory, exiting if we can't
213 /// output.try_reserve(SIZE)?;
214 ///
215 /// // Now we know this can't OOM in the middle of our complex work
216 /// data.iter().for_each(|&val| {
217 /// output.push(val * 2 + 5).expect("In range") // very complicated
218 /// });
219 ///
220 /// Ok(output)
221 /// }
222 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
223 /// ```
224 #[inline]
225 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
226 self.0.try_reserve(additional)
227 }
228
229 /// Tries to reserve the minimum capacity for at least `additional`
230 /// elements to be inserted in the given `BoundedVec<T>`. Unlike [`try_reserve`],
231 /// this will not deliberately over-allocate to speculatively avoid frequent
232 /// allocations. After calling `try_reserve_exact`, capacity will be greater
233 /// than or equal to `self.len() + additional` if it returns `Ok(())`.
234 /// Does nothing if the capacity is already sufficient.
235 ///
236 /// Note that the allocator may give the collection more space than it
237 /// requests. Therefore, capacity can not be relied upon to be precisely
238 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
239 ///
240 /// [`try_reserve`]: BoundedVec::try_reserve
241 ///
242 /// # Errors
243 ///
244 /// If the capacity overflows, or the allocator reports a failure, then an error
245 /// is returned.
246 ///
247 /// # Examples
248 ///
249 /// ```
250 /// use bounded_vector::BoundedVec;
251 /// use std::collections::TryReserveError;
252 ///
253 /// fn process_data<const SIZE: usize>(data: &[u32; SIZE]) -> Result<BoundedVec<u32, 0, SIZE>, TryReserveError> {
254 /// let mut output = BoundedVec::new();
255 ///
256 /// // Pre-reserve the memory, exiting if we can't
257 /// output.try_reserve_exact(SIZE)?;
258 ///
259 /// // Now we know this can't OOM in the middle of our complex work
260 /// data.iter().for_each(|&val| {
261 /// output.push(val * 2 + 5).expect("In range") // very complicated
262 /// });
263 ///
264 /// Ok(output)
265 /// }
266 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
267 /// ```
268 #[inline]
269 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
270 self.0.try_reserve_exact(additional)
271 }
272
273 /// Shrinks the capacity of the vector as much as possible.
274 ///
275 /// The behavior of this method depends on the allocator, which may either shrink the vector
276 /// in-place or reallocate. The resulting vector might still have some excess capacity, just as
277 /// is the case for [`with_capacity`]. See [`Allocator::shrink`] for more details.
278 ///
279 /// [`with_capacity`]: BoundedVec::with_capacity
280 ///
281 /// # Examples
282 ///
283 /// ```
284 /// use bounded_vector::BoundedVec;
285 ///
286 /// let mut vec: BoundedVec<i32, 0, 10> = BoundedVec::with_capacity(10);
287 /// vec.append(&mut vec![1, 2, 3]);
288 /// assert!(vec.capacity() >= 10);
289 /// vec.shrink_to_fit();
290 /// assert!(vec.capacity() >= 3);
291 /// ```
292 #[inline]
293 pub fn shrink_to_fit(&mut self) {
294 self.0.shrink_to_fit()
295 }
296
297 /// Shrinks the capacity of the vector with a lower bound.
298 ///
299 /// The capacity will remain at least as large as both the length
300 /// and the supplied value.
301 ///
302 /// If the current capacity is less than the lower limit, this is a no-op.
303 ///
304 /// # Examples
305 ///
306 /// ```
307 /// use bounded_vector::BoundedVec;
308 ///
309 /// let mut vec: BoundedVec<i32, 0, 10> = BoundedVec::with_capacity(10);
310 /// vec.append(&mut vec![1, 2, 3]);
311 /// vec.shrink_to(4);
312 /// assert!(vec.capacity() >= 4);
313 /// vec.shrink_to(0);
314 /// assert!(vec.capacity() >= 3);
315 /// ```
316 #[inline]
317 pub fn shrink_to(&mut self, min_capacity: usize) {
318 self.0.shrink_to(min_capacity);
319 }
320
321 /// Converts the vector into [`Box<[T]>`][owned slice].
322 ///
323 /// Before doing the conversion, this method discards excess capacity like [`shrink_to_fit`].
324 ///
325 /// [owned slice]: Box
326 /// [`shrink_to_fit`]: Vec::shrink_to_fit
327 ///
328 /// # Examples
329 ///
330 /// ```
331 /// use bounded_vector::{BoundedVec, bvec};
332 ///
333 /// let v: BoundedVec<i32, 0, 10> = bvec![1, 2, 3];
334 /// let slice = v.into_boxed_slice();
335 /// ```
336 ///
337 /// Any excess capacity is removed:
338 ///
339 /// ```
340 /// use bounded_vector::BoundedVec;
341 /// let mut vec: BoundedVec<i32, 0, 10> = BoundedVec::with_capacity(10);
342 /// vec.append(&mut vec![1, 2, 3]);
343 ///
344 /// assert!(vec.capacity() >= 10);
345 /// let slice = vec.into_boxed_slice();
346 /// assert_eq!(slice.into_vec().capacity(), 3);
347 /// ```
348 #[inline]
349 pub fn into_boxed_slice(self) -> Box<[T]> {
350 self.0.into_boxed_slice()
351 }
352
353 /// Shortens the vector, keeping the first `len` elements and dropping
354 /// the rest.
355 ///
356 /// If `len` is greater or equal to the vector's current length, this has
357 /// no effect.
358 ///
359 /// Note that this method has no effect on the allocated capacity
360 /// of the vector.
361 ///
362 /// # Examples
363 ///
364 /// Truncating a five element vector to two elements:
365 ///
366 /// ```
367 /// use bounded_vector::{BoundedVec, bvec};
368 ///
369 /// let mut vec: BoundedVec<i32, 0, 10> = bvec![1, 2, 3, 4, 5];
370 /// vec.truncate(2).expect("In range");
371 /// assert_eq!(vec.as_slice(), &[1, 2][..]);
372 /// ```
373 ///
374 /// No truncation occurs when `len` is greater than the vector's current
375 /// length:
376 ///
377 /// ```
378 /// use bounded_vector::{BoundedVec, bvec};
379 ///
380 /// let mut vec: BoundedVec<i32, 0, 10> = bvec![1, 2, 3];
381 /// vec.truncate(8).expect("In range");
382 /// assert_eq!(vec.as_slice(), &[1, 2, 3][..]);
383 /// ```
384 ///
385 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
386 /// method.
387 ///
388 /// ```
389 /// use bounded_vector::{BoundedVec, bvec};
390 ///
391 /// let mut vec: BoundedVec<i32, 0, 10> = bvec![1, 2, 3];
392 /// vec.truncate(0).expect("In range");
393 /// assert!(vec.is_empty());
394 /// ```
395 ///
396 /// When length is smaller than LOW bound truncate returns Error
397 ///
398 /// ```
399 /// use bounded_vector::{BoundedVec, bvec, Error};
400 ///
401 /// let mut vec: BoundedVec<i32, 2, 10> = bvec![1, 2, 3];
402 /// assert_eq!(vec.truncate(1), Err(Error::OutOfBoundsVec));
403 /// assert_eq!(vec.as_slice(), &[1, 2, 3][..]);
404 /// ```
405 ///
406 /// [`clear`]: Vec::clear
407 #[inline]
408 pub fn truncate(&mut self, length: usize) -> Result<(), Error> {
409 if length < LOW {
410 return Err(Error::OutOfBoundsVec);
411 }
412
413 self.0.truncate(length);
414 Ok(())
415 }
416
417 /// Extracts a slice containing the entire vector.
418 ///
419 /// Equivalent to `&s[..]`.
420 ///
421 /// # Examples
422 ///
423 /// ```
424 /// use bounded_vector::{BoundedVec, bvec};
425 /// use std::io::{self, Write};
426 ///
427 /// let buffer: BoundedVec<u8, 0, 10> = bvec![1, 2, 3, 5, 8];
428 /// io::sink().write(buffer.as_slice()).unwrap();
429 /// ```
430 #[inline]
431 pub fn as_slice(&self) -> &[T] {
432 self.0.as_slice()
433 }
434
435 /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer
436 /// valid for zero sized reads if the vector didn't allocate.
437 ///
438 /// The caller must ensure that the vector outlives the pointer this
439 /// function returns, or else it will end up dangling.
440 /// Modifying the vector may cause its buffer to be reallocated,
441 /// which would also make any pointers to it invalid.
442 ///
443 /// The caller must also ensure that the memory the pointer (non-transitively) points to
444 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
445 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
446 ///
447 /// This method guarantees that for the purpose of the aliasing model, this method
448 /// does not materialize a reference to the underlying slice, and thus the returned pointer
449 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`].
450 /// Note that calling other methods that materialize mutable references to the slice,
451 /// or mutable references to specific elements you are planning on accessing through this pointer,
452 /// as well as writing to those elements, may still invalidate this pointer.
453 /// See the second example below for how this guarantee can be used.
454 ///
455 ///
456 /// # Examples
457 ///
458 /// ```
459 /// use bounded_vector::{BoundedVec, bvec};
460 ///
461 /// let x: BoundedVec<i32,0,10> = bvec![1, 2, 4];
462 /// let x_ptr = x.as_ptr();
463 ///
464 /// unsafe {
465 /// for i in 0..x.len() {
466 /// assert_eq!(*x_ptr.add(i), 1 << i);
467 /// }
468 /// }
469 /// ```
470 ///
471 /// Due to the aliasing guarantee, the following code is legal:
472 ///
473 /// ```
474 /// use bounded_vector::{BoundedVec, bvec};
475 ///
476 /// unsafe {
477 /// let mut v:BoundedVec<i32,0,10> = bvec![0, 1, 2];
478 /// let ptr1 = v.as_ptr();
479 /// let _ = ptr1.read();
480 /// let ptr2 = v.as_mut_ptr().offset(2);
481 /// ptr2.write(2);
482 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`
483 /// // because it mutated a different element:
484 /// let _ = ptr1.read();
485 /// }
486 /// ```
487 ///
488 /// [`as_mut_ptr`]: Vec::as_mut_ptr
489 /// [`as_ptr`]: Vec::as_ptr
490 #[inline]
491 pub fn as_ptr(&self) -> *const T {
492 self.0.as_ptr()
493 }
494
495 /// Extracts a mutable slice of the entire vector.
496 ///
497 /// Equivalent to `&mut s[..]`.
498 ///
499 /// # Examples
500 ///
501 /// ```
502 /// use bounded_vector::{BoundedVec, bvec};
503 /// use std::io::{self, Read};
504 ///
505 /// let mut buffer: BoundedVec<u8, 0, 10> = bvec![0; 3];
506 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
507 /// ```
508 #[inline]
509 pub fn as_mut_slice(&mut self) -> &mut [T] {
510 self.0.as_mut_slice()
511 }
512
513 /// Returns a raw mutable pointer to the vector's buffer, or a dangling
514 /// raw pointer valid for zero sized reads if the vector didn't allocate.
515 ///
516 /// The caller must ensure that the vector outlives the pointer this
517 /// function returns, or else it will end up dangling.
518 /// Modifying the vector may cause its buffer to be reallocated,
519 /// which would also make any pointers to it invalid.
520 ///
521 /// This method guarantees that for the purpose of the aliasing model, this method
522 /// does not materialize a reference to the underlying slice, and thus the returned pointer
523 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`].
524 /// Note that calling other methods that materialize references to the slice,
525 /// or references to specific elements you are planning on accessing through this pointer,
526 /// may still invalidate this pointer.
527 /// See the second example below for how this guarantee can be used.
528 ///
529 /// # Examples
530 ///
531 /// ```
532 /// use bounded_vector::BoundedVec;
533 ///
534 /// // Allocate vector big enough for 4 elements.
535 /// let size = 4;
536 /// let mut x: BoundedVec<i32, 0, 10> = BoundedVec::with_capacity(size);
537 /// let x_ptr = x.as_mut_ptr();
538 ///
539 /// // Initialize elements via raw pointer writes, then set length.
540 /// unsafe {
541 /// for i in 0..size {
542 /// *x_ptr.add(i) = i as i32;
543 /// }
544 /// x.set_len(size);
545 /// }
546 /// assert_eq!(&*x, &[0, 1, 2, 3]);
547 /// ```
548 ///
549 /// Due to the aliasing guarantee, the following code is legal:
550 ///
551 /// ```
552 /// use bounded_vector::{BoundedVec, bvec};
553 ///
554 /// unsafe {
555 /// let mut v: BoundedVec<i32, 0, 10> = bvec![0];
556 /// let ptr1 = v.as_mut_ptr();
557 /// ptr1.write(1);
558 /// let ptr2 = v.as_mut_ptr();
559 /// ptr2.write(2);
560 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
561 /// ptr1.write(3);
562 /// }
563 /// ```
564 ///
565 /// [`as_mut_ptr`]: Vec::as_mut_ptr
566 /// [`as_ptr`]: Vec::as_ptr
567 /// [`as_non_null`]: Vec::as_non_null
568 #[inline]
569 pub fn as_mut_ptr(&mut self) -> *mut T {
570 self.0.as_mut_ptr()
571 }
572
573 /// # Safety
574 ///
575 /// - `new_len` must be less than or equal to [`capacity()`].
576 /// - `new_len` must be in range of upper and lower bounds
577 /// - The elements at `old_len..new_len` must be initialized.
578 ///
579 /// [`capacity()`]: Vec::capacity
580 ///
581 #[inline]
582 pub unsafe fn set_len(&mut self, new_len: usize) -> Result<(), Error> {
583 self.0.set_len(new_len);
584 Ok(())
585 }
586
587 /// Removes an element from the vector and returns it.
588 ///
589 /// The removed element is replaced by the last element of the vector.
590 ///
591 /// This does not preserve ordering of the remaining elements, but is *O*(1).
592 /// If you need to preserve the element order, use [`remove`] instead.
593 ///
594 /// Returns error if len after removal would be out of bounds
595 ///
596 /// [`remove`]: BoundedVec::remove
597 ///
598 /// # Panics
599 ///
600 /// Panics if `index` is out of bounds.
601 ///
602 /// # Examples
603 ///
604 /// ```
605 /// use bounded_vector::{BoundedVec, bvec, Error};
606 ///
607 /// let mut v: BoundedVec<&str, 2, 10> = bvec!["foo", "bar", "baz", "qux"];
608 ///
609 /// assert_eq!(v.swap_remove(1), Ok("bar"));
610 /// assert_eq!(v.as_slice(), &["foo", "qux", "baz"][..]);
611 ///
612 /// assert_eq!(v.swap_remove(0), Ok("foo"));
613 /// assert_eq!(v.as_slice(), &["baz", "qux"][..]);
614 ///
615 /// assert_eq!(v.swap_remove(0), Err(Error::OutOfBoundsVec));
616 /// assert_eq!(v.as_slice(), &["baz", "qux"][..]);
617 /// ```
618 #[inline]
619 pub fn swap_remove(&mut self, index: usize) -> Result<T, Error> {
620 if self.len() <= LOW {
621 return Err(Error::OutOfBoundsVec);
622 }
623
624 Ok(self.0.swap_remove(index))
625 }
626
627 /// Inserts an element at position `index` within the vector, shifting all
628 /// elements after it to the right.
629 ///
630 /// Returns error if len after inserting would be out of bounds.
631 ///
632 /// # Panics
633 ///
634 /// Panics if `index > len`.
635 ///
636 /// # Examples
637 ///
638 /// ```
639 /// use bounded_vector::{BoundedVec, bvec, Error};
640 ///
641 /// let mut vec: BoundedVec<char, 0, 5> = bvec!['a', 'b', 'c'];
642 /// vec.insert(1, 'd').expect("In range");
643 /// assert_eq!(vec.as_slice(), &['a', 'd', 'b', 'c'][..]);
644 /// vec.insert(4, 'e').expect("In range");
645 /// assert_eq!(vec.as_slice(), &['a', 'd', 'b', 'c', 'e'][..]);
646 /// assert_eq!(vec.insert(4, 'e'), Err(Error::OutOfBoundsVec));
647 /// assert_eq!(vec.as_slice(), &['a', 'd', 'b', 'c', 'e'][..]);
648 /// ```
649 ///
650 /// # Time complexity
651 ///
652 /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be
653 /// shifted to the right. In the worst case, all elements are shifted when
654 /// the insertion index is 0.
655 #[inline]
656 pub fn insert(&mut self, index: usize, element: T) -> Result<(), Error> {
657 if self.len() >= UPP {
658 return Err(Error::OutOfBoundsVec);
659 }
660
661 self.0.insert(index, element);
662 Ok(())
663 }
664
665 /// Removes and returns the element at position `index` within the vector,
666 /// shifting all elements after it to the left.
667 ///
668 /// Returns error if len after removing would be out of bounds.
669 ///
670 /// Note: Because this shifts over the remaining elements, it has a
671 /// worst-case performance of *O*(*n*). If you don't need the order of elements
672 /// to be preserved, use [`swap_remove`] instead.
673 ///
674 /// [`swap_remove`]: BoundedVec::swap_remove
675 ///
676 /// # Panics
677 ///
678 /// Panics if `index` is out of bounds.
679 ///
680 /// # Examples
681 ///
682 /// ```
683 /// use bounded_vector::{BoundedVec, bvec, Error};
684 ///
685 /// let mut v: BoundedVec<char, 2, 10> = bvec!['a', 'b', 'c'];
686 /// assert_eq!(v.remove(1), Ok('b'));
687 /// assert_eq!(v.as_slice(), &['a', 'c'][..]);
688 /// assert_eq!(v.remove(1), Err(Error::OutOfBoundsVec));
689 /// assert_eq!(v.as_slice(), &['a', 'c'][..]);
690 /// ```
691 #[inline]
692 pub fn remove(&mut self, index: usize) -> Result<T, Error> {
693 if self.len() <= LOW {
694 return Err(Error::OutOfBoundsVec);
695 }
696
697 Ok(self.0.remove(index))
698 }
699
700 /// Retains only the elements specified by the predicate.
701 ///
702 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
703 /// This method operates in place, visiting each element exactly once in the
704 /// original order, and preserves the order of the retained elements.
705 ///
706 /// Returns error if len after removing would be out of bounds.
707 ///
708 /// # Examples
709 ///
710 /// ```
711 /// use bounded_vector::{BoundedVec, bvec, Error};
712 ///
713 /// let vec: BoundedVec<i32, 1, 10> = bvec![1, 2, 3, 4];
714 /// let vec = vec.retain(|&x| x % 2 == 0).expect("In range");
715 /// assert_eq!(vec.as_slice(), &[2, 4][..]);
716 /// assert_eq!(vec.retain(|&x| x % 2 == 1), Err(Error::OutOfBoundsVec));
717 /// ```
718 ///
719 /// Because the elements are visited exactly once in the original order,
720 /// external state may be used to decide which elements to keep.
721 ///
722 /// ```
723 /// use bounded_vector::{BoundedVec, bvec};
724 ///
725 /// let vec: BoundedVec<i32, 0, 10> = bvec![1, 2, 3, 4, 5];
726 /// let keep = [false, true, true, false, true];
727 /// let mut iter = keep.iter();
728 /// let vec = vec.retain(|_| *iter.next().unwrap()).expect("In range");
729 /// assert_eq!(vec.as_slice(), &[2, 3, 5][..]);
730 /// ```
731 #[inline]
732 pub fn retain<F>(mut self, f: F) -> Result<Self, Error>
733 where
734 F: FnMut(&T) -> bool,
735 {
736 self.0.retain(f);
737 if self.len() < LOW {
738 return Err(Error::OutOfBoundsVec);
739 }
740
741 Ok(self)
742 }
743
744 /// Retains only the elements specified by the predicate, passing a mutable reference to it.
745 ///
746 /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
747 /// This method operates in place, visiting each element exactly once in the
748 /// original order, and preserves the order of the retained elements.
749 ///
750 /// Returns error if len after removing would be out of bounds.
751 ///
752 /// # Examples
753 ///
754 /// ```
755 /// use bounded_vector::{BoundedVec, bvec, Error};
756 ///
757 /// let vec: BoundedVec<i32, 1, 10> = bvec![1, 2, 3, 4];
758 /// let vec = vec.retain_mut(|x| if *x <= 3 {
759 /// *x += 1;
760 /// true
761 /// } else {
762 /// false
763 /// }).expect("In range");
764 /// assert_eq!(vec.as_slice(), &[2, 3, 4][..]);
765 /// assert_eq!(vec.retain(|_| false), Err(Error::OutOfBoundsVec))
766 /// ```
767 #[inline]
768 pub fn retain_mut<F>(mut self, f: F) -> Result<Self, Error>
769 where
770 F: FnMut(&mut T) -> bool,
771 {
772 self.0.retain_mut(f);
773 if self.len() < LOW {
774 return Err(Error::OutOfBoundsVec);
775 }
776
777 Ok(self)
778 }
779
780 /// Removes all but the first of consecutive elements in the vector that resolve to the same
781 /// key.
782 ///
783 /// If the vector is sorted, this removes all duplicates.
784 ///
785 /// Returns error if len after removing would be out of bounds.
786 ///
787 /// # Examples
788 ///
789 /// ```
790 /// use bounded_vector::{BoundedVec, bvec, Error};
791 ///
792 /// let vec: BoundedVec<i32, 2, 10> = bvec![10, 20, 21, 30, 20];
793 /// let vec = vec.dedup_by_key(|i| *i / 10).expect("In range");
794 /// assert_eq!(vec.as_slice(), &[10, 20, 30, 20][..]);
795 /// assert_eq!(vec.dedup_by_key(|i| *i/100), Err(Error::OutOfBoundsVec));
796 /// ```
797 #[inline]
798 pub fn dedup_by_key<F, K>(mut self, key: F) -> Result<Self, Error>
799 where
800 F: FnMut(&mut T) -> K,
801 K: PartialEq,
802 {
803 self.0.dedup_by_key(key);
804 if self.len() < LOW {
805 return Err(Error::OutOfBoundsVec);
806 }
807
808 Ok(self)
809 }
810
811 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
812 /// relation.
813 ///
814 /// The `same_bucket` function is passed references to two elements from the vector and
815 /// must determine if the elements compare equal. The elements are passed in opposite order
816 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
817 ///
818 /// If the vector is sorted, this removes all duplicates.
819 ///
820 /// Returns error if len after removing would be out of bounds.
821 ///
822 /// # Examples
823 ///
824 /// ```
825 /// use bounded_vector::{BoundedVec, bvec, Error};
826 ///
827 /// let vec: BoundedVec<&str, 2, 10> = bvec!["foo", "bar", "Bar", "baz", "bar"];
828 /// let vec = vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)).expect("In range");
829 /// assert_eq!(vec.as_slice(), &["foo", "bar", "baz", "bar"][..]);
830 /// assert_eq!(vec.dedup_by(|_, _| true), Err(Error::OutOfBoundsVec));
831 /// ```
832 #[inline]
833 pub fn dedup_by<F>(mut self, same_bucket: F) -> Result<Self, Error>
834 where
835 F: FnMut(&mut T, &mut T) -> bool,
836 {
837 self.0.dedup_by(same_bucket);
838 if self.len() < LOW {
839 return Err(Error::OutOfBoundsVec);
840 }
841
842 Ok(self)
843 }
844
845 /// Appends an element to the back of a collection.
846 ///
847 /// Returns error if len after pushing would be out of bounds.
848 ///
849 /// # Panics
850 ///
851 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
852 ///
853 /// # Examples
854 ///
855 /// ```
856 /// use bounded_vector::{BoundedVec, bvec, Error};
857 ///
858 /// let mut vec: BoundedVec<i32, 0, 3> = bvec![1, 2];
859 /// vec.push(3).expect("In range");
860 /// assert_eq!(vec.as_slice(), &[1, 2, 3][..]);
861 /// assert_eq!(vec.push(4), Err(Error::OutOfBoundsVec));
862 /// assert_eq!(vec.as_slice(), &[1, 2, 3][..]);
863 /// ```
864 ///
865 /// # Time complexity
866 ///
867 /// Takes amortized *O*(1) time. If the vector's length would exceed its
868 /// capacity after the push, *O*(*capacity*) time is taken to copy the
869 /// vector's elements to a larger allocation. This expensive operation is
870 /// offset by the *capacity* *O*(1) insertions it allows.
871 #[inline]
872 pub fn push(&mut self, value: T) -> Result<(), Error> {
873 if self.len() >= UPP {
874 return Err(Error::OutOfBoundsVec);
875 }
876
877 self.0.push(value);
878 Ok(())
879 }
880
881 /// Removes the last element from a vector and returns it, or [`Error::OutOfBoundsVec`] if size
882 /// after removal size would be out of bounds.
883 ///
884 /// # Examples
885 ///
886 /// ```
887 /// use bounded_vector::{BoundedVec, bvec, Error};
888 ///
889 /// let mut vec: BoundedVec<i32, 2, 10> = bvec![1, 2, 3];
890 /// assert_eq!(vec.pop(), Ok(3));
891 /// assert_eq!(vec.as_slice(), &[1, 2][..]);
892 /// assert_eq!(vec.pop(), Err(Error::OutOfBoundsVec));
893 /// assert_eq!(vec.as_slice(), &[1, 2][..]);
894 /// ```
895 ///
896 /// # Time complexity
897 ///
898 /// Takes *O*(1) time.
899 #[inline]
900 pub fn pop(&mut self) -> Result<T, Error> {
901 if self.len() <= LOW {
902 return Err(Error::OutOfBoundsVec);
903 }
904
905 Ok(self.0.pop().expect("Checked before"))
906 }
907
908 /// Moves all the elements of `other` into `self`, leaving `other` empty.
909 ///
910 /// Returns error if len after pushing would be out of bounds.
911 ///
912 /// # Panics
913 ///
914 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
915 ///
916 /// # Examples
917 ///
918 /// ```
919 /// use bounded_vector::{BoundedVec, bvec, Error};
920 ///
921 /// let mut vec: BoundedVec<i32, 2, 6> = bvec![1, 2, 3];
922 /// let mut vec2 = vec![4, 5, 6];
923 /// vec.append(&mut vec2).expect("In range");
924 /// assert_eq!(vec.as_slice(), &[1, 2, 3, 4, 5, 6][..]);
925 /// assert_eq!(vec2, []);
926 /// assert_eq!(vec.append(&mut vec![7]), Err(Error::OutOfBoundsVec));
927 /// assert_eq!(vec.as_slice(), &[1, 2, 3, 4, 5, 6][..]);
928 /// ```
929 #[inline]
930 pub fn append(&mut self, vec: &mut Vec<T>) -> Result<(), Error> {
931 if self.len() + vec.len() > UPP {
932 return Err(Error::OutOfBoundsVec);
933 }
934
935 self.0.append(vec);
936 Ok(())
937 }
938
939 /// Returns the number of elements in the vector, also referred to
940 /// as its 'length'.
941 ///
942 /// # Examples
943 ///
944 /// ```
945 /// use bounded_vector::{BoundedVec, bvec};
946 ///
947 /// let a: BoundedVec<i32, 0, 10> = bvec![1, 2, 3];
948 /// assert_eq!(a.len(), 3);
949 /// ```
950 #[inline]
951 pub fn len(&self) -> usize {
952 if LOW == UPP {
953 LOW
954 } else {
955 self.0.len()
956 }
957 }
958
959 /// Returns `true` if the vector contains no elements.
960 ///
961 /// # Examples
962 ///
963 /// ```
964 /// use bounded_vector::BoundedVec;
965 ///
966 /// let mut v: BoundedVec<i32, 0, 10> = BoundedVec::new();
967 /// assert!(v.is_empty());
968 ///
969 /// v.push(1).expect("In range");
970 /// assert!(!v.is_empty());
971 /// ```
972 #[inline]
973 pub fn is_empty(&self) -> bool {
974 if UPP == 0 {
975 true
976 } else {
977 self.0.is_empty()
978 }
979 }
980
981 /// Splits the collection into two at the given index.
982 ///
983 /// Returns a newly allocated vector containing the elements in the range
984 /// `[at, len)`. After the call, the original vector will be left containing
985 /// the elements `[0, at)` with its previous capacity unchanged.
986 ///
987 /// Returns error if len after splitting would be out of bounds.
988 ///
989 /// - If you want to take ownership of the entire contents and capacity of
990 /// the vector, see [`mem::take`] or [`mem::replace`].
991 /// - If you don't need the returned vector at all, see [`Vec::truncate`].
992 ///
993 /// # Panics
994 ///
995 /// Panics if `at > len`.
996 ///
997 /// # Examples
998 ///
999 /// ```
1000 /// use bounded_vector::{BoundedVec, bvec, Error};
1001 ///
1002 /// let mut vec: BoundedVec<char, 1, 10> = bvec!['a', 'b', 'c'];
1003 /// let vec2 = vec.split_off(1).expect("In range");
1004 /// assert_eq!(vec.as_slice(), &['a'][..]);
1005 /// assert_eq!(vec2, ['b', 'c']);
1006 /// assert_eq!(vec.split_off(0), Err(Error::OutOfBoundsVec));
1007 /// assert_eq!(vec.as_slice(), &['a'][..]);
1008 /// ```
1009 #[inline]
1010 pub fn split_off(&mut self, at: usize) -> Result<Vec<T>, Error> {
1011 if at < LOW {
1012 return Err(Error::OutOfBoundsVec);
1013 }
1014
1015 Ok(self.0.split_off(at))
1016 }
1017
1018 /// Resizes the `BoundedVec` in-place so that `len` is equal to `new_len`.
1019 ///
1020 /// If `new_len` is greater than `len`, the `BoundedVec` is extended by the
1021 /// difference, with each additional slot filled with the result of
1022 /// calling the closure `f`. The return values from `f` will end up
1023 /// in the `Vec` in the order they have been generated.
1024 ///
1025 /// If `new_len` is less than `len`, the `BoundedVec` is simply truncated.
1026 ///
1027 /// This method uses a closure to create new values on every push. If
1028 /// you'd rather [`Clone`] a given value, use [`BoundedVec::resize`]. If you
1029 /// want to use the [`Default`] trait to generate values, you can
1030 /// pass [`Default::default`] as the second argument.
1031 ///
1032 /// Returns error if len after resizing would be out of bounds.
1033 ///
1034 /// # Examples
1035 ///
1036 /// ```
1037 /// use bounded_vector::{BoundedVec, bvec, Error};
1038 ///
1039 /// let mut vec: BoundedVec<i32, 1, 5> = bvec![1, 2, 3];
1040 /// vec.resize_with(5, Default::default).expect("In range");
1041 /// assert_eq!(vec.as_slice(), &[1, 2, 3, 0, 0][..]);
1042 /// assert_eq!(vec.resize_with(6, Default::default), Err(Error::OutOfBoundsVec));
1043 /// assert_eq!(vec.as_slice(), &[1, 2, 3, 0, 0][..]);
1044 /// assert_eq!(vec.resize_with(0, Default::default), Err(Error::OutOfBoundsVec));
1045 /// assert_eq!(vec.as_slice(), &[1, 2, 3, 0, 0][..]);
1046 ///
1047 /// let mut vec: BoundedVec<i32, 0, 10> = bvec![];
1048 /// let mut p = 1;
1049 /// vec.resize_with(4, || { p *= 2; p }).expect("In range");
1050 /// assert_eq!(vec.as_slice(), &[2, 4, 8, 16][..]);
1051 /// ```
1052 #[inline]
1053 pub fn resize_with<F>(&mut self, new_len: usize, f: F) -> Result<(), Error>
1054 where
1055 F: FnMut() -> T,
1056 {
1057 if !Self::BOUNDS.contains(&new_len) {
1058 return Err(Error::OutOfBoundsVec);
1059 }
1060
1061 self.0.resize_with(new_len, f);
1062 Ok(())
1063 }
1064
1065 /// Converts BoundedVec into BoundedVec with less strict bounds
1066 ///
1067 /// # Examples
1068 ///
1069 /// ```
1070 /// use bounded_vector::{BoundedVec, bvec};
1071 ///
1072 /// let vec: BoundedVec<i32, 3, 3> = bvec![1,2,3];
1073 /// let vec: BoundedVec<i32, 0, 10> = vec.into_bounded_vec();
1074 /// ```
1075 #[inline]
1076 pub fn into_bounded_vec<const LOW2: usize, const UPP2: usize>(
1077 self,
1078 ) -> BoundedVec<T, LOW2, UPP2> {
1079 let _ = const { assert!(LOW2 <= LOW) };
1080 let _ = const { assert!(UPP2 >= UPP) };
1081
1082 unsafe { BoundedVec::<T, LOW2, UPP2>::from_vec_unchecked(self.to_vec()) }
1083 }
1084
1085 /// Converts BoundedVec into other BoundedVec
1086 ///
1087 /// This method returns error if element count doesn't fit new bounds
1088 ///
1089 /// # Examples
1090 /// ```
1091 /// use bounded_vector::{BoundedVec, bvec, Error};
1092 ///
1093 /// let vec: BoundedVec<i32, 0, 10> = bvec![1,2,3];
1094 /// let vec: BoundedVec<i32, 3, 3> = vec.try_into_bounded_vec().expect("In range");
1095 /// assert_eq!(vec.try_into_bounded_vec::<4, 4>(), Err(Error::OutOfBoundsVec))
1096 /// ```
1097 #[inline]
1098 pub fn try_into_bounded_vec<const LOW2: usize, const UPP2: usize>(
1099 self,
1100 ) -> Result<BoundedVec<T, LOW2, UPP2>, Error> {
1101 if LOW2 <= LOW && UPP2 >= UPP {
1102 return Ok(unsafe { BoundedVec::<T, LOW2, UPP2>::from_vec_unchecked(self.to_vec()) });
1103 }
1104
1105 BoundedVec::try_from(self.to_vec())
1106 }
1107}
1108
1109impl<T: Clone, const LOW: usize, const UPP: usize> BoundedVec<T, LOW, UPP> {
1110 #[doc(hidden)]
1111 #[inline]
1112 pub fn from_elem(elem: T, n: usize) -> Result<Self, Error> {
1113 let _ = Self::VALID_L_U_TEST;
1114 if !Self::BOUNDS.contains(&n) {
1115 return Err(Error::OutOfBoundsVec);
1116 }
1117
1118 Ok(Self(vec![elem; n]))
1119 }
1120
1121 /// Resizes the `BoundedVec` in-place so that `len` is equal to `new_len`.
1122 ///
1123 /// If `new_len` is greater than `len`, the `BoundedVec` is extended by the
1124 /// difference, with each additional slot filled with `value`.
1125 /// If `new_len` is less than `len`, the `BoundedVec` is simply truncated.
1126 ///
1127 /// This method requires `T` to implement [`Clone`],
1128 /// in order to be able to clone the passed value.
1129 /// If you need more flexibility (or want to rely on [`Default`] instead of
1130 /// [`Clone`]), use [`BoundedVec::resize_with`].
1131 /// If you only need to resize to a smaller size, use [`BoundedVec::truncate`].
1132 ///
1133 /// This method returns error if new bound doesn't fit bounds
1134 ///
1135 /// # Examples
1136 ///
1137 /// ```
1138 /// use bounded_vector::{BoundedVec, bvec, Error};
1139 ///
1140 /// let mut vec: BoundedVec<&str, 0, 3> = bvec!["hello"];
1141 /// vec.resize(3, "world").expect("In range");
1142 /// assert_eq!(vec.as_slice(), &["hello", "world", "world"][..]);
1143 /// assert_eq!(vec.resize(4, "world"), Err(Error::OutOfBoundsVec));
1144 /// assert_eq!(vec.as_slice(), &["hello", "world", "world"][..]);
1145 ///
1146 /// let mut vec: BoundedVec<char, 2, 10> = bvec!['a', 'b', 'c', 'd'];
1147 /// vec.resize(2, '_');
1148 /// assert_eq!(vec.as_slice(), &['a', 'b'][..]);
1149 /// assert_eq!(vec.resize(1, '_'), Err(Error::OutOfBoundsVec));
1150 /// assert_eq!(vec.as_slice(), &['a', 'b'][..]);
1151 /// ```
1152 #[inline]
1153 pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), Error> {
1154 if !Self::BOUNDS.contains(&new_len) {
1155 return Err(Error::OutOfBoundsVec);
1156 }
1157
1158 self.0.resize(new_len, value);
1159 Ok(())
1160 }
1161
1162 /// Clones and appends all elements in a slice to the `BoundedVec`.
1163 ///
1164 /// Iterates over the slice `other`, clones each element, and then appends
1165 /// it to this `BoundedVec`. The `other` slice is traversed in-order.
1166 ///
1167 /// Returns error if len after extending would be out of bounds.
1168 ///
1169 /// # Examples
1170 ///
1171 /// ```
1172 /// use bounded_vector::{BoundedVec, bvec, Error};
1173 ///
1174 /// let mut vec: BoundedVec<i32, 0, 5> = bvec![1];
1175 /// vec.extend_from_slice(&[2, 3, 4]).expect("In range");
1176 /// assert_eq!(vec.as_slice(), &[1, 2, 3, 4][..]);
1177 /// assert_eq!(vec.extend_from_slice(&[2, 3]), Err(Error::OutOfBoundsVec));
1178 /// assert_eq!(vec.as_slice(), &[1, 2, 3, 4][..]);
1179 /// ```
1180 #[inline]
1181 pub fn extend_from_slice(&mut self, other: &[T]) -> Result<(), Error> {
1182 if self.len() + other.len() > UPP {
1183 return Err(Error::OutOfBoundsVec);
1184 }
1185
1186 self.0.extend_from_slice(other);
1187 Ok(())
1188 }
1189
1190 /// Given a range `src`, clones a slice of elements in that range and appends it to the end.
1191 ///
1192 /// `src` must be a range that can form a valid subslice of the `BoundedVec`.
1193 ///
1194 /// Returns error if len after extending would be out of bounds.
1195 ///
1196 /// # Panics
1197 ///
1198 /// Panics if starting index is greater than the end index
1199 /// or if the index is greater than the length of the vector.
1200 ///
1201 /// # Examples
1202 ///
1203 /// ```
1204 /// use bounded_vector::{BoundedVec, bvec, Error};
1205 ///
1206 /// let mut characters: BoundedVec<char, 0, 10> = bvec!['a', 'b', 'c', 'd', 'e'];
1207 /// characters.extend_from_within(2..).expect("In range");;
1208 /// assert_eq!(characters.as_slice(), &['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e'][..]);
1209 ///
1210 /// let mut numbers: BoundedVec<i32, 0, 10> = bvec![0, 1, 2, 3, 4];
1211 /// numbers.extend_from_within(..2).expect("In range");
1212 /// assert_eq!(numbers.as_slice(), &[0, 1, 2, 3, 4, 0, 1][..]);
1213 ///
1214 /// let mut strings: BoundedVec<String, 0, 6> = bvec![String::from("hello"), String::from("world"), String::from("!")];
1215 /// strings.extend_from_within(1..=2);
1216 /// assert_eq!(strings.as_slice(), &["hello", "world", "!", "world", "!"][..]);
1217 /// assert_eq!(strings.extend_from_within(1..=2), Err(Error::OutOfBoundsVec));
1218 /// assert_eq!(strings.as_slice(), &["hello", "world", "!", "world", "!"][..]);
1219 /// ```
1220 pub fn extend_from_within<R>(&mut self, src: R) -> Result<(), Error>
1221 where
1222 R: RangeBounds<usize>,
1223 {
1224 let start = match src.start_bound() {
1225 Bound::Unbounded => 0,
1226 Bound::Excluded(v) => v + 1,
1227 Bound::Included(v) => *v,
1228 };
1229
1230 let end = match src.end_bound() {
1231 Bound::Unbounded => self.len(),
1232 Bound::Excluded(v) => *v,
1233 Bound::Included(v) => v + 1,
1234 };
1235
1236 if start > end {
1237 panic!("Range index starts at {start} but ends at {end}")
1238 }
1239
1240 if end > self.len() {
1241 panic!("Range end outside vector")
1242 }
1243
1244 let new_len = end - start + self.len();
1245 if new_len > UPP {
1246 return Err(Error::OutOfBoundsVec);
1247 }
1248
1249 self.0.extend_from_within(src);
1250 if !Self::BOUNDS.contains(&self.len()) {
1251 panic!(
1252 "The length of array({}) is outside LOW and UPP bounds",
1253 self.len()
1254 )
1255 }
1256
1257 Ok(())
1258 }
1259}
1260
1261impl<T, const UPP: usize> BoundedVec<T, 0, UPP> {
1262 /// Constructs a new, empty `BoundedVec<T, LOW, UPP>`.
1263 ///
1264 /// The vector will not allocate until elements are pushed onto it.
1265 ///
1266 /// # Examples
1267 ///
1268 /// ```
1269 /// use bounded_vector::BoundedVec;
1270 ///
1271 /// let vec: BoundedVec<i32, 0, 10> = BoundedVec::new();
1272 /// ```
1273 #[inline]
1274 pub const fn new() -> Self {
1275 let _ = Self::VALID_L_U_TEST;
1276 Self(Vec::new())
1277 }
1278
1279 /// Constructs a new, empty `BoundedVec<T, LOW, UPP>` with at least the specified capacity.
1280 ///
1281 /// The vector will be able to hold at least `capacity` elements without
1282 /// reallocating. This method is allowed to allocate for more elements than
1283 /// `capacity`. If `capacity` is zero, the vector will not allocate.
1284 ///
1285 /// It is important to note that although the returned vector has the
1286 /// minimum *capacity* specified, the vector will have a zero *length*. For
1287 /// an explanation of the difference between length and capacity, see
1288 /// *[Capacity and reallocation]*.
1289 ///
1290 /// If it is important to know the exact allocated capacity of a `Vec`,
1291 /// always use the [`capacity`] method after construction.
1292 ///
1293 /// For `BoundedVec<T, LOW, UPP>` where `T` is a zero-sized type, there will be no allocation
1294 /// and the capacity will always be `usize::MAX`.
1295 ///
1296 /// [Capacity and reallocation]: #capacity-and-reallocation
1297 /// [`capacity`]: BoundedVec::capacity
1298 ///
1299 /// # Panics
1300 ///
1301 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1302 ///
1303 /// # Examples
1304 ///
1305 /// ```
1306 /// use bounded_vector::BoundedVec;
1307 ///
1308 /// let mut vec: BoundedVec<i32, 0, 11> = BoundedVec::with_capacity(10);
1309 ///
1310 /// // The vector contains no items, even though it has capacity for more
1311 /// assert_eq!(vec.len(), 0);
1312 /// assert!(vec.capacity() >= 10);
1313 ///
1314 /// // These are all done without reallocating...
1315 /// for i in 0..10 {
1316 /// vec.push(i).expect("In range");
1317 /// }
1318 /// assert_eq!(vec.len(), 10);
1319 /// assert!(vec.capacity() >= 10);
1320 ///
1321 /// // ...but this may make the vector reallocate
1322 /// vec.push(11).expect("In range");
1323 /// assert_eq!(vec.len(), 11);
1324 /// assert!(vec.capacity() >= 11);
1325 ///
1326 /// // A vector of a zero-sized type will always over-allocate, since no
1327 /// // allocation is necessary
1328 /// let vec_units: BoundedVec<(), 0, 10> = BoundedVec::with_capacity(10);
1329 /// assert_eq!(vec_units.capacity(), usize::MAX);
1330 /// ```
1331 #[inline]
1332 pub fn with_capacity(capacity: usize) -> Self {
1333 let _ = Self::VALID_L_U_TEST;
1334 Self(Vec::with_capacity(capacity))
1335 }
1336
1337 /// Clears the vector, removing all values.
1338 ///
1339 /// Note that this method has no effect on the allocated capacity
1340 /// of the vector.
1341 ///
1342 /// # Examples
1343 ///
1344 /// ```
1345 /// use bounded_vector::{BoundedVec, bvec};
1346 ///
1347 /// let mut v: BoundedVec<i32, 0, 10> = bvec![1, 2, 3];
1348 ///
1349 /// v.clear();
1350 ///
1351 /// assert!(v.is_empty());
1352 /// ```
1353 #[inline]
1354 pub fn clear(&mut self) {
1355 self.0.clear()
1356 }
1357}
1358
1359impl<T, const UPP: usize> Default for BoundedVec<T, 0, UPP> {
1360 fn default() -> Self {
1361 let _ = Self::VALID_L_U_TEST;
1362 Self::new()
1363 }
1364}
1365
1366impl<T, const LOW: usize, const UPP: usize> TryFrom<Vec<T>> for BoundedVec<T, LOW, UPP> {
1367 type Error = Error;
1368 fn try_from(value: Vec<T>) -> Result<Self, Self::Error> {
1369 let _ = Self::VALID_L_U_TEST;
1370 if !Self::BOUNDS.contains(&value.len()) {
1371 return Err(Error::OutOfBoundsVec);
1372 }
1373
1374 Ok(Self(value))
1375 }
1376}
1377
1378impl<T, const LOW: usize, const UPP: usize> TryFrom<Box<[T]>> for BoundedVec<T, LOW, UPP> {
1379 type Error = Error;
1380 fn try_from(value: Box<[T]>) -> Result<Self, Self::Error> {
1381 let _ = Self::VALID_L_U_TEST;
1382 if !Self::BOUNDS.contains(&value.len()) {
1383 return Err(Error::OutOfBoundsVec);
1384 }
1385
1386 Ok(Self(value.into()))
1387 }
1388}
1389
1390impl<T, const LOW: usize, const UPP: usize, const N: usize> From<Box<[T; N]>>
1391 for BoundedVec<T, LOW, UPP>
1392{
1393 fn from(value: Box<[T; N]>) -> Self {
1394 let _ = BoundedVec::<T, LOW, UPP>::VALID_L_U_TEST;
1395 let _ = const { assert!(LOW <= N) };
1396 let _ = const { assert!(UPP >= N) };
1397 let value: Box<[T]> = value;
1398 Self(value.into())
1399 }
1400}
1401
1402impl<T, const LOW: usize, const UPP: usize> From<BoundedVec<T, LOW, UPP>> for Vec<T> {
1403 fn from(value: BoundedVec<T, LOW, UPP>) -> Self {
1404 let _ = BoundedVec::<T, LOW, UPP>::VALID_L_U_TEST;
1405 value.0
1406 }
1407}
1408
1409impl<T, const LOW: usize, const UPP: usize, const N: usize> From<[T; N]>
1410 for BoundedVec<T, LOW, UPP>
1411{
1412 fn from(value: [T; N]) -> Self {
1413 let _ = Self::VALID_L_U_TEST;
1414 let _ = const { assert!(LOW <= N) };
1415 let _ = const { assert!(UPP >= N) };
1416
1417 Self(value.into())
1418 }
1419}
1420
1421impl<T, const LOW: usize, const UPP: usize> AsRef<Vec<T>> for BoundedVec<T, LOW, UPP> {
1422 fn as_ref(&self) -> &Vec<T> {
1423 &self.0
1424 }
1425}
1426
1427impl<T, const LOW: usize, const UPP: usize> Deref for BoundedVec<T, LOW, UPP> {
1428 type Target = [T];
1429 fn deref(&self) -> &Self::Target {
1430 &self.0
1431 }
1432}
1433
1434impl<T, const LOW: usize, const UPP: usize> DerefMut for BoundedVec<T, LOW, UPP> {
1435 fn deref_mut(&mut self) -> &mut Self::Target {
1436 &mut self.0
1437 }
1438}
1439
1440impl<T: Debug, const LOW: usize, const UPP: usize> Debug for BoundedVec<T, LOW, UPP> {
1441 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1442 fmt::Debug::fmt(&*self.0, f)
1443 }
1444}
1445
1446#[cfg(test)]
1447mod tests {
1448 use crate::bvec;
1449
1450 use super::*;
1451
1452 const fn err<T>() -> Result<T, Error> {
1453 Err(Error::OutOfBoundsVec)
1454 }
1455
1456 #[test]
1457 fn try_into_bounded_vec() {
1458 let bvec: BoundedVec<_, 1, 5> = bvec![1, 2, 3, 4];
1459 assert_eq!(
1460 bvec.clone().try_into_bounded_vec::<1, 5>(),
1461 Ok(bvec![1, 2, 3, 4])
1462 );
1463 assert_eq!(
1464 bvec.clone().try_into_bounded_vec::<4, 4>(),
1465 Ok(bvec![1, 2, 3, 4])
1466 );
1467 assert_eq!(
1468 bvec.clone().try_into_bounded_vec::<3, 5>(),
1469 Ok(bvec![1, 2, 3, 4])
1470 );
1471 assert_eq!(
1472 bvec.clone().try_into_bounded_vec::<0, 5>(),
1473 Ok(bvec![1, 2, 3, 4])
1474 );
1475 assert_eq!(
1476 bvec.clone().try_into_bounded_vec::<1, 4>(),
1477 Ok(bvec![1, 2, 3, 4])
1478 );
1479 assert_eq!(
1480 bvec.clone().try_into_bounded_vec::<0, 6>(),
1481 Ok(bvec![1, 2, 3, 4])
1482 );
1483 assert_eq!(
1484 bvec.clone().try_into_bounded_vec::<1, 3>(),
1485 Err(Error::OutOfBoundsVec)
1486 );
1487 assert_eq!(
1488 bvec.try_into_bounded_vec::<5, 5>(),
1489 Err(Error::OutOfBoundsVec)
1490 );
1491 }
1492
1493 #[test]
1494 fn format() {
1495 let bvec: BoundedVec<_, 0, 10> = bvec![1, 2, 3];
1496 assert_eq!("[1, 2, 3]", format!("{:?}", bvec));
1497 }
1498
1499 #[test]
1500 fn format_hash() {
1501 let bvec: BoundedVec<_, 0, 10> = bvec![1, 2, 3];
1502 assert_eq!("[\n 1,\n 2,\n 3,\n]", format!("{:#?}", bvec));
1503 }
1504
1505 #[test]
1506 fn from_array() {
1507 let bounded_vec = BoundedVec::<_, 2, 3>::from([1, 2, 3]);
1508 assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1509 }
1510
1511 #[test]
1512 fn try_from_box_array() {
1513 let bounded_vec =
1514 BoundedVec::<_, 2, 3>::try_from(vec![1, 2, 3].into_boxed_slice()).unwrap();
1515 assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1516
1517 let bounded_vec = BoundedVec::<_, 1, 2>::try_from(vec![1, 2, 3].into_boxed_slice());
1518 assert_eq!(err(), bounded_vec);
1519 }
1520
1521 #[test]
1522 fn try_from_vec() {
1523 let bounded_vec = BoundedVec::<_, 2, 3>::try_from(vec![1, 2, 3]).unwrap();
1524 assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1525
1526 let bounded_vec = BoundedVec::<_, 1, 2>::try_from(vec![1, 2, 3]);
1527 assert_eq!(err(), bounded_vec);
1528 }
1529
1530 #[test]
1531 fn new() {
1532 assert_eq!(Vec::<()>::new(), BoundedVec::<(), 0, 0>::new().to_vec());
1533 }
1534
1535 #[test]
1536 fn with_capacity() {
1537 assert_eq!(
1538 BoundedVec::<(), 0, 0>::new(),
1539 BoundedVec::<(), 0, 0>::with_capacity(0)
1540 );
1541 }
1542
1543 #[test]
1544 fn truncate() {
1545 let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1546 bounded_vec.truncate(2).unwrap();
1547 assert_eq!(vec![1, 2], bounded_vec.to_vec());
1548
1549 let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1550 assert_eq!(err(), bounded_vec.truncate(1));
1551 assert_eq!(vec![1, 2, 3], bounded_vec.to_vec())
1552 }
1553
1554 #[test]
1555 fn swap_remove() {
1556 let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1557 assert_eq!(Ok(1), bounded_vec.swap_remove(0));
1558 assert_eq!(vec![3, 2], bounded_vec.to_vec());
1559
1560 let mut bounded_vec: BoundedVec<i32, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1561 assert_eq!(err(), bounded_vec.swap_remove(0));
1562 assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1563 }
1564
1565 #[test]
1566 fn insert() {
1567 let mut bounded_vec: BoundedVec<i32, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1568 bounded_vec.insert(2, 20).unwrap();
1569 assert_eq!(vec![1, 2, 20, 3], bounded_vec.to_vec());
1570
1571 let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1572 assert_eq!(err(), bounded_vec.insert(3, 4));
1573 assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1574 }
1575
1576 #[test]
1577 fn remove() {
1578 let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1579 assert_eq!(Ok(2), bounded_vec.remove(1));
1580 assert_eq!(vec![1, 3], bounded_vec.to_vec());
1581
1582 let mut bounded_vec: BoundedVec<i32, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1583 assert_eq!(err(), bounded_vec.remove(1));
1584 assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1585 }
1586
1587 #[test]
1588 fn retain() {
1589 let bounded_vec: BoundedVec<i32, 1, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1590 let bounded_vec = bounded_vec.retain(|x| *x == 3).unwrap();
1591 assert_eq!(vec![3], bounded_vec.to_vec());
1592
1593 let bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1594 assert_eq!(err(), bounded_vec.retain(|x| *x == 2));
1595 }
1596
1597 #[test]
1598 fn retain_mut() {
1599 let bounded_vec: BoundedVec<i32, 1, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1600 let bounded_vec = bounded_vec
1601 .retain_mut(|x| {
1602 *x *= 2;
1603 *x == 6
1604 })
1605 .unwrap();
1606
1607 assert_eq!(vec![6], bounded_vec.to_vec());
1608
1609 let bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1610 assert_eq!(
1611 err(),
1612 bounded_vec.retain_mut(|x| {
1613 *x *= 2;
1614 *x == 6
1615 })
1616 )
1617 }
1618
1619 #[test]
1620 fn dedup_by_key() {
1621 let bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 1, 2]).unwrap();
1622 let bounded_vec = bounded_vec.dedup_by_key(|x| *x).unwrap();
1623 assert_eq!(vec![1, 2], bounded_vec.to_vec());
1624
1625 let bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 1, 2]).unwrap();
1626 assert_eq!(err(), bounded_vec.dedup_by_key(|x| *x));
1627 }
1628
1629 #[test]
1630 fn dedup_by() {
1631 let bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 1, 2]).unwrap();
1632 let bounded_vec = bounded_vec.dedup_by(|x, y| x == y).unwrap();
1633 assert_eq!(vec![1, 2], bounded_vec.to_vec());
1634
1635 let bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 1, 2]).unwrap();
1636 assert_eq!(err(), bounded_vec.dedup_by(|x, y| x == y));
1637 }
1638
1639 #[test]
1640 fn push() {
1641 let mut bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1642 bounded_vec.push(4).unwrap();
1643 assert_eq!(vec![1, 2, 3, 4], bounded_vec.to_vec());
1644
1645 let mut bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1646 assert_eq!(err(), bounded_vec.push(4));
1647 assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1648 }
1649
1650 #[test]
1651 fn pop() {
1652 let mut bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1653 assert_eq!(3, bounded_vec.pop().unwrap());
1654 assert_eq!(vec![1, 2], bounded_vec.to_vec());
1655
1656 let mut bounded_vec: BoundedVec<_, 3, 5> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1657 assert_eq!(err(), bounded_vec.pop());
1658 assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1659 }
1660
1661 #[test]
1662 fn append() {
1663 let mut vec = vec![4, 5];
1664 let mut bounded_vec: BoundedVec<_, 3, 5> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1665 bounded_vec.append(&mut vec).unwrap();
1666 assert_eq!(Vec::<i32>::new(), vec);
1667 assert_eq!(vec![1, 2, 3, 4, 5], bounded_vec.to_vec());
1668
1669 let mut vec = vec![4, 5];
1670 let mut bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1671 assert_eq!(err(), bounded_vec.append(&mut vec));
1672 assert_eq!(vec![4, 5], vec);
1673 assert_eq!(vec![1, 2, 3], bounded_vec.to_vec())
1674 }
1675
1676 #[test]
1677 fn clear() {
1678 let mut bounded_vec: BoundedVec<_, 0, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1679 bounded_vec.clear();
1680 assert_eq!(BoundedVec::new(), bounded_vec);
1681 }
1682
1683 #[test]
1684 fn split_off() {
1685 let mut bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1686 assert_eq!(vec![3], bounded_vec.split_off(2).unwrap());
1687 assert_eq!(vec![1, 2], bounded_vec.to_vec());
1688
1689 let mut bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1690 assert_eq!(err(), bounded_vec.split_off(2));
1691 assert_eq!(vec![1, 2, 3], bounded_vec.to_vec())
1692 }
1693
1694 #[test]
1695 fn resize_with() {
1696 let mut bounded_vec: BoundedVec<_, 3, 5> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1697 bounded_vec.resize_with(5, || 0).unwrap();
1698 assert_eq!(vec![1, 2, 3, 0, 0], bounded_vec.to_vec());
1699
1700 let mut bounded_vec: BoundedVec<_, 1, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1701 bounded_vec.resize_with(1, || 0).unwrap();
1702 assert_eq!(vec![1], bounded_vec.to_vec());
1703
1704 let mut bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1705 assert_eq!(err(), bounded_vec.resize_with(5, || 0));
1706 assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1707
1708 let mut bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1709 assert_eq!(err(), bounded_vec.resize_with(1, || 0));
1710 assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1711 }
1712
1713 #[test]
1714 fn from_elem() {
1715 let bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::from_elem(3, 4).unwrap();
1716 assert_eq!(vec![3, 3, 3, 3], bounded_vec.to_vec());
1717
1718 let bounded_vec = BoundedVec::<_, 2, 3>::from_elem(3, 4);
1719 assert_eq!(err(), bounded_vec)
1720 }
1721
1722 #[test]
1723 pub fn resize() {
1724 let mut bounded_vec = BoundedVec::<_, 1, 3>::try_from(vec![1, 2, 3]).unwrap();
1725 bounded_vec.resize(1, 2).unwrap();
1726 assert_eq!(&vec![1], bounded_vec.as_vec());
1727 bounded_vec.resize(3, 2).unwrap();
1728 assert_eq!(&vec![1, 2, 2], bounded_vec.as_vec());
1729 assert_eq!(err(), bounded_vec.resize(4, 2));
1730 assert_eq!(vec![1, 2, 2], bounded_vec.to_vec());
1731 }
1732
1733 #[test]
1734 pub fn extend_from_slice() {
1735 let mut bounded_vec = BoundedVec::<_, 3, 5>::try_from(vec![1, 2, 3]).unwrap();
1736 bounded_vec.extend_from_slice(&[4, 5]).unwrap();
1737 assert_eq!(&vec![1, 2, 3, 4, 5], bounded_vec.as_vec());
1738 assert_eq!(err(), bounded_vec.extend_from_slice(&[6]));
1739 assert_eq!(&vec![1, 2, 3, 4, 5], bounded_vec.as_vec());
1740 }
1741
1742 #[test]
1743 pub fn extend_from_within() {
1744 let mut bounded_vec = BoundedVec::<_, 3, 5>::try_from(vec![1, 2, 3]).unwrap();
1745 bounded_vec.extend_from_within(1..).unwrap();
1746 assert_eq!(&vec![1, 2, 3, 2, 3], bounded_vec.as_vec());
1747 bounded_vec.extend_from_within(4..4).unwrap();
1748 assert_eq!(&vec![1, 2, 3, 2, 3], bounded_vec.as_vec());
1749 assert_eq!(err(), bounded_vec.extend_from_within(4..=4));
1750 assert_eq!(&vec![1, 2, 3, 2, 3], bounded_vec.as_vec())
1751 }
1752}