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].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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"].expect("In range");
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'].expect("In range");
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'].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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"].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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'].expect("In range");
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].expect("In range");
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].expect("In range");
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].expect("In range");
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		if !Self::BOUNDS.contains(&n) {
1114			return Err(Error::OutOfBoundsVec);
1115		}
1116
1117		Ok(Self(vec![elem; n]))
1118	}
1119
1120	/// Resizes the `BoundedVec` in-place so that `len` is equal to `new_len`.
1121	///
1122	/// If `new_len` is greater than `len`, the `BoundedVec` is extended by the
1123	/// difference, with each additional slot filled with `value`.
1124	/// If `new_len` is less than `len`, the `BoundedVec` is simply truncated.
1125	///
1126	/// This method requires `T` to implement [`Clone`],
1127	/// in order to be able to clone the passed value.
1128	/// If you need more flexibility (or want to rely on [`Default`] instead of
1129	/// [`Clone`]), use [`BoundedVec::resize_with`].
1130	/// If you only need to resize to a smaller size, use [`BoundedVec::truncate`].
1131	///
1132	/// This method returns error if new bound doesn't fit bounds
1133	///
1134	/// # Examples
1135	///
1136	/// ```
1137	/// use bounded_vector::{BoundedVec, bvec, Error};
1138	///
1139	/// let mut vec: BoundedVec<&str, 0, 3> = bvec!["hello"].expect("In range");
1140	/// vec.resize(3, "world").expect("In range");
1141	/// assert_eq!(vec.as_slice(), &["hello", "world", "world"][..]);
1142	/// assert_eq!(vec.resize(4, "world"), Err(Error::OutOfBoundsVec));
1143	/// assert_eq!(vec.as_slice(), &["hello", "world", "world"][..]);
1144	///
1145	/// let mut vec: BoundedVec<char, 2, 10> = bvec!['a', 'b', 'c', 'd'].expect("In range");
1146	/// vec.resize(2, '_');
1147	/// assert_eq!(vec.as_slice(), &['a', 'b'][..]);
1148	/// assert_eq!(vec.resize(1, '_'), Err(Error::OutOfBoundsVec));
1149	/// assert_eq!(vec.as_slice(), &['a', 'b'][..]);
1150	/// ```
1151	#[inline]
1152	pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), Error> {
1153		if !Self::BOUNDS.contains(&new_len) {
1154			return Err(Error::OutOfBoundsVec);
1155		}
1156
1157		self.0.resize(new_len, value);
1158		Ok(())
1159	}
1160
1161	/// Clones and appends all elements in a slice to the `BoundedVec`.
1162	///
1163	/// Iterates over the slice `other`, clones each element, and then appends
1164	/// it to this `BoundedVec`. The `other` slice is traversed in-order.
1165	///
1166	/// Returns error if len after extending would be out of bounds.
1167	///
1168	/// # Examples
1169	///
1170	/// ```
1171	/// use bounded_vector::{BoundedVec, bvec, Error};
1172	///
1173	/// let mut vec: BoundedVec<i32, 0, 5> = bvec![1].expect("In range");
1174	/// vec.extend_from_slice(&[2, 3, 4]).expect("In range");
1175	/// assert_eq!(vec.as_slice(), &[1, 2, 3, 4][..]);
1176	/// assert_eq!(vec.extend_from_slice(&[2, 3]), Err(Error::OutOfBoundsVec));
1177	/// assert_eq!(vec.as_slice(), &[1, 2, 3, 4][..]);
1178	/// ```
1179	#[inline]
1180	pub fn extend_from_slice(&mut self, other: &[T]) -> Result<(), Error> {
1181		if self.len() + other.len() > UPP {
1182			return Err(Error::OutOfBoundsVec);
1183		}
1184
1185		self.0.extend_from_slice(other);
1186		Ok(())
1187	}
1188
1189	/// Given a range `src`, clones a slice of elements in that range and appends it to the end.
1190	///
1191	/// `src` must be a range that can form a valid subslice of the `BoundedVec`.
1192	///
1193	/// Returns error if len after extending would be out of bounds.
1194	///
1195	/// # Panics
1196	///
1197	/// Panics if starting index is greater than the end index
1198	/// or if the index is greater than the length of the vector.
1199	///
1200	/// # Examples
1201	///
1202	/// ```
1203	/// use bounded_vector::{BoundedVec, bvec, Error};
1204	///
1205	/// let mut characters: BoundedVec<char, 0, 10> = bvec!['a', 'b', 'c', 'd', 'e'].expect("In range");
1206	/// characters.extend_from_within(2..).expect("In range");;
1207	/// assert_eq!(characters.as_slice(), &['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e'][..]);
1208	///
1209	/// let mut numbers: BoundedVec<i32, 0, 10> = bvec![0, 1, 2, 3, 4].expect("In range");
1210	/// numbers.extend_from_within(..2).expect("In range");
1211	/// assert_eq!(numbers.as_slice(), &[0, 1, 2, 3, 4, 0, 1][..]);
1212	///
1213	/// let mut strings: BoundedVec<String, 0, 6> = bvec![String::from("hello"), String::from("world"), String::from("!")].expect("In range");
1214	/// strings.extend_from_within(1..=2);
1215	/// assert_eq!(strings.as_slice(), &["hello", "world", "!", "world", "!"][..]);
1216	/// assert_eq!(strings.extend_from_within(1..=2), Err(Error::OutOfBoundsVec));
1217	/// assert_eq!(strings.as_slice(), &["hello", "world", "!", "world", "!"][..]);
1218	/// ```
1219	pub fn extend_from_within<R>(&mut self, src: R) -> Result<(), Error>
1220	where
1221		R: RangeBounds<usize>,
1222	{
1223		let start = match src.start_bound() {
1224			Bound::Unbounded => 0,
1225			Bound::Excluded(v) => v + 1,
1226			Bound::Included(v) => *v,
1227		};
1228
1229		let end = match src.end_bound() {
1230			Bound::Unbounded => self.len(),
1231			Bound::Excluded(v) => *v,
1232			Bound::Included(v) => v + 1,
1233		};
1234
1235		if start > end {
1236			panic!("Range index starts at {start} but ends at {end}")
1237		}
1238
1239		if end > self.len() {
1240			panic!("Range end outside vector")
1241		}
1242
1243		let new_len = end - start + self.len();
1244		if new_len > UPP {
1245			return Err(Error::OutOfBoundsVec);
1246		}
1247
1248		self.0.extend_from_within(src);
1249		if !Self::BOUNDS.contains(&self.len()) {
1250			panic!(
1251				"The length of array({}) is outside LOW and UPP bounds",
1252				self.len()
1253			)
1254		}
1255
1256		Ok(())
1257	}
1258}
1259
1260impl<T, const UPP: usize> BoundedVec<T, 0, UPP> {
1261	/// Constructs a new, empty `BoundedVec<T, LOW, UPP>`.
1262	///
1263	/// The vector will not allocate until elements are pushed onto it.
1264	///
1265	/// # Examples
1266	///
1267	/// ```
1268	/// use bounded_vector::BoundedVec;
1269	///
1270	/// let vec: BoundedVec<i32, 0, 10> = BoundedVec::new();
1271	/// ```
1272	#[inline]
1273	pub const fn new() -> Self {
1274		let _ = Self::VALID_L_U_TEST;
1275		Self(Vec::new())
1276	}
1277
1278	/// Constructs a new, empty `BoundedVec<T, LOW, UPP>` with at least the specified capacity.
1279	///
1280	/// The vector will be able to hold at least `capacity` elements without
1281	/// reallocating. This method is allowed to allocate for more elements than
1282	/// `capacity`. If `capacity` is zero, the vector will not allocate.
1283	///
1284	/// It is important to note that although the returned vector has the
1285	/// minimum *capacity* specified, the vector will have a zero *length*. For
1286	/// an explanation of the difference between length and capacity, see
1287	/// *[Capacity and reallocation]*.
1288	///
1289	/// If it is important to know the exact allocated capacity of a `Vec`,
1290	/// always use the [`capacity`] method after construction.
1291	///
1292	/// For `BoundedVec<T, LOW, UPP>` where `T` is a zero-sized type, there will be no allocation
1293	/// and the capacity will always be `usize::MAX`.
1294	///
1295	/// [Capacity and reallocation]: #capacity-and-reallocation
1296	/// [`capacity`]: BoundedVec::capacity
1297	///
1298	/// # Panics
1299	///
1300	/// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1301	///
1302	/// # Examples
1303	///
1304	/// ```
1305	/// use bounded_vector::BoundedVec;
1306	///
1307	/// let mut vec: BoundedVec<i32, 0, 11> = BoundedVec::with_capacity(10);
1308	///
1309	/// // The vector contains no items, even though it has capacity for more
1310	/// assert_eq!(vec.len(), 0);
1311	/// assert!(vec.capacity() >= 10);
1312	///
1313	/// // These are all done without reallocating...
1314	/// for i in 0..10 {
1315	///     vec.push(i).expect("In range");
1316	/// }
1317	/// assert_eq!(vec.len(), 10);
1318	/// assert!(vec.capacity() >= 10);
1319	///
1320	/// // ...but this may make the vector reallocate
1321	/// vec.push(11).expect("In range");
1322	/// assert_eq!(vec.len(), 11);
1323	/// assert!(vec.capacity() >= 11);
1324	///
1325	/// // A vector of a zero-sized type will always over-allocate, since no
1326	/// // allocation is necessary
1327	/// let vec_units: BoundedVec<(), 0, 10> = BoundedVec::with_capacity(10);
1328	/// assert_eq!(vec_units.capacity(), usize::MAX);
1329	/// ```
1330	#[inline]
1331	pub fn with_capacity(capacity: usize) -> Self {
1332		let _ = Self::VALID_L_U_TEST;
1333		Self(Vec::with_capacity(capacity))
1334	}
1335
1336	/// Clears the vector, removing all values.
1337	///
1338	/// Note that this method has no effect on the allocated capacity
1339	/// of the vector.
1340	///
1341	/// # Examples
1342	///
1343	/// ```
1344	/// use bounded_vector::{BoundedVec, bvec};
1345	///
1346	/// let mut v: BoundedVec<i32, 0, 10> = bvec![1, 2, 3].expect("In range");
1347	///
1348	/// v.clear();
1349	///
1350	/// assert!(v.is_empty());
1351	/// ```
1352	#[inline]
1353	pub fn clear(&mut self) {
1354		self.0.clear()
1355	}
1356}
1357
1358impl<T, const UPP: usize> Default for BoundedVec<T, 0, UPP> {
1359	fn default() -> Self {
1360		Self::new()
1361	}
1362}
1363
1364impl<T, const LOW: usize, const UPP: usize> TryFrom<Vec<T>> for BoundedVec<T, LOW, UPP> {
1365	type Error = Error;
1366	fn try_from(value: Vec<T>) -> Result<Self, Self::Error> {
1367		let _ = Self::VALID_L_U_TEST;
1368		if !Self::BOUNDS.contains(&value.len()) {
1369			return Err(Error::OutOfBoundsVec);
1370		}
1371
1372		Ok(Self(value))
1373	}
1374}
1375
1376impl<T, const LOW: usize, const UPP: usize> TryFrom<Box<[T]>> for BoundedVec<T, LOW, UPP> {
1377	type Error = Error;
1378	fn try_from(value: Box<[T]>) -> Result<Self, Self::Error> {
1379		let _ = Self::VALID_L_U_TEST;
1380		if !Self::BOUNDS.contains(&value.len()) {
1381			return Err(Error::OutOfBoundsVec);
1382		}
1383
1384		Ok(Self(value.into()))
1385	}
1386}
1387
1388impl<T, const LOW: usize, const UPP: usize> From<BoundedVec<T, LOW, UPP>> for Vec<T> {
1389	fn from(value: BoundedVec<T, LOW, UPP>) -> Self {
1390		let _ = BoundedVec::<T, LOW, UPP>::VALID_L_U_TEST;
1391		value.0
1392	}
1393}
1394
1395impl<T, const LOW: usize, const UPP: usize, const N: usize> TryFrom<[T; N]>
1396	for BoundedVec<T, LOW, UPP>
1397{
1398	type Error = Error;
1399	fn try_from(value: [T; N]) -> Result<Self, Self::Error> {
1400		let _ = Self::VALID_L_U_TEST;
1401		if !Self::BOUNDS.contains(&N) {
1402			return Err(Error::OutOfBoundsVec);
1403		}
1404
1405		Ok(Self(value.into()))
1406	}
1407}
1408
1409impl<T, const LOW: usize, const UPP: usize> AsRef<Vec<T>> for BoundedVec<T, LOW, UPP> {
1410	fn as_ref(&self) -> &Vec<T> {
1411		&self.0
1412	}
1413}
1414
1415impl<T, const LOW: usize, const UPP: usize> Deref for BoundedVec<T, LOW, UPP> {
1416	type Target = [T];
1417	fn deref(&self) -> &Self::Target {
1418		&self.0
1419	}
1420}
1421
1422impl<T, const LOW: usize, const UPP: usize> DerefMut for BoundedVec<T, LOW, UPP> {
1423	fn deref_mut(&mut self) -> &mut Self::Target {
1424		&mut self.0
1425	}
1426}
1427
1428impl<T: Debug, const LOW: usize, const UPP: usize> Debug for BoundedVec<T, LOW, UPP> {
1429	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1430		fmt::Debug::fmt(&*self.0, f)
1431	}
1432}
1433
1434#[cfg(test)]
1435mod tests {
1436	use crate::bvec;
1437
1438	use super::*;
1439
1440	const fn err<T>() -> Result<T, Error> {
1441		Err(Error::OutOfBoundsVec)
1442	}
1443
1444	#[test]
1445	fn try_into_bounded_vec() {
1446		let bvec: BoundedVec<_, 1, 5> = bvec![1, 2, 3, 4].unwrap();
1447		assert_eq!(
1448			bvec.clone().try_into_bounded_vec::<1, 5>(),
1449			Ok(bvec![1, 2, 3, 4].unwrap())
1450		);
1451		assert_eq!(
1452			bvec.clone().try_into_bounded_vec::<4, 4>(),
1453			Ok(bvec![1, 2, 3, 4].unwrap())
1454		);
1455		assert_eq!(
1456			bvec.clone().try_into_bounded_vec::<3, 5>(),
1457			Ok(bvec![1, 2, 3, 4].unwrap())
1458		);
1459		assert_eq!(
1460			bvec.clone().try_into_bounded_vec::<0, 5>(),
1461			Ok(bvec![1, 2, 3, 4].unwrap())
1462		);
1463		assert_eq!(
1464			bvec.clone().try_into_bounded_vec::<1, 4>(),
1465			Ok(bvec![1, 2, 3, 4].unwrap())
1466		);
1467		assert_eq!(
1468			bvec.clone().try_into_bounded_vec::<0, 6>(),
1469			Ok(bvec![1, 2, 3, 4].unwrap())
1470		);
1471		assert_eq!(
1472			bvec.clone().try_into_bounded_vec::<1, 3>(),
1473			Err(Error::OutOfBoundsVec)
1474		);
1475		assert_eq!(
1476			bvec.try_into_bounded_vec::<5, 5>(),
1477			Err(Error::OutOfBoundsVec)
1478		);
1479	}
1480
1481	#[test]
1482	fn format() {
1483		let bvec: BoundedVec<_, 0, 10> = bvec![1, 2, 3].unwrap();
1484		assert_eq!("[1, 2, 3]", format!("{:?}", bvec));
1485	}
1486
1487	#[test]
1488	fn format_hash() {
1489		let bvec: BoundedVec<_, 0, 10> = bvec![1, 2, 3].unwrap();
1490		assert_eq!("[\n    1,\n    2,\n    3,\n]", format!("{:#?}", bvec));
1491	}
1492
1493	#[test]
1494	fn try_from_array() {
1495		let bounded_vec = BoundedVec::<_, 2, 3>::try_from([1, 2, 3]).unwrap();
1496		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1497
1498		let bounded_vec = BoundedVec::<_, 1, 2>::try_from([1, 2, 3]);
1499		assert_eq!(err(), bounded_vec);
1500	}
1501
1502	#[test]
1503	fn try_from_box_array() {
1504		let bounded_vec =
1505			BoundedVec::<_, 2, 3>::try_from(vec![1, 2, 3].into_boxed_slice()).unwrap();
1506		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1507
1508		let bounded_vec = BoundedVec::<_, 1, 2>::try_from(vec![1, 2, 3].into_boxed_slice());
1509		assert_eq!(err(), bounded_vec);
1510	}
1511
1512	#[test]
1513	fn try_from_vec() {
1514		let bounded_vec = BoundedVec::<_, 2, 3>::try_from(vec![1, 2, 3]).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]);
1518		assert_eq!(err(), bounded_vec);
1519	}
1520
1521	#[test]
1522	fn new() {
1523		assert_eq!(Vec::<()>::new(), BoundedVec::<(), 0, 0>::new().to_vec());
1524	}
1525
1526	#[test]
1527	fn with_capacity() {
1528		assert_eq!(
1529			BoundedVec::<(), 0, 0>::new(),
1530			BoundedVec::<(), 0, 0>::with_capacity(0)
1531		);
1532	}
1533
1534	#[test]
1535	fn truncate() {
1536		let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1537		bounded_vec.truncate(2).unwrap();
1538		assert_eq!(vec![1, 2], bounded_vec.to_vec());
1539
1540		let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1541		assert_eq!(err(), bounded_vec.truncate(1));
1542		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec())
1543	}
1544
1545	#[test]
1546	fn swap_remove() {
1547		let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1548		assert_eq!(Ok(1), bounded_vec.swap_remove(0));
1549		assert_eq!(vec![3, 2], bounded_vec.to_vec());
1550
1551		let mut bounded_vec: BoundedVec<i32, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1552		assert_eq!(err(), bounded_vec.swap_remove(0));
1553		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1554	}
1555
1556	#[test]
1557	fn insert() {
1558		let mut bounded_vec: BoundedVec<i32, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1559		bounded_vec.insert(2, 20).unwrap();
1560		assert_eq!(vec![1, 2, 20, 3], bounded_vec.to_vec());
1561
1562		let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1563		assert_eq!(err(), bounded_vec.insert(3, 4));
1564		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1565	}
1566
1567	#[test]
1568	fn remove() {
1569		let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1570		assert_eq!(Ok(2), bounded_vec.remove(1));
1571		assert_eq!(vec![1, 3], bounded_vec.to_vec());
1572
1573		let mut bounded_vec: BoundedVec<i32, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1574		assert_eq!(err(), bounded_vec.remove(1));
1575		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1576	}
1577
1578	#[test]
1579	fn retain() {
1580		let bounded_vec: BoundedVec<i32, 1, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1581		let bounded_vec = bounded_vec.retain(|x| *x == 3).unwrap();
1582		assert_eq!(vec![3], bounded_vec.to_vec());
1583
1584		let bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1585		assert_eq!(err(), bounded_vec.retain(|x| *x == 2));
1586	}
1587
1588	#[test]
1589	fn retain_mut() {
1590		let bounded_vec: BoundedVec<i32, 1, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1591		let bounded_vec = bounded_vec
1592			.retain_mut(|x| {
1593				*x *= 2;
1594				*x == 6
1595			})
1596			.unwrap();
1597
1598		assert_eq!(vec![6], bounded_vec.to_vec());
1599
1600		let bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1601		assert_eq!(
1602			err(),
1603			bounded_vec.retain_mut(|x| {
1604				*x *= 2;
1605				*x == 6
1606			})
1607		)
1608	}
1609
1610	#[test]
1611	fn dedup_by_key() {
1612		let bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 1, 2]).unwrap();
1613		let bounded_vec = bounded_vec.dedup_by_key(|x| *x).unwrap();
1614		assert_eq!(vec![1, 2], bounded_vec.to_vec());
1615
1616		let bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 1, 2]).unwrap();
1617		assert_eq!(err(), bounded_vec.dedup_by_key(|x| *x));
1618	}
1619
1620	#[test]
1621	fn dedup_by() {
1622		let bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 1, 2]).unwrap();
1623		let bounded_vec = bounded_vec.dedup_by(|x, y| x == y).unwrap();
1624		assert_eq!(vec![1, 2], bounded_vec.to_vec());
1625
1626		let bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 1, 2]).unwrap();
1627		assert_eq!(err(), bounded_vec.dedup_by(|x, y| x == y));
1628	}
1629
1630	#[test]
1631	fn push() {
1632		let mut bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1633		bounded_vec.push(4).unwrap();
1634		assert_eq!(vec![1, 2, 3, 4], bounded_vec.to_vec());
1635
1636		let mut bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1637		assert_eq!(err(), bounded_vec.push(4));
1638		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1639	}
1640
1641	#[test]
1642	fn pop() {
1643		let mut bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1644		assert_eq!(3, bounded_vec.pop().unwrap());
1645		assert_eq!(vec![1, 2], bounded_vec.to_vec());
1646
1647		let mut bounded_vec: BoundedVec<_, 3, 5> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1648		assert_eq!(err(), bounded_vec.pop());
1649		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1650	}
1651
1652	#[test]
1653	fn append() {
1654		let mut vec = vec![4, 5];
1655		let mut bounded_vec: BoundedVec<_, 3, 5> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1656		bounded_vec.append(&mut vec).unwrap();
1657		assert_eq!(Vec::<i32>::new(), vec);
1658		assert_eq!(vec![1, 2, 3, 4, 5], bounded_vec.to_vec());
1659
1660		let mut vec = vec![4, 5];
1661		let mut bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1662		assert_eq!(err(), bounded_vec.append(&mut vec));
1663		assert_eq!(vec![4, 5], vec);
1664		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec())
1665	}
1666
1667	#[test]
1668	fn clear() {
1669		let mut bounded_vec: BoundedVec<_, 0, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1670		bounded_vec.clear();
1671		assert_eq!(BoundedVec::new(), bounded_vec);
1672	}
1673
1674	#[test]
1675	fn split_off() {
1676		let mut bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1677		assert_eq!(vec![3], bounded_vec.split_off(2).unwrap());
1678		assert_eq!(vec![1, 2], bounded_vec.to_vec());
1679
1680		let mut bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1681		assert_eq!(err(), bounded_vec.split_off(2));
1682		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec())
1683	}
1684
1685	#[test]
1686	fn resize_with() {
1687		let mut bounded_vec: BoundedVec<_, 3, 5> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1688		bounded_vec.resize_with(5, || 0).unwrap();
1689		assert_eq!(vec![1, 2, 3, 0, 0], bounded_vec.to_vec());
1690
1691		let mut bounded_vec: BoundedVec<_, 1, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1692		bounded_vec.resize_with(1, || 0).unwrap();
1693		assert_eq!(vec![1], bounded_vec.to_vec());
1694
1695		let mut bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1696		assert_eq!(err(), bounded_vec.resize_with(5, || 0));
1697		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1698
1699		let mut bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
1700		assert_eq!(err(), bounded_vec.resize_with(1, || 0));
1701		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
1702	}
1703
1704	#[test]
1705	fn from_elem() {
1706		let bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::from_elem(3, 4).unwrap();
1707		assert_eq!(vec![3, 3, 3, 3], bounded_vec.to_vec());
1708
1709		let bounded_vec = BoundedVec::<_, 2, 3>::from_elem(3, 4);
1710		assert_eq!(err(), bounded_vec)
1711	}
1712
1713	#[test]
1714	pub fn resize() {
1715		let mut bounded_vec = BoundedVec::<_, 1, 3>::try_from(vec![1, 2, 3]).unwrap();
1716		bounded_vec.resize(1, 2).unwrap();
1717		assert_eq!(&vec![1], bounded_vec.as_vec());
1718		bounded_vec.resize(3, 2).unwrap();
1719		assert_eq!(&vec![1, 2, 2], bounded_vec.as_vec());
1720		assert_eq!(err(), bounded_vec.resize(4, 2));
1721		assert_eq!(vec![1, 2, 2], bounded_vec.to_vec());
1722	}
1723
1724	#[test]
1725	pub fn extend_from_slice() {
1726		let mut bounded_vec = BoundedVec::<_, 3, 5>::try_from(vec![1, 2, 3]).unwrap();
1727		bounded_vec.extend_from_slice(&[4, 5]).unwrap();
1728		assert_eq!(&vec![1, 2, 3, 4, 5], bounded_vec.as_vec());
1729		assert_eq!(err(), bounded_vec.extend_from_slice(&[6]));
1730		assert_eq!(&vec![1, 2, 3, 4, 5], bounded_vec.as_vec());
1731	}
1732
1733	#[test]
1734	pub fn extend_from_within() {
1735		let mut bounded_vec = BoundedVec::<_, 3, 5>::try_from(vec![1, 2, 3]).unwrap();
1736		bounded_vec.extend_from_within(1..).unwrap();
1737		assert_eq!(&vec![1, 2, 3, 2, 3], bounded_vec.as_vec());
1738		bounded_vec.extend_from_within(4..4).unwrap();
1739		assert_eq!(&vec![1, 2, 3, 2, 3], bounded_vec.as_vec());
1740		assert_eq!(err(), bounded_vec.extend_from_within(4..=4));
1741		assert_eq!(&vec![1, 2, 3, 2, 3], bounded_vec.as_vec())
1742	}
1743}