1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
#![allow(clippy::let_unit_value)]

use core::fmt;
use std::{
	collections::TryReserveError,
	fmt::Debug,
	ops::{Bound, Deref, DerefMut, RangeBounds, RangeInclusive},
	usize,
};
use thiserror::Error;

#[derive(Error, Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum Error {
	#[error("Vector len outside LOW and UPP bounds")]
	OutOfBoundsVec,
}

/// Bounded Vec with minimal (L - lower bound) and maximal (U - upper bound) length
#[derive(PartialEq, Eq, Hash, Clone)]
pub struct BoundedVec<T, const LOW: usize, const UPP: usize>(Vec<T>);

impl<T, const LOW: usize, const UPP: usize> BoundedVec<T, LOW, UPP> {
	#[doc(hidden)]
	pub const VALID_L_U_TEST: () = assert!(LOW <= UPP);
	#[doc(hidden)]
	pub const BOUNDS: RangeInclusive<usize> = LOW..=UPP;

	/// # Safety
	///
	/// This is highly unsafe, due to the number of invariants that aren't
	/// checked:
	///
	/// * `ptr` must have been allocated using the global allocator, such as via
	///   the [`alloc::alloc`] function.
	/// * `T` needs to have the same alignment as what `ptr` was allocated with.
	///   (`T` having a less strict alignment is not sufficient, the alignment really
	///   needs to be equal to satisfy the [`dealloc`] requirement that memory must be
	///   allocated and deallocated with the same layout.)
	/// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs
	///   to be the same size as the pointer was allocated with. (Because similar to
	///   alignment, [`dealloc`] must be called with the same layout `size`.)
	/// * `length` needs to be less than or equal to `capacity`.
	/// * The first `length` values must be properly initialized values of type `T`.
	/// * `capacity` needs to be the capacity that the pointer was allocated with.
	/// * The allocated size in bytes must be no larger than `isize::MAX`.
	///   See the safety documentation of pointer::offset.
	/// * `length` needs to be in range of upper and lower bounds
	///
	/// These requirements are always upheld by any `ptr` that has been allocated
	/// via `Vec<T>`. Other allocation sources are allowed if the invariants are
	/// upheld.
	///
	/// Violating these may cause problems like corrupting the allocator's
	/// internal data structures. For example it is normally **not** safe
	/// to build a `Vec<u8>` from a pointer to a C `char` array with length
	/// `size_t`, doing so is only safe if the array was initially allocated by
	/// a `Vec` or `String`.
	/// It's also not safe to build one from a `Vec<u16>` and its length, because
	/// the allocator cares about the alignment, and these two types have different
	/// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
	/// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid
	/// these issues, it is often preferable to do casting/transmuting using
	/// [`std::slice::from_raw_parts`] instead.
	///
	/// The ownership of `ptr` is effectively transferred to the
	/// `Vec<T>` which may then deallocate, reallocate or change the
	/// contents of memory pointed to by the pointer at will. Ensure
	/// that nothing else uses the pointer after calling this
	/// function.
	///
	/// [`String`]: std::string::String
	/// [`alloc::alloc`]: std::alloc::alloc
	/// [`dealloc`]: std::alloc::GlobalAlloc::dealloc
	///
	#[inline]
	pub unsafe fn from_raw_parts(
		ptr: *mut T,
		length: usize,
		capacity: usize,
	) -> Result<Self, Error> {
		let _ = Self::VALID_L_U_TEST;
		if !Self::BOUNDS.contains(&length) {
			return Err(Error::OutOfBoundsVec);
		}

		Ok(Self(Vec::from_raw_parts(ptr, length, capacity)))
	}

	#[inline]
	pub fn as_vec(&self) -> &Vec<T> {
		&self.0
	}

	#[inline]
	pub fn to_vec(self) -> Vec<T> {
		self.0
	}

	/// # Safety
	///
	/// vector len must always be in range of upper and lower bounds
	///
	#[inline]
	pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<T> {
		&mut self.0
	}

	#[inline]
	pub fn reserve(&mut self, additional: usize) {
		self.0.reserve(additional)
	}

	#[inline]
	pub fn capacity(&self) -> usize {
		self.0.capacity()
	}

	#[inline]
	pub fn reserve_exact(&mut self, additional: usize) {
		self.0.reserve_exact(additional)
	}

	#[inline]
	pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
		self.0.try_reserve(additional)
	}

	#[inline]
	pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
		self.0.try_reserve_exact(additional)
	}

	#[inline]
	pub fn shrink_to_fit(&mut self) {
		self.0.shrink_to_fit()
	}

	#[inline]
	pub fn shrink_to(&mut self, min_capacity: usize) {
		self.0.shrink_to(min_capacity);
	}

	#[inline]
	pub fn into_boxed_slice(self) -> Box<[T]> {
		self.0.into_boxed_slice()
	}

	#[inline]
	pub fn truncate(&mut self, length: usize) -> Result<(), Error> {
		if length < LOW {
			return Err(Error::OutOfBoundsVec);
		}

		self.0.truncate(length);
		Ok(())
	}

	#[inline]
	pub fn as_slice(&self) -> &[T] {
		self.0.as_slice()
	}

	#[inline]
	pub fn as_ptr(&self) -> *const T {
		self.0.as_ptr()
	}

	#[inline]
	pub fn as_mut_slice(&mut self) -> &[T] {
		self.0.as_mut_slice()
	}

	#[inline]
	pub fn as_mut_ptr(&mut self) -> *mut T {
		self.0.as_mut_ptr()
	}

	/// # Safety
	///
	/// - `new_len` must be less than or equal to [`capacity()`].
	/// - `new_len` must be in range of upper and lower bounds
	/// - The elements at `old_len..new_len` must be initialized.
	///
	/// [`capacity()`]: Vec::capacity
	///
	#[inline]
	pub unsafe fn set_len(&mut self, new_len: usize) -> Result<(), Error> {
		self.0.set_len(new_len);
		Ok(())
	}

	#[inline]
	pub fn swap_remove(&mut self, index: usize) -> Result<T, Error> {
		if self.len() <= LOW {
			return Err(Error::OutOfBoundsVec);
		}

		Ok(self.0.swap_remove(index))
	}

	#[inline]
	pub fn insert(&mut self, index: usize, element: T) -> Result<(), Error> {
		if self.len() >= UPP {
			return Err(Error::OutOfBoundsVec);
		}

		self.0.insert(index, element);
		Ok(())
	}

	#[inline]
	pub fn remove(&mut self, index: usize) -> Result<T, Error> {
		if self.len() <= LOW {
			return Err(Error::OutOfBoundsVec);
		}

		Ok(self.0.remove(index))
	}

	#[inline]
	pub fn retain<F>(mut self, f: F) -> Result<Self, Error>
	where
		F: FnMut(&T) -> bool,
	{
		self.0.retain(f);
		if self.len() < LOW {
			return Err(Error::OutOfBoundsVec);
		}

		Ok(self)
	}

	#[inline]
	pub fn retain_mut<F>(mut self, f: F) -> Result<Self, Error>
	where
		F: FnMut(&mut T) -> bool,
	{
		self.0.retain_mut(f);
		if self.len() < LOW {
			return Err(Error::OutOfBoundsVec);
		}

		Ok(self)
	}

	#[inline]
	pub fn dedup_by_key<F, K>(mut self, key: F) -> Result<Self, Error>
	where
		F: FnMut(&mut T) -> K,
		K: PartialEq,
	{
		self.0.dedup_by_key(key);
		if self.len() < LOW {
			return Err(Error::OutOfBoundsVec);
		}

		Ok(self)
	}

	#[inline]
	pub fn dedup_by<F>(mut self, same_bucket: F) -> Result<Self, Error>
	where
		F: FnMut(&mut T, &mut T) -> bool,
	{
		self.0.dedup_by(same_bucket);
		if self.len() < LOW {
			return Err(Error::OutOfBoundsVec);
		}

		Ok(self)
	}

	#[inline]
	pub fn push(&mut self, value: T) -> Result<(), Error> {
		if self.len() >= UPP {
			return Err(Error::OutOfBoundsVec);
		}

		self.0.push(value);
		Ok(())
	}

	#[inline]
	pub fn pop(&mut self) -> Result<T, Error> {
		if self.len() <= LOW {
			return Err(Error::OutOfBoundsVec);
		}

		Ok(self.0.pop().expect("Checked before"))
	}

	#[inline]
	pub fn append(&mut self, vec: &mut Vec<T>) -> Result<(), Error> {
		if self.len() + vec.len() > UPP {
			return Err(Error::OutOfBoundsVec);
		}

		self.0.append(vec);
		Ok(())
	}

	#[inline]
	pub fn len(&self) -> usize {
		if LOW == UPP {
			LOW
		} else {
			self.0.len()
		}
	}

	#[inline]
	pub fn is_empty(&self) -> bool {
		if UPP == 0 {
			true
		} else {
			self.0.is_empty()
		}
	}

	#[inline]
	pub fn split_off(&mut self, at: usize) -> Result<Vec<T>, Error> {
		if at < LOW {
			return Err(Error::OutOfBoundsVec);
		}

		Ok(self.0.split_off(at))
	}

	#[inline]
	pub fn resize_with<F>(&mut self, new_len: usize, f: F) -> Result<(), Error>
	where
		F: FnMut() -> T,
	{
		if !Self::BOUNDS.contains(&new_len) {
			return Err(Error::OutOfBoundsVec);
		}

		self.0.resize_with(new_len, f);
		Ok(())
	}
}

impl<T: Clone, const LOW: usize, const UPP: usize> BoundedVec<T, LOW, UPP> {
	#[doc(hidden)]
	#[inline]
	pub fn from_elem(elem: T, n: usize) -> Result<Self, Error> {
		if !Self::BOUNDS.contains(&n) {
			return Err(Error::OutOfBoundsVec);
		}

		Ok(Self(vec![elem; n]))
	}

	#[inline]
	pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), Error> {
		if !Self::BOUNDS.contains(&new_len) {
			return Err(Error::OutOfBoundsVec);
		}

		self.0.resize(new_len, value);
		Ok(())
	}

	#[inline]
	pub fn extend_from_slice(&mut self, other: &[T]) -> Result<(), Error> {
		if self.len() + other.len() > UPP {
			return Err(Error::OutOfBoundsVec);
		}

		self.0.extend_from_slice(other);
		Ok(())
	}

	pub fn extend_from_within<R>(&mut self, src: R) -> Result<(), Error>
	where
		R: RangeBounds<usize>,
	{
		let start = match src.start_bound() {
			Bound::Unbounded => 0,
			Bound::Excluded(v) => v + 1,
			Bound::Included(v) => *v,
		};

		let end = match src.end_bound() {
			Bound::Unbounded => self.len(),
			Bound::Excluded(v) => *v,
			Bound::Included(v) => v + 1,
		};

		if start > end {
			panic!("slice index starts at {start} but ends at {end}")
		}

		let new_len = end - start + self.len();
		if new_len > UPP {
			return Err(Error::OutOfBoundsVec);
		}

		self.0.extend_from_within(src);
		if !Self::BOUNDS.contains(&self.len()) {
			panic!(
				"The length of array({}) is outside LOW and UPP bounds",
				self.len()
			)
		}

		Ok(())
	}
}

impl<T: Clone, const UPP: usize> BoundedVec<T, 0, UPP> {
	#[inline]
	pub const fn new() -> Self {
		let _ = Self::VALID_L_U_TEST;
		Self(Vec::new())
	}

	#[inline]
	pub fn with_capacity(capacity: usize) -> Self {
		let _ = Self::VALID_L_U_TEST;
		Self(Vec::with_capacity(capacity))
	}

	#[inline]
	pub fn clear(&mut self) {
		self.0.clear()
	}
}

impl<T, const LOW: usize, const UPP: usize> TryFrom<Vec<T>> for BoundedVec<T, LOW, UPP> {
	type Error = Error;
	fn try_from(value: Vec<T>) -> Result<Self, Self::Error> {
		let _ = Self::VALID_L_U_TEST;
		if !Self::BOUNDS.contains(&value.len()) {
			return Err(Error::OutOfBoundsVec);
		}

		Ok(Self(value))
	}
}

impl<T, const LOW: usize, const UPP: usize> TryFrom<Box<[T]>> for BoundedVec<T, LOW, UPP> {
	type Error = Error;
	fn try_from(value: Box<[T]>) -> Result<Self, Self::Error> {
		let _ = Self::VALID_L_U_TEST;
		if !Self::BOUNDS.contains(&value.len()) {
			return Err(Error::OutOfBoundsVec);
		}

		Ok(Self(value.into()))
	}
}

impl<T, const LOW: usize, const UPP: usize> From<BoundedVec<T, LOW, UPP>> for Vec<T> {
	fn from(value: BoundedVec<T, LOW, UPP>) -> Self {
		let _ = BoundedVec::<T, LOW, UPP>::VALID_L_U_TEST;
		value.0
	}
}

impl<T, const LOW: usize, const UPP: usize, const N: usize> TryFrom<[T; N]>
	for BoundedVec<T, LOW, UPP>
{
	type Error = Error;
	fn try_from(value: [T; N]) -> Result<Self, Self::Error> {
		let _ = Self::VALID_L_U_TEST;
		if !Self::BOUNDS.contains(&N) {
			return Err(Error::OutOfBoundsVec);
		}

		Ok(Self(value.into()))
	}
}

impl<T, const LOW: usize, const UPP: usize> AsRef<Vec<T>> for BoundedVec<T, LOW, UPP> {
	fn as_ref(&self) -> &Vec<T> {
		&self.0
	}
}

impl<T, const LOW: usize, const UPP: usize> Deref for BoundedVec<T, LOW, UPP> {
	type Target = [T];
	fn deref(&self) -> &Self::Target {
		&self.0
	}
}

impl<T, const LOW: usize, const UPP: usize> DerefMut for BoundedVec<T, LOW, UPP> {
	fn deref_mut(&mut self) -> &mut Self::Target {
		&mut self.0
	}
}

impl<T: Debug, const LOW: usize, const UPP: usize> Debug for BoundedVec<T, LOW, UPP> {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		fmt::Debug::fmt(&*self.0, f)
	}
}

#[cfg(test)]
mod tests {
	use crate::bvec;

	use super::*;

	const fn err<T>() -> Result<T, Error> {
		Err(Error::OutOfBoundsVec)
	}

	#[test]
	fn format() {
		let bvec: BoundedVec<_, 0, 10> = bvec![1, 2, 3].unwrap();
		assert_eq!("[1, 2, 3]", format!("{:?}", bvec));
	}

	#[test]
	fn format_hash() {
		let bvec: BoundedVec<_, 0, 10> = bvec![1, 2, 3].unwrap();
		assert_eq!("[\n    1,\n    2,\n    3,\n]", format!("{:#?}", bvec));
	}

	#[test]
	fn try_from_array() {
		let bounded_vec = BoundedVec::<_, 2, 3>::try_from([1, 2, 3]).unwrap();
		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());

		let bounded_vec = BoundedVec::<_, 1, 2>::try_from([1, 2, 3]);
		assert_eq!(err(), bounded_vec);
	}

	#[test]
	fn try_from_box_array() {
		let bounded_vec =
			BoundedVec::<_, 2, 3>::try_from(vec![1, 2, 3].into_boxed_slice()).unwrap();
		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());

		let bounded_vec = BoundedVec::<_, 1, 2>::try_from(vec![1, 2, 3].into_boxed_slice());
		assert_eq!(err(), bounded_vec);
	}

	#[test]
	fn try_from_vec() {
		let bounded_vec = BoundedVec::<_, 2, 3>::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());

		let bounded_vec = BoundedVec::<_, 1, 2>::try_from(vec![1, 2, 3]);
		assert_eq!(err(), bounded_vec);
	}

	#[test]
	fn new() {
		assert_eq!(Vec::<()>::new(), BoundedVec::<(), 0, 0>::new().to_vec());
	}

	#[test]
	fn with_capacity() {
		assert_eq!(
			BoundedVec::<(), 0, 0>::new(),
			BoundedVec::<(), 0, 0>::with_capacity(0)
		);
	}

	#[test]
	fn truncate() {
		let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		bounded_vec.truncate(2).unwrap();
		assert_eq!(vec![1, 2], bounded_vec.to_vec());

		let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(err(), bounded_vec.truncate(1));
		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec())
	}

	#[test]
	fn swap_remove() {
		let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(Ok(1), bounded_vec.swap_remove(0));
		assert_eq!(vec![3, 2], bounded_vec.to_vec());

		let mut bounded_vec: BoundedVec<i32, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(err(), bounded_vec.swap_remove(0));
		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
	}

	#[test]
	fn insert() {
		let mut bounded_vec: BoundedVec<i32, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		bounded_vec.insert(2, 20).unwrap();
		assert_eq!(vec![1, 2, 20, 3], bounded_vec.to_vec());

		let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(err(), bounded_vec.insert(3, 4));
		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
	}

	#[test]
	fn remove() {
		let mut bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(Ok(2), bounded_vec.remove(1));
		assert_eq!(vec![1, 3], bounded_vec.to_vec());

		let mut bounded_vec: BoundedVec<i32, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(err(), bounded_vec.remove(1));
		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
	}

	#[test]
	fn retain() {
		let bounded_vec: BoundedVec<i32, 1, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		let bounded_vec = bounded_vec.retain(|x| *x == 3).unwrap();
		assert_eq!(vec![3], bounded_vec.to_vec());

		let bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(err(), bounded_vec.retain(|x| *x == 2));
	}

	#[test]
	fn retain_mut() {
		let bounded_vec: BoundedVec<i32, 1, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		let bounded_vec = bounded_vec
			.retain_mut(|x| {
				*x *= 2;
				*x == 6
			})
			.unwrap();

		assert_eq!(vec![6], bounded_vec.to_vec());

		let bounded_vec: BoundedVec<i32, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(
			err(),
			bounded_vec.retain_mut(|x| {
				*x *= 2;
				*x == 6
			})
		)
	}

	#[test]
	fn dedup_by_key() {
		let bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 1, 2]).unwrap();
		let bounded_vec = bounded_vec.dedup_by_key(|x| *x).unwrap();
		assert_eq!(vec![1, 2], bounded_vec.to_vec());

		let bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 1, 2]).unwrap();
		assert_eq!(err(), bounded_vec.dedup_by_key(|x| *x));
	}

	#[test]
	fn dedup_by() {
		let bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 1, 2]).unwrap();
		let bounded_vec = bounded_vec.dedup_by(|x, y| x == y).unwrap();
		assert_eq!(vec![1, 2], bounded_vec.to_vec());

		let bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 1, 2]).unwrap();
		assert_eq!(err(), bounded_vec.dedup_by(|x, y| x == y));
	}

	#[test]
	fn push() {
		let mut bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		bounded_vec.push(4).unwrap();
		assert_eq!(vec![1, 2, 3, 4], bounded_vec.to_vec());

		let mut bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(err(), bounded_vec.push(4));
		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
	}

	#[test]
	fn pop() {
		let mut bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(3, bounded_vec.pop().unwrap());
		assert_eq!(vec![1, 2], bounded_vec.to_vec());

		let mut bounded_vec: BoundedVec<_, 3, 5> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(err(), bounded_vec.pop());
		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
	}

	#[test]
	fn append() {
		let mut vec = vec![4, 5];
		let mut bounded_vec: BoundedVec<_, 3, 5> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		bounded_vec.append(&mut vec).unwrap();
		assert_eq!(Vec::<i32>::new(), vec);
		assert_eq!(vec![1, 2, 3, 4, 5], bounded_vec.to_vec());

		let mut vec = vec![4, 5];
		let mut bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(err(), bounded_vec.append(&mut vec));
		assert_eq!(vec![4, 5], vec);
		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec())
	}

	#[test]
	fn clear() {
		let mut bounded_vec: BoundedVec<_, 0, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		bounded_vec.clear();
		assert_eq!(BoundedVec::new(), bounded_vec);
	}

	#[test]
	fn split_off() {
		let mut bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(vec![3], bounded_vec.split_off(2).unwrap());
		assert_eq!(vec![1, 2], bounded_vec.to_vec());

		let mut bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(err(), bounded_vec.split_off(2));
		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec())
	}

	#[test]
	fn resize_with() {
		let mut bounded_vec: BoundedVec<_, 3, 5> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		bounded_vec.resize_with(5, || 0).unwrap();
		assert_eq!(vec![1, 2, 3, 0, 0], bounded_vec.to_vec());

		let mut bounded_vec: BoundedVec<_, 1, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		bounded_vec.resize_with(1, || 0).unwrap();
		assert_eq!(vec![1], bounded_vec.to_vec());

		let mut bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(err(), bounded_vec.resize_with(5, || 0));
		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());

		let mut bounded_vec: BoundedVec<_, 2, 3> = BoundedVec::try_from(vec![1, 2, 3]).unwrap();
		assert_eq!(err(), bounded_vec.resize_with(1, || 0));
		assert_eq!(vec![1, 2, 3], bounded_vec.to_vec());
	}

	#[test]
	fn from_elem() {
		let bounded_vec: BoundedVec<_, 3, 4> = BoundedVec::from_elem(3, 4).unwrap();
		assert_eq!(vec![3, 3, 3, 3], bounded_vec.to_vec());

		let bounded_vec = BoundedVec::<_, 2, 3>::from_elem(3, 4);
		assert_eq!(err(), bounded_vec)
	}

	#[test]
	pub fn resize() {
		let mut bounded_vec = BoundedVec::<_, 1, 3>::try_from(vec![1, 2, 3]).unwrap();
		bounded_vec.resize(1, 2).unwrap();
		assert_eq!(&vec![1], bounded_vec.as_vec());
		bounded_vec.resize(3, 2).unwrap();
		assert_eq!(&vec![1, 2, 2], bounded_vec.as_vec());
		assert_eq!(err(), bounded_vec.resize(4, 2));
		assert_eq!(vec![1, 2, 2], bounded_vec.to_vec());
	}

	#[test]
	pub fn extend_from_slice() {
		let mut bounded_vec = BoundedVec::<_, 3, 5>::try_from(vec![1, 2, 3]).unwrap();
		bounded_vec.extend_from_slice(&[4, 5]).unwrap();
		assert_eq!(&vec![1, 2, 3, 4, 5], bounded_vec.as_vec());
		assert_eq!(err(), bounded_vec.extend_from_slice(&[6]));
		assert_eq!(&vec![1, 2, 3, 4, 5], bounded_vec.as_vec());
	}

	#[test]
	pub fn extend_from_within() {
		let mut bounded_vec = BoundedVec::<_, 3, 5>::try_from(vec![1, 2, 3]).unwrap();
		bounded_vec.extend_from_within(1..).unwrap();
		assert_eq!(&vec![1, 2, 3, 2, 3], bounded_vec.as_vec());
		bounded_vec.extend_from_within(4..4).unwrap();
		assert_eq!(&vec![1, 2, 3, 2, 3], bounded_vec.as_vec());
		assert_eq!(err(), bounded_vec.extend_from_within(4..=4));
		assert_eq!(&vec![1, 2, 3, 2, 3], bounded_vec.as_vec())
	}
}