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