vec1/shared.rs
1use core::ops::{Bound, RangeBounds};
2
3/// Returns the boolean pair `(covers_all_of_slice, is_out_of_bounds)`.
4///
5/// E.g. given a unbound start of the range, if the end of the range is behind the len of
6/// the slice it will cover all of the slice but it also will be out of bounds.
7///
8/// E.g. given a bound start at 1 of the range, if the end of the range is behind the len
9/// of the slice it will *not* cover all but still be out of bounds.
10///
11//FIXME(v2.0): For simplicity we might move the panic into this check (but currently can't as for Vec1::splice we don't panic)
12pub(crate) fn range_covers_slice(
13 range: &impl RangeBounds<usize>,
14 slice_len: usize,
15) -> (bool, bool) {
16 // As this is only used for vec1 we don't need the if vec_len == 0.
17 // if vec_len == 0 { return true; }
18 let (covers_start, oob_start) = range_covers_slice_start(range.start_bound(), slice_len);
19 let (covers_end, oob_end) = range_covers_slice_end(range.end_bound(), slice_len);
20 (covers_start && covers_end, oob_start || oob_end)
21}
22
23fn range_covers_slice_start(start_bound: Bound<&usize>, slice_len: usize) -> (bool, bool) {
24 match start_bound {
25 Bound::Included(idx) => (*idx == 0, *idx > slice_len),
26 Bound::Excluded(idx) => (false, *idx >= slice_len),
27 Bound::Unbounded => (true, false),
28 }
29}
30
31fn range_covers_slice_end(end_bound: Bound<&usize>, len: usize) -> (bool, bool) {
32 match end_bound {
33 Bound::Included(idx) => {
34 if len == 0 {
35 (true, true)
36 } else {
37 (*idx >= len - 1, *idx >= len)
38 }
39 }
40 Bound::Excluded(idx) => (*idx >= len, *idx > len),
41 Bound::Unbounded => (true, false),
42 }
43}
44
45macro_rules! impl_wrapper {
46 (
47 base_bounds_macro = $($tb:ident : $trait:ident)?,
48 impl <$A:ident> $ty_name:ident<$A_:ident> {
49 $(fn $fn_name:ident(&$($m:ident)* $(, $param:ident: $tp:ty)*) -> $rt:ty ;)*
50 }
51 ) => (
52 impl<$A> $ty_name<$A>
53 where
54 $($tb : $trait,)?
55 {$(
56 /// See [`Vec`] for a rough idea how this method works.
57 #[inline]
58 pub fn $fn_name(self: impl_wrapper!{__PRIV_SELF &$($m)*} $(, $param: $tp)*) -> $rt {
59 (self.0).$fn_name($($param),*)
60 }
61 )*}
62 );
63 (__PRIV_SELF &mut self) => (&mut Self);
64 (__PRIV_SELF &self) => (&Self);
65}
66
67macro_rules! shared_impl {
68 (
69 base_bounds_macro = $($tb:ident : $trait:ident)?,
70 item_ty_macro = $item_ty:ty,
71 $(#[$attr:meta])*
72 $v:vis struct $name:ident<$t:ident>($wrapped:ident<$_t:ident>);
73 ) => (
74 $(#[$attr])*
75 $v struct $name<$t>($wrapped<$t>)
76 where
77 $($tb : $trait,)?;
78
79 const _: () = {
80 use core::{
81 borrow::{Borrow, BorrowMut},
82 cmp::{Eq, Ord, Ordering, PartialEq},
83 convert::TryFrom,
84 fmt::{self, Debug},
85 hash::{Hash, Hasher},
86 ops::{Deref, DerefMut, Index, IndexMut, RangeBounds},
87 slice::SliceIndex,
88 num::NonZeroUsize,
89 };
90 use alloc::{vec::Vec, boxed::Box};
91
92 impl<$t> $name<$t>
93 where
94 $($tb : $trait,)?
95 {
96 /// Creates a new instance containing a single element.
97 pub fn new(first: $item_ty) -> Self {
98 #![allow(clippy::vec_init_then_push)]
99 let mut inner = $wrapped::new();
100 inner.push(first);
101 $name(inner)
102 }
103
104 /// Creates a new instance with a given capacity and a given "first" element.
105 pub fn with_capacity(first: $item_ty, capacity: usize) -> Self {
106 let mut vec = $wrapped::with_capacity(capacity);
107 vec.push(first);
108 $name(vec)
109 }
110
111 /// Creates an instance from a normal `Vec<T>` pushing one additional element.
112 pub fn from_vec_push(mut vec: Vec<$item_ty>, last: $item_ty) -> Self {
113 vec.push(last);
114 $name($wrapped::from(vec))
115 }
116
117 /// Creates an instance from a normal `Vec<T>` inserting one additional element.
118 ///
119 /// # Panics
120 ///
121 /// Panics if `index > len`.
122 pub fn from_vec_insert(mut vec: Vec<$item_ty>, index: usize, item: $item_ty) -> Self {
123 vec.insert(index, item);
124 $name($wrapped::from(vec))
125 }
126
127 /// Tries to create an instance from a normal `Vec<T>`.
128 ///
129 /// # Errors
130 ///
131 /// This will fail if the input `Vec<T>` is empty.
132 /// The returned error is a `Size0Error` instance, as
133 /// such this means the _input vector will be dropped if
134 /// it's empty_. But this is normally fine as it only
135 /// happens if the `Vec<T>` is empty.
136 ///
137 pub fn try_from_vec(vec: Vec<$item_ty>) -> Result<Self, Size0Error> {
138 if vec.is_empty() {
139 Err(Size0Error)
140 } else {
141 Ok($name($wrapped::from(vec)))
142 }
143 }
144
145 /// Returns a reference to the last element.
146 ///
147 /// As `$name` always contains at least one element there is always a last element.
148 pub fn last(&self) -> &$item_ty {
149 //UNWRAP_SAFE: len is at least 1
150 self.0.last().unwrap()
151 }
152
153 /// Returns a mutable reference to the last element.
154 ///
155 /// As `$name` always contains at least one element there is always a last element.
156 pub fn last_mut(&mut self) -> &mut $item_ty {
157 //UNWRAP_SAFE: len is at least 1
158 self.0.last_mut().unwrap()
159 }
160
161 /// Returns a reference to the first element.
162 ///
163 /// As `$name` always contains at least one element there is always a first element.
164 pub fn first(&self) -> &$item_ty {
165 //UNWRAP_SAFE: len is at least 1
166 self.0.first().unwrap()
167 }
168
169 /// Returns a mutable reference to the first element.
170 ///
171 /// As `$name` always contains at least one element there is always a first element.
172 pub fn first_mut(&mut self) -> &mut $item_ty {
173 //UNWRAP_SAFE: len is at least 1
174 self.0.first_mut().unwrap()
175 }
176
177
178 /// Truncates this vector to given length.
179 ///
180 /// # Errors
181 ///
182 /// If len is 0 an error is returned as the
183 /// length >= 1 constraint must be uphold.
184 ///
185 pub fn truncate(&mut self, len: usize) -> Result<(), Size0Error> {
186 if len > 0 {
187 self.0.truncate(len);
188 Ok(())
189 } else {
190 Err(Size0Error)
191 }
192 }
193
194 /// Truncates this vector to given length.
195 pub fn truncate_nonzero(&mut self, len: NonZeroUsize) {
196 self.0.truncate(len.get())
197 }
198
199 /// Returns the len as a [`NonZeroUsize`]
200 pub fn len_nonzero(&self) -> NonZeroUsize {
201 NonZeroUsize::new(self.len()).unwrap()
202 }
203
204 /// Truncates the `SmalVec1` to given length.
205 ///
206 /// # Errors
207 ///
208 /// If len is 0 an error is returned as the
209 /// length >= 1 constraint must be uphold.
210 ///
211 #[deprecated(
212 since = "1.8.0",
213 note = "try_ prefix created ambiguity use `truncate`"
214 )]
215 #[inline(always)]
216 pub fn try_truncate(&mut self, len: usize) -> Result<(), Size0Error> {
217 self.truncate(len)
218 }
219
220 /// Calls `swap_remove` on the inner smallvec if length >= 2.
221 ///
222 /// # Errors
223 ///
224 /// If len is 1 an error is returned as the
225 /// length >= 1 constraint must be uphold.
226 pub fn swap_remove(&mut self, index: usize) -> Result<$item_ty, Size0Error> {
227 if self.len() > 1 {
228 Ok(self.0.swap_remove(index))
229 } else {
230 Err(Size0Error)
231 }
232 }
233
234 /// Calls `swap_remove` on the inner smallvec if length >= 2.
235 ///
236 /// # Errors
237 ///
238 /// If len is 1 an error is returned as the
239 /// length >= 1 constraint must be uphold.
240 #[deprecated(
241 since = "1.8.0",
242 note = "try_ prefix created ambiguity use `swap_remove`"
243 )]
244 #[inline(always)]
245 pub fn try_swap_remove(&mut self, index: usize) -> Result<$item_ty, Size0Error> {
246 self.swap_remove(index)
247 }
248
249 /// Calls `remove` on the inner smallvec if length >= 2.
250 ///
251 /// # Errors
252 ///
253 /// If len is 1 an error is returned as the
254 /// length >= 1 constraint must be uphold.
255 pub fn remove(&mut self, index: usize) -> Result<$item_ty, Size0Error> {
256 if self.len() > 1 {
257 Ok(self.0.remove(index))
258 } else {
259 Err(Size0Error)
260 }
261 }
262
263 /// Calls `remove` on the inner smallvec if length >= 2.
264 ///
265 /// # Errors
266 ///
267 /// If len is 1 an error is returned as the
268 /// length >= 1 constraint must be uphold.
269 ///
270 /// # Panics
271 ///
272 /// If `index` is greater or equal then `len`.
273 #[deprecated(
274 since = "1.8.0",
275 note = "try_ prefix created ambiguity use `remove`, also try_remove PANICS on out of bounds"
276 )]
277 #[inline(always)]
278 pub fn try_remove(&mut self, index: usize) -> Result<$item_ty, Size0Error> {
279 self.remove(index)
280 }
281
282 /// If calls `drain` on the underlying vector if it will not empty the vector.
283 ///
284 /// # Error
285 ///
286 /// If calling `drain` would empty the vector an `Err(Size0Error)` is returned
287 /// **instead** of draining the vector.
288 ///
289 /// # Panic
290 ///
291 /// Like [`Vec::drain()`] panics if:
292 ///
293 /// - The starting point is greater than the end point.
294 /// - The end point is greater than the length of the vector.
295 ///
296 pub fn drain<R>(&mut self, range: R) -> Result<Drain<'_, $t>, Size0Error>
297 where
298 R: RangeBounds<usize>
299 {
300 let (covers_all, out_of_bounds) = crate::shared::range_covers_slice(&range, self.len());
301 // To make sure we get the same panic we do call drain if it will cause a panic.
302 if covers_all && !out_of_bounds {
303 Err(Size0Error)
304 } else {
305 Ok(self.0.drain(range))
306 }
307 }
308
309 /// Removes all elements except the ones which the predicate says need to be retained.
310 ///
311 /// The moment the last element would be removed this will instead fail, not removing
312 /// the element. **All but the last element will have been removed anyway.**
313 ///
314 /// # Panic Behavior
315 ///
316 /// The panic behavior is for now unspecified and might change without a
317 /// major version release.
318 ///
319 /// The current implementation does only delete non-retained elements at
320 /// the end of the `retain` function call. This might change in the future
321 /// matching `std`s behavior.
322 ///
323 /// # Error
324 ///
325 /// If the last element would be removed instead of removing it a `Size0Error` is
326 /// returned.
327 ///
328 /// # Example
329 ///
330 /// Is for `Vec1` but similar code works with `SmallVec1`, too.
331 ///
332 /// ```
333 /// # use vec1::vec1;
334 ///
335 /// let mut vec = vec1![1, 7, 8, 9, 10];
336 /// vec.retain(|v| *v % 2 == 1).unwrap();
337 /// assert_eq!(vec, vec1![1, 7, 9]);
338 /// let Size0Error = vec.retain(|_| false).unwrap_err();
339 /// assert_eq!(vec.len(), 1);
340 /// assert_eq!(vec.last(), &9);
341 /// ```
342 pub fn retain<F>(&mut self, mut f: F) -> Result<(), Size0Error>
343 where
344 F: FnMut(&$item_ty) -> bool
345 {
346 self.retain_mut(|e| f(e))
347 }
348
349 /// Removes all elements except the ones which the predicate says need to be retained.
350 ///
351 /// The moment the last element would be removed this will instead fail, not removing
352 /// the element. **All other non retained elements will still be removed.** This means
353 /// you have to be more careful compared to `Vec::retain_mut` about how you modify
354 /// non retained elements in the closure.
355 ///
356 /// # Panic Behavior
357 ///
358 /// The panic behavior is for now unspecified and might change without a
359 /// major version release.
360 ///
361 /// The current implementation does only delete non-retained elements at
362 /// the end of the `retain` function call. This might change in the future
363 /// matching `std`s behavior.
364 ///
365 /// # Error
366 ///
367 /// If the last element would be removed instead of removing it a `Size0Error` is
368 /// returned.
369 ///
370 /// # Example
371 ///
372 /// Is for `Vec1` but similar code works with `SmallVec1`, too.
373 ///
374 /// ```
375 /// # use vec1::vec1;
376 ///
377 /// let mut vec = vec1![1, 7, 8, 9, 10];
378 /// vec.retain_mut(|v| {
379 /// *v += 2;
380 /// *v % 2 == 1
381 /// }).unwrap();
382 /// assert_eq!(vec, vec1![3, 9, 11]);
383 /// let Size0Error = vec.retain_mut(|_| false).unwrap_err();
384 /// assert_eq!(vec.len(), 1);
385 /// assert_eq!(vec.last(), &11);
386 /// ```
387 pub fn retain_mut<F>(&mut self, mut f: F) -> Result<(), Size0Error>
388 where
389 F: FnMut(&mut $item_ty) -> bool
390 {
391 // Code is based on the code in the standard library, but not the newest version
392 // as the newest version uses unsafe optimizations.
393 // Given a local instal of rust v1.50.0 source documentation in rustup:
394 // <path-to-rustup-rust-v1.50.0-toolchain-with-source-doc>/share/doc/rust/html/src/alloc/vec.rs.html#1314-1334
395 let len = self.len();
396 let mut del = 0;
397 {
398 let v = &mut **self;
399
400 for i in 0..len {
401 if !f(&mut v[i]) {
402 del += 1;
403 } else if del > 0 {
404 v.swap(i - del, i);
405 }
406 }
407 }
408 if del == 0 {
409 Ok(())
410 } else {
411 if del < len {
412 self.0.truncate(len - del);
413 Ok(())
414 } else {
415 // if we would delete all then:
416 // del == len AND no swap was done
417 // so retain only last and return error
418 self.swap(0, len - 1);
419 self.0.truncate(1);
420 Err(Size0Error)
421 }
422 }
423 }
424
425 /// Calls `dedup_by_key` on the inner smallvec.
426 ///
427 /// While this can remove elements it will
428 /// never produce a empty vector from an non
429 /// empty vector.
430 pub fn dedup_by_key<F, K>(&mut self, key: F)
431 where
432 F: FnMut(&mut $item_ty) -> K,
433 K: PartialEq<K>,
434 {
435 self.0.dedup_by_key(key)
436 }
437
438 /// Calls `dedup_by_key` on the inner smallvec.
439 ///
440 /// While this can remove elements it will
441 /// never produce a empty vector from an non
442 /// empty vector.
443 pub fn dedup_by<F>(&mut self, same_bucket: F)
444 where
445 F: FnMut(&mut $item_ty, &mut $item_ty) -> bool,
446 {
447 self.0.dedup_by(same_bucket)
448 }
449
450 /// Remove the last element from this vector, if there is more than one element in it.
451 ///
452 /// # Errors
453 ///
454 /// If len is 1 an error is returned as the
455 /// length >= 1 constraint must be uphold.
456 pub fn pop(&mut self) -> Result<$item_ty, Size0Error> {
457 if self.len() > 1 {
458 //UNWRAP_SAFE: pop on len > 1 can not be none
459 Ok(self.0.pop().unwrap())
460 } else {
461 Err(Size0Error)
462 }
463 }
464
465 /// Remove the last element from this vector, if there is more than one element in it.
466 ///
467 /// # Errors
468 ///
469 /// If len is 1 an error is returned as the
470 /// length >= 1 constraint must be uphold.
471 #[deprecated(
472 since = "1.8.0",
473 note = "try_ prefix created ambiguity use `pop`"
474 )]
475 #[inline(always)]
476 pub fn try_pop(&mut self) -> Result<$item_ty, Size0Error> {
477 self.pop()
478 }
479
480 /// See [`Vec::resize_with()`] but fails if it would resize to length 0.
481 pub fn resize_with<F>(&mut self, new_len: usize, f: F) -> Result<(), Size0Error>
482 where
483 F: FnMut() -> $item_ty
484 {
485 if new_len > 0 {
486 self.0.resize_with(new_len, f);
487 Ok(())
488 } else {
489 Err(Size0Error)
490 }
491 }
492
493 /// See [`Vec::resize_with()`]
494 pub fn resize_with_nonzero<F>(&mut self, new_len: NonZeroUsize, f: F)
495 where
496 F: FnMut() -> $item_ty
497 {
498 self.0.resize_with(new_len.get(), f);
499 }
500
501 /// See [`Vec::resize_with()`] but fails if it would resize to length 0.
502 #[deprecated(
503 since = "1.8.0",
504 note = "try_ prefix created ambiguity use `resize_with`"
505 )]
506 #[inline(always)]
507 pub fn try_resize_with<F>(&mut self, new_len: usize, f: F) -> Result<(), Size0Error>
508 where
509 F: FnMut() -> $item_ty
510 {
511 self.resize_with(new_len, f)
512 }
513
514 /// Splits off the first element of this vector and returns it together with the rest of the
515 /// vector.
516 ///
517 pub fn split_off_first(self) -> ($item_ty, $wrapped<$t>) {
518 let mut smallvec = self.0;
519 let first = smallvec.remove(0);
520 (first, smallvec)
521 }
522
523 /// Splits off the last element of this vector and returns it together with the rest of the
524 /// vector.
525 pub fn split_off_last(self) -> ($wrapped<$t>, $item_ty) {
526 let mut smallvec = self.0;
527 let last = smallvec.remove(smallvec.len() - 1);
528 (smallvec, last)
529 }
530
531 /// Turns this vector into a boxed slice.
532 ///
533 /// For `Vec1` this is as cheap as for `Vec` but for
534 /// `SmallVec1` this will cause an allocation if the
535 /// on-stack buffer was not yet spilled.
536 pub fn into_boxed_slice(self) -> Box<[$item_ty]> {
537 self.into_vec().into_boxed_slice()
538 }
539
540 /// Leaks the allocation to return a mutable slice reference.
541 ///
542 /// This is equivalent to turning this vector into a boxed
543 /// slice and then leaking that slice.
544 ///
545 /// In case of `SmallVec1` calling leak does entail an allocation
546 /// if the stack-buffer had not yet spilled.
547 pub fn leak<'a>(self) -> &'a mut [$item_ty]
548 where
549 $item_ty: 'a
550 {
551 self.into_vec().leak()
552 }
553
554 /// Like [`Iterator::reduce()`] but does not return an option.
555 ///
556 /// This is roughly equivalent with `.into_iter().reduce(f).unwrap()`.
557 ///
558 /// # Example
559 ///
560 /// ```
561 /// # use vec1::vec1;
562 /// assert_eq!(vec1![1,2,4,3].reduce(std::cmp::max), 4)
563 /// ```
564 ///
565 /// *Be aware that `reduce` consumes the vector, to get a reference
566 /// use either `reduce_ref` or `reduce_mut`.*
567 ///
568 pub fn reduce(self, f: impl FnMut($item_ty, $item_ty) -> $item_ty) -> $item_ty {
569 //UNWRAP_SAFE: len is at least 1
570 self.into_iter().reduce(f).unwrap()
571 }
572
573 /// Like [`Iterator::reduce()`] but does not return an option.
574 ///
575 /// This is roughly equivalent with `.iter().reduce(f).unwrap()`.
576 ///
577 /// *Hint: Because of the reduction function returning a reference
578 /// this method is (in general) only suitable for selecting exactly
579 /// one element from the vector.*
580 ///
581 /// # Example
582 ///
583 /// ```
584 /// # use vec1::vec1;
585 /// assert_eq!(vec1![1,2,4,3].reduce_ref(std::cmp::max), &4)
586 /// ```
587 ///
588 pub fn reduce_ref<'a>(&'a self, f: impl FnMut(&'a $item_ty, &'a $item_ty) -> &'a $item_ty) -> &'a $item_ty {
589 //UNWRAP_SAFE: len is at least 1
590 self.iter().reduce(f).unwrap()
591 }
592
593 /// Like [`Iterator::reduce()`] but does not return an option.
594 ///
595 /// This is roughly equivalent with `.iter_mut().reduce(f).unwrap()`.
596 ///
597 /// *Hint: Because of the reduction function returning a reference
598 /// this method is (in general) only suitable for selecting exactly
599 /// one element from the vector.*
600 ///
601 /// # Example
602 ///
603 /// ```
604 /// # use vec1::vec1;
605 /// assert_eq!(vec1![1,2,4,3].reduce_mut(std::cmp::max), &mut 4)
606 /// ```
607 ///
608 pub fn reduce_mut<'a>(&'a mut self, f: impl FnMut(&'a mut $item_ty, &'a mut $item_ty) -> &'a mut $item_ty) -> &'a mut $item_ty {
609 //UNWRAP_SAFE: len is at least 1
610 self.iter_mut().reduce(f).unwrap()
611 }
612
613 }
614
615 // methods in Vec not in &[] which can be directly exposed
616 impl_wrapper! {
617 base_bounds_macro = $($tb : $trait)?,
618 impl<$t> $name<$t> {
619 fn append(&mut self, other: &mut $wrapped<$t>) -> ();
620 fn reserve(&mut self, additional: usize) -> ();
621 fn reserve_exact(&mut self, additional: usize) -> ();
622 fn shrink_to_fit(&mut self) -> ();
623 fn as_mut_slice(&mut self) -> &mut [$item_ty];
624 fn push(&mut self, value: $item_ty) -> ();
625 fn insert(&mut self, idx: usize, val: $item_ty) -> ();
626 fn len(&self) -> usize;
627 fn capacity(&self) -> usize;
628 fn as_slice(&self) -> &[$item_ty];
629 }
630 }
631
632 impl<$t> $name<$t>
633 where
634 $item_ty: PartialEq<$item_ty>,
635 $($tb : $trait,)?
636 {
637 pub fn dedup(&mut self) {
638 self.0.dedup()
639 }
640 }
641
642 impl<$t> $name<$t>
643 where
644 $item_ty: Copy,
645 $($tb : $trait,)?
646 {
647 pub fn extend_from_slice(&mut self, slice: &[$item_ty]) {
648 self.0.extend_from_slice(slice)
649 }
650 }
651
652 impl<$t> $name<$t>
653 where
654 $item_ty: Clone,
655 $($tb : $trait,)?
656 {
657 /// See [`Vec::resize()`] but fails if it would resize to length 0.
658 pub fn resize(&mut self, len: usize, value: $item_ty) -> Result<(), Size0Error> {
659 if len == 0 {
660 Err(Size0Error)
661 } else {
662 self.0.resize(len, value);
663 Ok(())
664 }
665 }
666
667 /// See [`Vec::resize()`].
668 pub fn resize_nonzero(&mut self, len: NonZeroUsize, value: $item_ty) {
669 self.0.resize(len.get(), value);
670 }
671
672 /// See [`Vec::resize()`] but fails if it would resize to length 0.
673 #[deprecated(
674 since = "1.8.0",
675 note = "try_ prefix created ambiguity use `resize_with`"
676 )]
677 #[inline(always)]
678 pub fn try_resize(&mut self, len: usize, value: $item_ty) -> Result<(), Size0Error> {
679 self.resize(len, value)
680 }
681 }
682
683 impl<$t> From<$name<$t>> for $wrapped<$t>
684 where
685 $($tb : $trait,)?
686 {
687 fn from(vec: $name<$t>) -> $wrapped<$t> {
688 vec.0
689 }
690 }
691
692
693 impl<$t> TryFrom<$wrapped<$t>> for $name<$t>
694 where
695 $($tb : $trait,)?
696 {
697 type Error = Size0Error;
698 fn try_from(vec: $wrapped<$t>) -> Result<Self, Size0Error> {
699 if vec.is_empty() {
700 Err(Size0Error)
701 } else {
702 Ok(Self(vec))
703 }
704 }
705 }
706
707
708 impl<$t> TryFrom<&'_ [$item_ty]> for $name<$t>
709 where
710 $item_ty: Clone,
711 $($tb : $trait,)?
712 {
713 type Error = Size0Error;
714 fn try_from(slice: &'_ [$item_ty]) -> Result<Self, Size0Error> {
715 if slice.is_empty() {
716 Err(Size0Error)
717 } else {
718 Ok($name($wrapped::from(slice)))
719 }
720 }
721 }
722
723 impl<$t> TryFrom<Box<[$item_ty]>> for $name<$t>
724 where
725 $($tb : $trait,)?
726 {
727 type Error = Size0Error;
728 fn try_from(slice: Box<[$item_ty]>) -> Result<Self, Size0Error> {
729 if slice.is_empty() {
730 Err(Size0Error)
731 } else {
732 let vec = Vec::from(slice);
733 Self::try_from_vec(vec)
734 }
735 }
736 }
737
738 impl<$t> Debug for $name<$t>
739 where
740 $item_ty: Debug,
741 $($tb : $trait,)?
742 {
743 #[inline]
744 fn fmt(&self, fter: &mut fmt::Formatter) -> fmt::Result {
745 Debug::fmt(&self.0, fter)
746 }
747 }
748
749 impl<$t> Clone for $name<$t>
750 where
751 $item_ty: Clone,
752 $($tb : $trait,)?
753 {
754 #[inline]
755 fn clone(&self) -> Self {
756 $name(self.0.clone())
757 }
758 }
759
760 impl<$t, B> PartialEq<B> for $name<$t>
761 where
762 B: ?Sized,
763 $wrapped<$t>: PartialEq<B>,
764 $($tb : $trait,)?
765 {
766 #[inline]
767 fn eq(&self, other: &B) -> bool {
768 self.0.eq(other)
769 }
770 }
771
772 impl<$t> Eq for $name<$t>
773 where
774 $item_ty: Eq,
775 $($tb : $trait,)?
776 {}
777
778 impl<$t> Hash for $name<$t>
779 where
780 $item_ty: Hash,
781 $($tb : $trait,)?
782 {
783 #[inline]
784 fn hash<H: Hasher>(&self, state: &mut H) {
785 self.0.hash(state)
786 }
787 }
788
789 impl<$t> PartialOrd for $name<$t>
790 where
791 $item_ty: PartialOrd,
792 $($tb : $trait,)?
793 {
794 #[inline]
795 fn partial_cmp(&self, other: &$name<$t>) -> Option<Ordering> {
796 self.0.partial_cmp(&other.0)
797 }
798 }
799
800 impl<$t> Ord for $name<$t>
801 where
802 $item_ty: Ord,
803 $($tb : $trait,)?
804 {
805 #[inline]
806 fn cmp(&self, other: &$name<$t>) -> Ordering {
807 self.0.cmp(&other.0)
808 }
809 }
810
811 impl<$t> Deref for $name<$t>
812 where
813 $($tb : $trait,)?
814 {
815 type Target = [$item_ty];
816
817 fn deref(&self) -> &Self::Target {
818 &*self.0
819 }
820 }
821
822 impl<$t> DerefMut for $name<$t>
823 where
824 $($tb : $trait,)?
825 {
826 fn deref_mut(&mut self) -> &mut Self::Target {
827 &mut *self.0
828 }
829 }
830
831 impl<'a, $t> IntoIterator for &'a $name<$t>
832 where
833 $($tb : $trait,)?
834 {
835 type Item = &'a $item_ty;
836 type IntoIter = core::slice::Iter<'a, $item_ty>;
837
838 fn into_iter(self) -> Self::IntoIter {
839 (&self.0).into_iter()
840 }
841 }
842
843 impl<'a, $t> IntoIterator for &'a mut $name<$t>
844 where
845 $($tb : $trait,)?
846 {
847 type Item = &'a mut $item_ty;
848 type IntoIter = core::slice::IterMut<'a, $item_ty>;
849
850 fn into_iter(self) -> Self::IntoIter {
851 (&mut self.0).into_iter()
852 }
853 }
854
855 impl<$t> Default for $name<$t>
856 where
857 $item_ty: Default,
858 $($tb : $trait,)?
859 {
860 fn default() -> Self {
861 $name::new(Default::default())
862 }
863 }
864
865 impl<$t> AsRef<[$item_ty]> for $name<$t>
866 where
867 $($tb : $trait,)?
868 {
869 fn as_ref(&self) -> &[$item_ty] {
870 self.0.as_ref()
871 }
872 }
873
874 impl<$t> AsMut<[$item_ty]> for $name<$t>
875 where
876 $($tb : $trait,)?
877 {
878 fn as_mut(&mut self) -> &mut [$item_ty] {
879 self.0.as_mut()
880 }
881 }
882
883 impl<$t> AsRef<$wrapped<$t>> for $name<$t>
884 where
885 $($tb : $trait,)?
886 {
887 fn as_ref(&self) -> &$wrapped<$t>{
888 &self.0
889 }
890 }
891
892 impl<$t> AsRef<$name<$t>> for $name<$t>
893 where
894 $($tb : $trait,)?
895 {
896 fn as_ref(&self) -> &$name<$t> {
897 self
898 }
899 }
900
901 impl<$t> AsMut<$name<$t>> for $name<$t>
902 where
903 $($tb : $trait,)?
904 {
905 fn as_mut(&mut self) -> &mut $name<$t> {
906 self
907 }
908 }
909
910
911
912 impl<$t> Borrow<[$item_ty]> for $name<$t>
913 where
914 $($tb : $trait,)?
915 {
916 fn borrow(&self) -> &[$item_ty] {
917 self.0.as_ref()
918 }
919 }
920
921
922 impl<$t> Borrow<$wrapped<$t>> for $name<$t>
923 where
924 $($tb : $trait,)?
925 {
926 fn borrow(&self) -> &$wrapped<$t>{
927 &self.0
928 }
929 }
930
931 impl<$t, SI> Index<SI> for $name<$t>
932 where
933 SI: SliceIndex<[$item_ty]>,
934 $($tb : $trait,)?
935 {
936 type Output = SI::Output;
937
938 fn index(&self, index: SI) -> &SI::Output {
939 self.0.index(index)
940 }
941 }
942
943 impl<$t, SI> IndexMut<SI> for $name<$t>
944 where
945 SI: SliceIndex<[$item_ty]>,
946 $($tb : $trait,)?
947 {
948 fn index_mut(&mut self, index: SI) -> &mut SI::Output {
949 self.0.index_mut(index)
950 }
951 }
952
953
954 impl<$t> BorrowMut<[$item_ty]> for $name<$t>
955 where
956 $($tb : $trait,)?
957 {
958 fn borrow_mut(&mut self) -> &mut [$item_ty] {
959 self.0.as_mut()
960 }
961 }
962
963 impl<$t> Extend<$item_ty> for $name<$t>
964 where
965 $($tb : $trait,)?
966 {
967 fn extend<IT: IntoIterator<Item = $item_ty>>(&mut self, iterable: IT) {
968 self.0.extend(iterable)
969 }
970 }
971
972 //Note: We can not (simply) have if feature serde and feature smallvec enable
973 // dependency smallvec/serde, but we can mirror the serde implementation.
974 #[cfg(feature = "serde")]
975 const _: () = {
976 use core::marker::PhantomData;
977 use serde::{
978 de::{SeqAccess,Deserialize, Visitor, Deserializer, Error as _},
979 ser::{Serialize, Serializer, SerializeSeq}
980 };
981
982 impl<$t> Serialize for $name<$t>
983 where
984 $item_ty: Serialize,
985 $($tb : $trait,)?
986 {
987 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
988 let mut seq_ser = serializer.serialize_seq(Some(self.len()))?;
989 for item in self {
990 seq_ser.serialize_element(&item)?;
991 }
992 seq_ser.end()
993 }
994 }
995
996 impl<'de, $t> Deserialize<'de> for $name<$t>
997 where
998 $item_ty: Deserialize<'de>,
999 $($tb : $trait,)?
1000 {
1001 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1002 deserializer.deserialize_seq(SmallVec1Visitor {
1003 _type_carry: PhantomData,
1004 })
1005 }
1006 }
1007 struct SmallVec1Visitor<$t> {
1008 _type_carry: PhantomData<$t>,
1009 }
1010
1011 impl<'de, $t> Visitor<'de> for SmallVec1Visitor<$t>
1012 where
1013 $item_ty: Deserialize<'de>,
1014 $($tb : $trait,)?
1015 {
1016 type Value = $name<$t>;
1017
1018 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1019 formatter.write_str("a sequence")
1020 }
1021
1022 fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
1023 where
1024 B: SeqAccess<'de>,
1025 {
1026 let len = seq.size_hint().unwrap_or(0);
1027 let mut vec = $wrapped::new();
1028 //FIXME use try_reserve
1029 vec.reserve(len);
1030
1031 while let Some(value) = seq.next_element()? {
1032 vec.push(value);
1033 }
1034
1035 $name::try_from(vec).map_err(B::Error::custom)
1036 }
1037 }
1038 };
1039 };
1040 );
1041}
1042
1043#[cfg(test)]
1044mod tests {
1045 use core::ops::{Bound, RangeBounds};
1046
1047 #[derive(Debug)]
1048 struct AnyBound {
1049 start: Bound<usize>,
1050 end: Bound<usize>,
1051 }
1052
1053 fn bound_as_ref(bound: &Bound<usize>) -> Bound<&usize> {
1054 match bound {
1055 Bound::Included(v) => Bound::Included(v),
1056 Bound::Excluded(v) => Bound::Excluded(v),
1057 Bound::Unbounded => Bound::Unbounded,
1058 }
1059 }
1060
1061 impl RangeBounds<usize> for AnyBound {
1062 fn start_bound(&self) -> Bound<&usize> {
1063 bound_as_ref(&self.start)
1064 }
1065
1066 fn end_bound(&self) -> Bound<&usize> {
1067 bound_as_ref(&self.end)
1068 }
1069 }
1070
1071 mod range_covers_slice_start {
1072 use super::super::range_covers_slice_start;
1073 use core::ops::Bound;
1074
1075 #[test]
1076 fn included_bound() {
1077 let cases = &[
1078 (1, 10, (false, false)),
1079 (0, 0, (true, false)),
1080 (0, 1, (true, false)),
1081 (1, 0, (false, true)),
1082 (11, 10, (false, true)),
1083 (1, 1, (false, false)),
1084 ];
1085 for (start, len, expected_res) in cases {
1086 let res = range_covers_slice_start(Bound::Included(start), *len);
1087 assert_eq!(
1088 res, *expected_res,
1089 "Failed start=${}, len=${}, res]=${:?}",
1090 start, len, res
1091 );
1092 }
1093 }
1094
1095 #[test]
1096 fn excluded_bound() {
1097 let cases = &[
1098 (1, 10, (false, false)),
1099 (0, 0, (false, true)),
1100 (0, 1, (false, false)),
1101 (1, 0, (false, true)),
1102 (11, 10, (false, true)),
1103 (1, 1, (false, true)),
1104 ];
1105 for (start, len, expected_res) in cases {
1106 let res = range_covers_slice_start(Bound::Excluded(start), *len);
1107 assert_eq!(
1108 res, *expected_res,
1109 "Failed start=${}, len=${}, res]=${:?}",
1110 start, len, res
1111 );
1112 }
1113 }
1114
1115 #[test]
1116 fn unbound_bound() {
1117 for len in &[0, 1, 100] {
1118 assert_eq!(
1119 range_covers_slice_start(Bound::Unbounded, *len),
1120 (true, false)
1121 );
1122 }
1123 }
1124 }
1125
1126 mod range_covers_slice_end {
1127 use super::super::range_covers_slice_end;
1128 use core::ops::Bound;
1129
1130 #[test]
1131 fn included_bound() {
1132 let cases = &[
1133 (5, 6, (true, false)),
1134 (4, 6, (false, false)),
1135 (0, 10, (false, false)),
1136 (6, 6, (true, true)),
1137 (9, 8, (true, true)),
1138 (0, 0, (true, true)),
1139 ];
1140 for (end, len, expected_res) in cases {
1141 let res = range_covers_slice_end(Bound::Included(end), *len);
1142 assert_eq!(
1143 res, *expected_res,
1144 "Failed start=${}, len=${}, res]=${:?}",
1145 end, len, res
1146 );
1147 }
1148 }
1149
1150 #[test]
1151 fn excluded_bound() {
1152 let cases = &[
1153 (5, 6, (false, false)),
1154 (4, 6, (false, false)),
1155 (0, 10, (false, false)),
1156 (6, 6, (true, false)),
1157 (0, 0, (true, false)),
1158 (11, 10, (true, true)),
1159 (1, 0, (true, true)),
1160 ];
1161 for (end, len, expected_res) in cases {
1162 let res = range_covers_slice_end(Bound::Excluded(end), *len);
1163 assert_eq!(
1164 res, *expected_res,
1165 "Unexpected result: start=${}, len=${}, res=${:?} => ${:?}",
1166 end, len, res, expected_res
1167 );
1168 }
1169 }
1170
1171 #[test]
1172 fn unbound_bound() {
1173 for len in &[0, 1, 100] {
1174 assert_eq!(
1175 range_covers_slice_end(Bound::Unbounded, *len),
1176 (true, false)
1177 );
1178 }
1179 }
1180 }
1181
1182 mod range_covers_slice {
1183 use super::super::range_covers_slice;
1184 use super::AnyBound;
1185
1186 #[test]
1187 fn test_multiple_cases_from_table() {
1188 use core::ops::Bound::*;
1189 /*
1190 start end cover-all oob
1191 ----------------------------------------------
1192 cover cover true false
1193 cover non-cover false false
1194 cover cover-oob true true
1195 non-cover cover false false
1196 non-cover non-cover false false
1197 non-cover cover-oob false true
1198 non-cover-oob cover false true
1199 non-cover-obb non-cover false true
1200 non-cover-oob cover-oob false true
1201 */
1202 let len = 3;
1203 let cases: &[_] = &[
1204 (Included(0), Excluded(len), (true, false)),
1205 (Unbounded, Excluded(len - 1), (false, false)),
1206 (Included(0), Included(len), (true, true)),
1207 (Included(1), Included(len - 1), (false, false)),
1208 (Excluded(0), Included(len - 2), (false, false)),
1209 (Included(1), Excluded(len + 4), (false, true)),
1210 (Excluded(len), Excluded(len), (false, true)),
1211 (Included(len + 1), Excluded(len - 1), (false, true)),
1212 (Excluded(len), Included(len), (false, true)),
1213 ];
1214
1215 for &(start, end, expected_res) in cases.into_iter() {
1216 let bound = AnyBound { start, end };
1217 let res = range_covers_slice(&bound, len);
1218 assert_eq!(
1219 res, expected_res,
1220 "Unexpected result: bound=${:?}, len=${} => ${:?}",
1221 bound, len, expected_res
1222 )
1223 }
1224 }
1225 }
1226}