sized_vec/lib.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5//! # Type Level Sized Vectors
6//!
7//! This crate provides a `Vec<N, A>` type, which wraps the standard `Vec<A>`
8//! and tracks its size `N` at the type level.
9//!
10//! Because the size is embedded in the type, we can do things like verifying at
11//! compile time that index lookups are within bounds.
12//!
13//! ```compile_fail
14//! # #[macro_use] extern crate sized_vec;
15//! # extern crate typenum;
16//! # use typenum::U8;
17//! # fn main() {
18//! let vec = svec![1, 2, 3];
19//! // This index lookup won't compile, because index `U8` is outside
20//! // the vector's length of `U3`:
21//! assert_eq!(5, vec[U8::new()]);
22//! # }
23//! ```
24//!
25//! ```
26//! # #[macro_use] extern crate sized_vec;
27//! # extern crate typenum;
28//! # use typenum::U2;
29//! # fn main() {
30//! let vec = svec![1, 2, 3];
31//! // On the other hand, this lookup can be verified to be correct
32//! // by the type system:
33//! assert_eq!(3, vec[U2::new()]);
34//! # }
35//! ```
36//!
37//! ## Limitations
38//!
39//! If this looks too good to be true, it's because it comes with a number of
40//! limitations: you won't be able to perform operations on the vector which
41//! could leave it with a length that can't be known at compile time. This
42//! includes `Extend::extend()` and filtering operations like `Vec::retain()`.
43//!
44//! `FromIterator::from_iter` is, notably, also not available, but you can use
45//! `Vec::try_from` as a replacement. Note that `try_from` needs to be able to
46//! infer the size of the resulting vector at compile time; there's no way to
47//! construct a vector of arbitrary length.
48//!
49//! ```
50//! # #[macro_use] extern crate sized_vec;
51//! # extern crate typenum;
52//! # use sized_vec::Vec;
53//! # use typenum::U2;
54//! # fn main() {
55//! let vec = svec![1, 2, 3, 4, 5];
56//! let new_vec = Vec::try_from_iter(vec.into_iter().map(|i| i + 10));
57//! assert_eq!(Some(svec![11, 12, 13, 14, 15]), new_vec);
58//! # }
59//! ```
60
61use std::convert::TryFrom;
62use typenum::consts::*;
63use typenum::{
64 Add1, Bit, Diff, Eq, IsEqual, IsLess, IsLessOrEqual, Le, LeEq, Sub1, Sum, True, Unsigned,
65};
66
67use std::borrow::{Borrow, BorrowMut};
68use std::convert::{AsMut, AsRef};
69use std::fmt::{Debug, Error, Formatter};
70use std::marker::PhantomData;
71use std::ops::{Add, Index, IndexMut, Sub};
72use std::slice::{Iter, IterMut};
73use std::vec::IntoIter;
74
75pub trait IsTrue {}
76impl IsTrue for True {}
77
78/// A type level range.
79pub struct Range<Left, Right>
80where
81 Left: Unsigned + IsLessOrEqual<Right>,
82 Right: Unsigned,
83 LeEq<Left, Right>: IsTrue,
84{
85 left: PhantomData<Left>,
86 right: PhantomData<Right>,
87}
88
89impl<Left, Right> Range<Left, Right>
90where
91 Left: Unsigned + IsLessOrEqual<Right>,
92 Right: Unsigned,
93 LeEq<Left, Right>: IsTrue,
94{
95 /// Create an instance of this Range.
96 pub fn new() -> Self {
97 Range {
98 left: PhantomData,
99 right: PhantomData,
100 }
101 }
102
103 /// Reify the range type into a `std::ops::Range<usize>` value.
104 pub fn to_usize() -> ::std::ops::Range<usize> {
105 Left::USIZE..Right::USIZE
106 }
107}
108
109impl<Left, Right> Default for Range<Left, Right>
110where
111 Left: Unsigned + IsLessOrEqual<Right>,
112 Right: Unsigned,
113 LeEq<Left, Right>: IsTrue,
114{
115 fn default() -> Self {
116 Self::new()
117 }
118}
119
120#[macro_export]
121macro_rules! svec {
122 () => { $crate::vec::Vec::new() };
123
124 ( $($x:expr),* ) => {{
125 $crate::Vec::new()$(.push($x))*
126 }};
127
128 ( $($x:expr ,)* ) => {{
129 $crate::Vec::new()$(.push($x))*
130 }};
131}
132
133/// A vector of length `N` containing elements of type `A`.
134#[derive(PartialEq, Eq, Clone, Hash, PartialOrd, Ord)]
135pub struct Vec<N, A>
136where
137 N: Unsigned,
138{
139 len: PhantomData<N>,
140 vec: ::std::vec::Vec<A>,
141}
142
143impl<A> Vec<U0, A> {
144 /// Construct an empty vector.
145 #[inline]
146 #[must_use]
147 pub fn new() -> Self {
148 Vec {
149 len: PhantomData,
150 vec: vec![],
151 }
152 }
153}
154
155impl<N, A> Vec<N, A>
156where
157 N: Unsigned,
158{
159 #[inline]
160 #[must_use]
161 fn trust_me<M: Unsigned>(self) -> Vec<M, A> {
162 use std::mem::transmute;
163 unsafe { transmute(self) }
164 }
165
166 #[must_use]
167 fn from_vec(vec: ::std::vec::Vec<A>) -> Vec<N, A> {
168 Vec {
169 len: PhantomData,
170 vec,
171 }
172 }
173
174 /// Construct a vector of size `N` using a function.
175 ///
176 /// The function is called with an index to generate a value of `A` for each
177 /// index in the vector.
178 ///
179 /// # Examples
180 /// ```
181 /// # #[macro_use] extern crate sized_vec;
182 /// # extern crate typenum;
183 /// # use sized_vec::Vec;
184 /// # use typenum::U3;
185 /// # fn main() {
186 /// let vec: Vec<U3, _> = Vec::fill(|i| i + 10);
187 /// assert_eq!(svec![10, 11, 12], vec);
188 /// # }
189 /// ```
190 #[must_use]
191 pub fn fill<F>(f: F) -> Vec<N, A>
192 where
193 F: FnMut(usize) -> A,
194 {
195 Vec::from_vec((0..N::USIZE).map(f).collect())
196 }
197
198 /// Construct a vector of size `N` containing the same element repeated.
199 ///
200 /// # Examples
201 /// ```
202 /// # #[macro_use] extern crate sized_vec;
203 /// # extern crate typenum;
204 /// # use sized_vec::Vec;
205 /// # use typenum::U3;
206 /// # fn main() {
207 /// let vec: Vec<U3, _> = Vec::repeat(5);
208 /// assert_eq!(svec![5, 5, 5], vec);
209 /// # }
210 /// ```
211 #[must_use]
212 pub fn repeat(a: A) -> Vec<N, A>
213 where
214 A: Clone,
215 {
216 Vec::from_vec(::std::iter::repeat(a).take(N::USIZE).collect())
217 }
218
219 /// Construct a vector of size `N` from an iterator.
220 ///
221 /// Returns `None` if the iterator didn't contain exactly `N` elements.
222 ///
223 /// # Examples
224 /// ```
225 /// # #[macro_use] extern crate sized_vec;
226 /// # extern crate typenum;
227 /// # use sized_vec::Vec;
228 /// # use typenum::U3;
229 /// # fn main() {
230 /// let good_vec: Option<Vec<U3, _>> = Vec::try_from_iter(1..=3);
231 /// assert_eq!(Some(svec![1, 2, 3]), good_vec);
232 ///
233 /// let bad_vec: Option<Vec<U3, _>> = Vec::try_from_iter(1..=500);
234 /// assert_eq!(None, bad_vec);
235 /// # }
236 /// ```
237 #[must_use]
238 pub fn try_from_iter<I>(iter: I) -> Option<Self>
239 where
240 I: IntoIterator<Item = A>,
241 {
242 let mut vec = ::std::vec::Vec::with_capacity(N::USIZE);
243 vec.extend(iter);
244 if vec.len() == N::USIZE {
245 Some(Vec::from_vec(vec))
246 } else {
247 None
248 }
249 }
250
251 /// Construct a vector of size `N` using the default value.
252 ///
253 /// # Examples
254 /// ```
255 /// # #[macro_use] extern crate sized_vec;
256 /// # extern crate typenum;
257 /// # use sized_vec::Vec;
258 /// # use typenum::U3;
259 /// # fn main() {
260 /// let vec: Vec<U3, _> = Vec::from_default();
261 /// assert_eq!(svec![0, 0, 0], vec);
262 /// # }
263 /// ```
264 #[must_use]
265 pub fn from_default() -> Vec<N, A>
266 where
267 A: Default,
268 {
269 Vec::from_vec((0..N::USIZE).map(|_| Default::default()).collect())
270 }
271
272 /// Push an element onto the end of the vector.
273 ///
274 /// # Examples
275 /// ```
276 /// # #[macro_use] extern crate sized_vec;
277 /// # extern crate typenum;
278 /// # use sized_vec::Vec;
279 /// # use typenum::{U2, U3};
280 /// # fn main() {
281 /// let vec: Vec<U2, _> = svec![1, 2];
282 /// let new_vec: Vec<U3, _> = vec.push(3);
283 /// assert_eq!(svec![1, 2, 3], new_vec);
284 /// # }
285 /// ```
286 ///
287 /// ```compile_fail
288 /// # #[macro_use] extern crate sized_vec;
289 /// # extern crate typenum;
290 /// # use sized_vec::Vec;
291 /// # use typenum::{U2, U3};
292 /// # fn main() {
293 /// let vec: Vec<U2, _> = svec![1, 2];
294 /// // Type error, because the new length will be U3, not U2:
295 /// let new_vec: Vec<U2, _> = vec.push(3);
296 /// # }
297 /// ```
298 #[must_use]
299 pub fn push(mut self, a: A) -> Vec<Add1<N>, A>
300 where
301 N: Add<B1>,
302 Add1<N>: Unsigned,
303 {
304 self.vec.push(a);
305 self.trust_me()
306 }
307
308 /// Pop an element off the end of the vector.
309 ///
310 /// # Examples
311 /// ```
312 /// # #[macro_use] extern crate sized_vec;
313 /// # extern crate typenum;
314 /// # use sized_vec::Vec;
315 /// # fn main() {
316 /// let vec = svec![1, 2, 3];
317 /// let (new_vec, value) = vec.pop();
318 /// assert_eq!(svec![1, 2], new_vec);
319 /// assert_eq!(3, value);
320 /// # }
321 /// ```
322 ///
323 /// ```compile_fail
324 /// # #[macro_use] extern crate sized_vec;
325 /// # extern crate typenum;
326 /// # use sized_vec::Vec;
327 /// # use typenum::{U2, U3};
328 /// # fn main() {
329 /// let vec: Vec<U3, _> = svec![1, 2, 3];
330 /// // Type error, because the new length will be U2, not U3:
331 /// let (new_vec: Vec<U3, _>, value) = vec.pop();
332 /// # }
333 /// ```
334 #[must_use]
335 pub fn pop(mut self) -> (Vec<Diff<N, U1>, A>, A)
336 where
337 N: Sub<U1>,
338 Diff<N, U1>: Unsigned,
339 {
340 let o = self.vec.pop().unwrap();
341 (self.trust_me(), o)
342 }
343
344 /// Insert an element into the vector at index `Index`.
345 #[must_use]
346 pub fn insert<Index>(mut self, _: Index, a: A) -> Vec<Add1<N>, A>
347 where
348 Index: Unsigned + IsLess<N>,
349 Le<Index, N>: IsTrue,
350 N: Add<B1>,
351 Add1<N>: Unsigned,
352 {
353 self.vec.insert(Index::USIZE, a);
354 self.trust_me()
355 }
356
357 /// Remove the element at index `Index` from the vector.
358 #[must_use]
359 pub fn remove<Index>(mut self, _: Index) -> (Vec<Sub1<N>, A>, A)
360 where
361 Index: Unsigned + IsLess<N>,
362 Le<Index, N>: IsTrue,
363 N: Sub<B1>,
364 Sub1<N>: Unsigned,
365 {
366 let o = self.vec.remove(Index::USIZE);
367 (self.trust_me(), o)
368 }
369
370 /// Remove the element at index `Index` from the vector,
371 /// replacing it with the element at the end of the vector.
372 #[must_use]
373 pub fn swap_remove<Index>(mut self, _: Index) -> (Vec<Sub1<N>, A>, A)
374 where
375 Index: Unsigned + IsLess<N>,
376 Le<Index, N>: IsTrue,
377 N: Sub<B1>,
378 Sub1<N>: Unsigned,
379 {
380 let o = self.vec.swap_remove(Index::USIZE);
381 (self.trust_me(), o)
382 }
383
384 /// Append two vectors together.
385 #[must_use]
386 pub fn append<M>(mut self, mut other: Vec<M, A>) -> Vec<Sum<N, M>, A>
387 where
388 N: Add<M>,
389 M: Unsigned,
390 Sum<N, M>: Unsigned,
391 {
392 self.vec.append(&mut other.vec);
393 self.trust_me()
394 }
395
396 /// Get a reference to the element at index `Index`.
397 ///
398 /// # Examples
399 /// ```
400 /// # #[macro_use] extern crate sized_vec;
401 /// # extern crate typenum;
402 /// # use sized_vec::Vec;
403 /// # use typenum::U1;
404 /// # fn main() {
405 /// let vec = svec![1, 2, 3];
406 /// assert_eq!(&2, vec.get(U1::new()));
407 /// # }
408 /// ```
409 ///
410 /// ```compile_fail
411 /// # #[macro_use] extern crate sized_vec;
412 /// # extern crate typenum;
413 /// # use sized_vec::Vec;
414 /// # use typenum::U5;
415 /// # fn main() {
416 /// let vec = svec![1, 2, 3];
417 /// // This index is out of bounds, so this won't compile:
418 /// assert_eq!(&2, vec.get(U5::new()));
419 /// # }
420 /// ```
421 #[inline]
422 #[must_use]
423 pub fn get<Index>(&self, _: Index) -> &A
424 where
425 Index: Unsigned + IsLess<N>,
426 Le<Index, N>: IsTrue,
427 {
428 unsafe { self.vec.get_unchecked(Index::USIZE) }
429 }
430
431 /// Get a mutable reference to the element at index `Index`.
432 #[inline]
433 #[must_use]
434 pub fn get_mut<Index>(&mut self, _: Index) -> &mut A
435 where
436 Index: Unsigned + IsLess<N>,
437 Le<Index, N>: IsTrue,
438 {
439 unsafe { self.vec.get_unchecked_mut(Index::USIZE) }
440 }
441
442 /// Get the length of the vector.
443 #[inline]
444 #[must_use]
445 pub fn len(&self) -> usize {
446 N::USIZE
447 }
448
449 /// Test if the vector is empty.
450 #[inline]
451 #[must_use]
452 pub fn is_empty(&self) -> bool
453 where
454 N: IsEqual<U0>,
455 {
456 Eq::<N, U0>::BOOL
457 }
458
459 /// Get an iterator over the elements of the vector.
460 #[inline]
461 #[must_use]
462 pub fn iter(&self) -> Iter<A> {
463 self.vec.iter()
464 }
465
466 /// Get a mutable iterator over the elements of the vector.
467 #[inline]
468 #[must_use]
469 pub fn iter_mut(&mut self) -> IterMut<A> {
470 self.vec.iter_mut()
471 }
472
473 /// Get a reference to the slice of elements contained in the vector.
474 #[inline]
475 #[must_use]
476 pub fn as_slice(&self) -> &[A] {
477 self.vec.as_slice()
478 }
479
480 /// Get a mutable reference to the slice of elements contained in the
481 /// vector.
482 #[inline]
483 #[must_use]
484 pub fn as_mut_slice(&mut self) -> &mut [A] {
485 self.vec.as_mut_slice()
486 }
487
488 /// Truncate the vector to fit the size given by the target type.
489 ///
490 /// # Examples
491 /// ```
492 /// # #[macro_use] extern crate sized_vec;
493 /// # extern crate typenum;
494 /// # use sized_vec::Vec;
495 /// # use typenum::U3;
496 /// # fn main() {
497 /// let vec_6 = svec![1, 2, 3, 4, 5, 6];
498 /// let vec_3: Vec<U3, _> = vec_6.truncate();
499 /// assert_eq!(svec![1, 2, 3], vec_3);
500 /// # }
501 /// ```
502 #[must_use]
503 pub fn truncate<M>(mut self) -> Vec<M, A>
504 where
505 M: Unsigned + IsLessOrEqual<N>,
506 LeEq<M, N>: IsTrue,
507 {
508 self.vec.truncate(M::USIZE);
509 self.trust_me()
510 }
511
512 /// Slice a subset out of the vector.
513 ///
514 /// # Examples
515 /// ```
516 /// # #[macro_use] extern crate sized_vec;
517 /// # extern crate typenum;
518 /// # use sized_vec::Range;
519 /// # use typenum::{U2, U4};
520 /// # fn main() {
521 /// let vec = svec![1, 2, 3, 4, 5, 6];
522 /// let (vec, sub_vec) = vec.slice(Range::<U2, U4>::new());
523 /// assert_eq!(svec![1, 2, 5, 6], vec);
524 /// assert_eq!(svec![3, 4], sub_vec);
525 /// # }
526 /// ```
527 #[must_use]
528 pub fn slice<Left, Right>(
529 mut self,
530 _: Range<Left, Right>,
531 ) -> (
532 Vec<Diff<N, Diff<Right, Left>>, A>,
533 Vec<Diff<Right, Left>, A>,
534 )
535 where
536 Diff<N, Diff<Right, Left>>: Unsigned,
537 Diff<Right, Left>: Unsigned,
538 Left: Unsigned + IsLessOrEqual<Right>,
539 Right: Unsigned + Sub<Left> + IsLessOrEqual<N>,
540 N: Sub<Diff<Right, Left>>,
541 LeEq<Left, Right>: IsTrue,
542 LeEq<Right, N>: IsTrue,
543 {
544 let removed = Vec::from_vec(self.vec.drain(Range::<Left, Right>::to_usize()).collect());
545 (self.trust_me(), removed)
546 }
547
548 /// Remove a subset from the vector and return an iterator over the removed
549 /// elements.
550 ///
551 /// # Examples
552 /// ```
553 /// # #[macro_use] extern crate sized_vec;
554 /// # extern crate typenum;
555 /// # use sized_vec::Range;
556 /// # use typenum::{U2, U4};
557 /// # fn main() {
558 /// let vec = svec![1, 2, 3, 4, 5, 6];
559 /// let (vec, iter) = vec.drain(Range::<U2, U4>::new());
560 /// assert_eq!(svec![1, 2, 5, 6], vec);
561 /// assert_eq!(vec![3, 4], iter.collect::<::std::vec::Vec<_>>());
562 /// # }
563 /// ```
564 #[must_use]
565 pub fn drain<Left, Right>(
566 self,
567 range: Range<Left, Right>,
568 ) -> (Vec<Diff<N, Diff<Right, Left>>, A>, impl Iterator<Item = A>)
569 where
570 Diff<N, Diff<Right, Left>>: Unsigned,
571 Diff<Right, Left>: Unsigned,
572 Left: Unsigned + IsLessOrEqual<Right>,
573 Right: Unsigned + Sub<Left> + IsLessOrEqual<N>,
574 N: Sub<Diff<Right, Left>>,
575 LeEq<Left, Right>: IsTrue,
576 LeEq<Right, N>: IsTrue,
577 {
578 let (remainder, slice) = self.slice(range);
579 (remainder.trust_me(), slice.into_iter())
580 }
581
582 /// Drop the contents of the vector, leaving an empty vector.
583 #[must_use]
584 pub fn clear(mut self) -> Vec<U0, A> {
585 self.vec.clear();
586 self.trust_me()
587 }
588
589 /// Split the vector at `Index`, returning the two sides of the split.
590 ///
591 /// # Examples
592 /// ```
593 /// # #[macro_use] extern crate sized_vec;
594 /// # extern crate typenum;
595 /// # use typenum::U3;
596 /// # fn main() {
597 /// let vec = svec![1, 2, 3, 4, 5, 6];
598 /// let (left, right) = vec.split_off(U3::new());
599 /// assert_eq!(svec![1, 2, 3], left);
600 /// assert_eq!(svec![4, 5, 6], right);
601 /// # }
602 /// ```
603 #[must_use]
604 pub fn split_off<Index>(mut self, _: Index) -> (Vec<Index, A>, Vec<Diff<N, Index>, A>)
605 where
606 Index: Unsigned + IsLessOrEqual<N>,
607 N: Sub<Index>,
608 Diff<N, Index>: Unsigned,
609 LeEq<Index, N>: IsTrue,
610 {
611 let split = self.vec.split_off(Index::USIZE);
612 (self.trust_me(), Vec::from_vec(split))
613 }
614
615 /// Resize the vector, dropping elements if the new size is smaller,
616 /// and padding with copies of `value` if it is larger.
617 ///
618 /// # Examples
619 /// ```
620 /// # #[macro_use] extern crate sized_vec;
621 /// # extern crate typenum;
622 /// # use sized_vec::Vec;
623 /// # use typenum::U5;
624 /// # fn main() {
625 /// let vec = svec![1, 2, 3];
626 /// let vec: Vec<U5, _> = vec.resize(100);
627 /// assert_eq!(svec![1, 2, 3, 100, 100], vec);
628 /// # }
629 /// ```
630 #[must_use]
631 pub fn resize<M>(mut self, value: A) -> Vec<M, A>
632 where
633 M: Unsigned,
634 A: Clone,
635 {
636 self.vec.resize(M::USIZE, value);
637 self.trust_me()
638 }
639
640 /// Map the vector into a vector of elements of `B` using a function.
641 ///
642 /// # Examples
643 /// ```
644 /// # #[macro_use] extern crate sized_vec;
645 /// # extern crate typenum;
646 /// # fn main() {
647 /// let vec = svec![1, 2, 3];
648 /// let vec = vec.map(|num| format!("{}", num));
649 /// assert_eq!(svec![
650 /// "1".to_string(), "2".to_string(), "3".to_string()
651 /// ], vec);
652 /// # }
653 /// ```
654 #[must_use]
655 pub fn map<F, B>(self, f: F) -> Vec<N, B>
656 where
657 F: FnMut(A) -> B,
658 {
659 Vec::from_vec(self.into_iter().map(f).collect())
660 }
661
662 /// Apply a list of functions from `A` to `B` to a vector of `A` in order,
663 /// returning a vector of `B`.
664 ///
665 /// # Examples
666 /// ```
667 /// # #[macro_use] extern crate sized_vec;
668 /// # extern crate typenum;
669 /// # fn main() {
670 /// let vec = svec![1, 2, 3];
671 /// let fn_vec = vec.clone().map(|i| move |a| a + i);
672 /// let vec = vec.apply(fn_vec);
673 /// assert_eq!(svec![2, 4, 6], vec);
674 /// # }
675 /// ```
676 #[must_use]
677 pub fn apply<F, B>(self, fs: Vec<N, F>) -> Vec<N, B>
678 where
679 F: FnMut(A) -> B,
680 {
681 Vec::from_vec(
682 self.into_iter()
683 .zip(fs.into_iter())
684 .map(|(a, mut f)| f(a))
685 .collect(),
686 )
687 }
688
689 /// Merge two vectors together into a new vector using a function.
690 ///
691 /// # Examples
692 /// ```
693 /// # #[macro_use] extern crate sized_vec;
694 /// # extern crate typenum;
695 /// # fn main() {
696 /// let left = svec!["foo", "bar"];
697 /// let right = svec!["lol", "omg"];
698 /// let vec = left.zip(right, |a, b| format!("{} {}", a, b));
699 /// assert_eq!(svec![
700 /// "foo lol".to_string(), "bar omg".to_string()
701 /// ], vec);
702 /// # }
703 /// ```
704 #[must_use]
705 pub fn zip<B, C, F>(self, other: Vec<N, B>, mut f: F) -> Vec<N, C>
706 where
707 F: FnMut(A, B) -> C,
708 {
709 Vec::from_vec(
710 self.into_iter()
711 .zip(other.into_iter())
712 .map(|(a, b)| f(a, b))
713 .collect(),
714 )
715 }
716
717 /// Split a vector into two vectors of the same size using a function.
718 ///
719 /// # Examples
720 /// ```
721 /// # #[macro_use] extern crate sized_vec;
722 /// # extern crate typenum;
723 /// # fn main() {
724 /// let vec = svec![1, 2, 3];
725 /// let vec = vec.unzip(|a| (a, a * 2));
726 /// assert_eq!((svec![1, 2, 3], svec![2, 4, 6]), vec);
727 /// # }
728 /// ```
729 #[must_use]
730 pub fn unzip<B, C, F>(self, f: F) -> (Vec<N, B>, Vec<N, C>)
731 where
732 F: FnMut(A) -> (B, C),
733 {
734 let (left, right) = self.into_iter().map(f).unzip();
735 (Vec::from_vec(left), Vec::from_vec(right))
736 }
737}
738
739impl<A> Default for Vec<U0, A> {
740 #[inline]
741 fn default() -> Self {
742 Self::new()
743 }
744}
745
746impl<N, A> Debug for Vec<N, A>
747where
748 N: Unsigned,
749 A: Debug,
750{
751 #[inline]
752 fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
753 self.vec.fmt(f)
754 }
755}
756
757impl<N, M, A> Add<Vec<M, A>> for Vec<N, A>
758where
759 N: Unsigned + Add<M>,
760 M: Unsigned,
761 Sum<N, M>: Unsigned,
762{
763 type Output = Vec<Sum<N, M>, A>;
764
765 fn add(self, other: Vec<M, A>) -> Self::Output {
766 self.append(other)
767 }
768}
769
770impl<N, A> Into<::std::vec::Vec<A>> for Vec<N, A>
771where
772 N: Unsigned,
773{
774 fn into(self) -> ::std::vec::Vec<A> {
775 self.vec
776 }
777}
778
779impl<'a, N, A> Into<&'a [A]> for &'a Vec<N, A>
780where
781 N: Unsigned,
782{
783 fn into(self) -> &'a [A] {
784 &self.vec
785 }
786}
787
788impl<'a, N, A> Into<&'a mut [A]> for &'a mut Vec<N, A>
789where
790 N: Unsigned,
791{
792 fn into(self) -> &'a mut [A] {
793 &mut self.vec
794 }
795}
796
797impl<N, A> IntoIterator for Vec<N, A>
798where
799 N: Unsigned,
800{
801 type Item = A;
802 type IntoIter = IntoIter<A>;
803
804 fn into_iter(self) -> Self::IntoIter {
805 self.vec.into_iter()
806 }
807}
808
809impl<'a, N, A> IntoIterator for &'a Vec<N, A>
810where
811 N: Unsigned,
812{
813 type Item = &'a A;
814 type IntoIter = Iter<'a, A>;
815
816 fn into_iter(self) -> Self::IntoIter {
817 self.vec.iter()
818 }
819}
820
821impl<'a, N, A> IntoIterator for &'a mut Vec<N, A>
822where
823 N: Unsigned,
824{
825 type Item = &'a mut A;
826 type IntoIter = IterMut<'a, A>;
827
828 fn into_iter(self) -> Self::IntoIter {
829 self.vec.iter_mut()
830 }
831}
832
833impl<N, A> Borrow<[A]> for Vec<N, A>
834where
835 N: Unsigned,
836{
837 fn borrow(&self) -> &[A] {
838 self.as_slice()
839 }
840}
841
842impl<N, A> Borrow<::std::vec::Vec<A>> for Vec<N, A>
843where
844 N: Unsigned,
845{
846 fn borrow(&self) -> &::std::vec::Vec<A> {
847 &self.vec
848 }
849}
850
851impl<N, A> BorrowMut<[A]> for Vec<N, A>
852where
853 N: Unsigned,
854{
855 fn borrow_mut(&mut self) -> &mut [A] {
856 self.as_mut_slice()
857 }
858}
859
860impl<N, A, I> Index<I> for Vec<N, A>
861where
862 N: Unsigned,
863 I: Unsigned + IsLess<N>,
864 Le<I, N>: IsTrue,
865{
866 type Output = A;
867 fn index(&self, index: I) -> &Self::Output {
868 self.get(index)
869 }
870}
871
872impl<N, A, I> IndexMut<I> for Vec<N, A>
873where
874 N: Unsigned,
875 I: Unsigned + IsLess<N>,
876 Le<I, N>: IsTrue,
877{
878 fn index_mut(&mut self, index: I) -> &mut Self::Output {
879 self.get_mut(index)
880 }
881}
882
883impl<N, A> AsRef<[A]> for Vec<N, A>
884where
885 N: Unsigned,
886{
887 fn as_ref(&self) -> &[A] {
888 self.as_slice()
889 }
890}
891
892impl<N, A> AsRef<Vec<N, A>> for Vec<N, A>
893where
894 N: Unsigned,
895{
896 fn as_ref(&self) -> &Self {
897 self
898 }
899}
900
901impl<N, A> AsRef<::std::vec::Vec<A>> for Vec<N, A>
902where
903 N: Unsigned,
904{
905 fn as_ref(&self) -> &::std::vec::Vec<A> {
906 &self.vec
907 }
908}
909
910impl<N, A> AsMut<[A]> for Vec<N, A>
911where
912 N: Unsigned,
913{
914 fn as_mut(&mut self) -> &mut [A] {
915 self.as_mut_slice()
916 }
917}
918
919impl<N, A> AsMut<Vec<N, A>> for Vec<N, A>
920where
921 N: Unsigned,
922{
923 fn as_mut(&mut self) -> &mut Self {
924 self
925 }
926}
927
928impl<N, A> TryFrom<std::vec::Vec<A>> for Vec<N, A>
929where
930 N: Unsigned,
931{
932 type Error = ();
933
934 /// Construct a vector of size `N` from a `std::vec::Vec`.
935 ///
936 /// Returns `Err(())` if the source vector didn't contain exactly `N` elements.
937 ///
938 /// # Examples
939 /// ```
940 /// # #[macro_use] extern crate sized_vec;
941 /// # extern crate typenum;
942 /// # use std::convert::TryFrom;
943 /// # use sized_vec::Vec;
944 /// # use typenum::U3;
945 /// # fn main() {
946 /// let good_vec: Result<Vec<U3, _>, _> = Vec::try_from(vec![1, 2, 3]);
947 /// assert_eq!(Ok(svec![1, 2, 3]), good_vec);
948 ///
949 /// let bad_vec: Result<Vec<U3, _>, _> = Vec::try_from(vec![1, 2]);
950 /// assert_eq!(Err(()), bad_vec);
951 /// # }
952 /// ```
953 #[must_use]
954 fn try_from(vec: ::std::vec::Vec<A>) -> Result<Self, Self::Error> {
955 if vec.len() == N::USIZE {
956 Ok(Vec::from_vec(vec))
957 } else {
958 Err(())
959 }
960 }
961}
962
963impl<N, A> TryFrom<Box<[A]>> for Vec<N, A>
964where
965 N: Unsigned,
966{
967 type Error = ();
968
969 /// Construct a vector of size `N` from a boxed array.
970 ///
971 /// Returns `Err(())` if the source vector didn't contain exactly `N` elements.
972 ///
973 /// # Examples
974 /// ```
975 /// # #[macro_use] extern crate sized_vec;
976 /// # extern crate typenum;
977 /// # use std::convert::TryFrom;
978 /// # use sized_vec::Vec;
979 /// # use typenum::U3;
980 /// # fn main() {
981 /// let boxed: Box<[_]> = Box::new([1, 2, 3]);
982 /// let good_vec: Result<Vec<U3, _>, _> = Vec::try_from(boxed);
983 /// assert_eq!(Ok(svec![1, 2, 3]), good_vec);
984 ///
985 /// let boxed: Box<[_]> = Box::new([1, 2]);
986 /// let bad_vec: Result<Vec<U3, _>, _> = Vec::try_from(boxed);
987 /// assert_eq!(Err(()), bad_vec);
988 /// # }
989 /// ```
990 #[must_use]
991 fn try_from(array: Box<[A]>) -> Result<Self, Self::Error> {
992 if array.len() == N::USIZE {
993 Ok(Vec::from_vec(array.into_vec()))
994 } else {
995 Err(())
996 }
997 }
998}
999
1000impl<'a, N, A> TryFrom<&'a [A]> for Vec<N, A>
1001where
1002 A: Clone,
1003 N: Unsigned,
1004{
1005 type Error = ();
1006
1007 /// Construct a vector of size `N` from a slice of clonable values.
1008 ///
1009 /// Returns `Err(())` if the source slice didn't contain exactly `N` elements.
1010 ///
1011 /// # Examples
1012 /// ```
1013 /// # #[macro_use] extern crate sized_vec;
1014 /// # extern crate typenum;
1015 /// # use std::convert::TryFrom;
1016 /// # use sized_vec::Vec;
1017 /// # use typenum::U3;
1018 /// # fn main() {
1019 /// let good_vec: Result<Vec<U3, _>, _> = Vec::try_from([1, 2, 3].as_ref());
1020 /// assert_eq!(Ok(svec![1, 2, 3]), good_vec);
1021 ///
1022 /// let bad_vec: Result<Vec<U3, _>, _> = Vec::try_from([1, 2].as_ref());
1023 /// assert_eq!(Err(()), bad_vec);
1024 /// # }
1025 /// ```
1026 #[must_use]
1027 fn try_from(slice: &'a [A]) -> Result<Self, Self::Error> {
1028 Vec::try_from_iter(slice.iter().cloned()).ok_or(())
1029 }
1030}
1031
1032macro_rules! declare_from_array {
1033 ($s1:expr, $s2:ty) => {
1034 impl<A> From<[A; $s1]> for Vec<$s2, A> {
1035 #[must_use]
1036 fn from(array: [A; $s1]) -> Self {
1037 let boxed_array: Box<[A]> = Box::new(array);
1038 let vec = boxed_array.into_vec();
1039 debug_assert_eq!($s1, vec.len());
1040 Vec::from_vec(vec)
1041 }
1042 }
1043 };
1044}
1045
1046declare_from_array!(0, U0);
1047declare_from_array!(1, U1);
1048declare_from_array!(2, U2);
1049declare_from_array!(3, U3);
1050declare_from_array!(4, U4);
1051declare_from_array!(5, U5);
1052declare_from_array!(6, U6);
1053declare_from_array!(7, U7);
1054declare_from_array!(8, U8);
1055declare_from_array!(9, U9);
1056declare_from_array!(10, U10);
1057declare_from_array!(11, U11);
1058declare_from_array!(12, U12);
1059declare_from_array!(13, U13);
1060declare_from_array!(14, U14);
1061declare_from_array!(15, U15);
1062declare_from_array!(16, U16);
1063declare_from_array!(17, U17);
1064declare_from_array!(18, U18);
1065declare_from_array!(19, U19);
1066declare_from_array!(20, U20);
1067declare_from_array!(21, U21);
1068declare_from_array!(22, U22);
1069declare_from_array!(23, U23);
1070declare_from_array!(24, U24);
1071declare_from_array!(25, U25);
1072declare_from_array!(26, U26);
1073declare_from_array!(27, U27);
1074declare_from_array!(28, U28);
1075declare_from_array!(29, U29);
1076declare_from_array!(30, U30);
1077declare_from_array!(31, U31);
1078
1079#[cfg(any(test, feature = "generic-array"))]
1080impl<N, A> From<generic_array::GenericArray<A, N>> for Vec<N, A>
1081where
1082 N: Unsigned + generic_array::ArrayLength<A>,
1083{
1084 /// Construct a vector of size `N` from a `GenericArray`.
1085 ///
1086 /// # Examples
1087 /// ```
1088 /// # #[macro_use] extern crate sized_vec;
1089 /// # use std::convert::TryFrom;
1090 /// # use sized_vec::Vec;
1091 /// # use typenum::U3;
1092 /// # use generic_array::GenericArray;
1093 /// # fn main() {
1094 /// let array = GenericArray::from([1, 2, 3]);
1095 /// let good_vec: Vec<U3, _> = Vec::from(array);
1096 /// assert_eq!(svec![1, 2, 3], good_vec);
1097 /// # }
1098 /// ```
1099 ///
1100 /// ```compile_fail
1101 /// # #[macro_use] extern crate sized_vec;
1102 /// # use std::convert::TryFrom;
1103 /// # use sized_vec::Vec;
1104 /// # use typenum::U3;
1105 /// # use generic_array::GenericArray;
1106 /// # fn main() {
1107 /// let array = GenericArray::from([1, 2]);
1108 /// let bad_vec: Vec<U3, _> = Vec::from(array);
1109 /// # }
1110 /// ```
1111 #[must_use]
1112 fn from(array: generic_array::GenericArray<A, N>) -> Self {
1113 Vec::from_vec(array.into_iter().collect())
1114 }
1115}
1116
1117#[cfg(any(test, feature = "serde"))]
1118mod ser {
1119 use super::*;
1120 use serde::de::{Deserialize, Deserializer, Error};
1121 use serde::ser::{Serialize, Serializer};
1122
1123 impl<N, A> Serialize for Vec<N, A>
1124 where
1125 N: Unsigned,
1126 A: Serialize,
1127 {
1128 fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
1129 where
1130 S: Serializer,
1131 {
1132 self.vec.serialize(ser)
1133 }
1134 }
1135
1136 impl<'de, N, A> Deserialize<'de> for Vec<N, A>
1137 where
1138 N: Unsigned,
1139 A: Deserialize<'de>,
1140 {
1141 fn deserialize<D>(des: D) -> Result<Self, D::Error>
1142 where
1143 D: Deserializer<'de>,
1144 {
1145 let vec: std::vec::Vec<_> = Deserialize::deserialize(des)?;
1146 Self::try_from(vec).map_err(|()| {
1147 <D as Deserializer<'de>>::Error::custom(format!(
1148 "length of sized_vec::Vec was not {}",
1149 N::USIZE
1150 ))
1151 })
1152 }
1153 }
1154}
1155
1156#[cfg(any(test, feature = "proptest"))]
1157pub mod proptest {
1158 use super::*;
1159 use ::proptest::collection::vec as stdvec;
1160 use ::proptest::strategy::{BoxedStrategy, Strategy, ValueTree};
1161
1162 /// A strategy for generating a sized vector.
1163 ///
1164 /// # Examples
1165 ///
1166 /// ```rust,ignore
1167 /// proptest! {
1168 /// #[test]
1169 /// fn proptest_a_vector(ref vec in sized_vec::<U16, _>(".*")) {
1170 /// assert_eq!(16, vec.len());
1171 /// }
1172 /// }
1173 /// ```
1174 pub fn sized_vec<N, A>(element: A) -> BoxedStrategy<Vec<N, <A::Tree as ValueTree>::Value>>
1175 where
1176 N: Unsigned + 'static,
1177 A: Strategy + 'static,
1178 <A::Tree as ValueTree>::Value: Clone,
1179 {
1180 stdvec(element, N::USIZE).prop_map(Vec::from_vec).boxed()
1181 }
1182}
1183
1184#[cfg(test)]
1185mod tests {
1186 use super::proptest::sized_vec;
1187 use super::*;
1188 use ::proptest::proptest;
1189 use pretty_assertions::assert_eq;
1190 use serde_json::{from_str, to_string};
1191
1192 #[test]
1193 fn basics() {
1194 let v = svec![1, 2, 3];
1195 assert_eq!(U3::USIZE, v.len());
1196 assert_eq!(&2, v.get(U1::new()));
1197 assert_eq!((svec![1, 2], 3), v.pop());
1198 let v1 = svec![1, 2, 3];
1199 let v2 = svec![4, 5, 6];
1200 let v3 = v1.append(v2);
1201 assert_eq!(6, v3.len());
1202 assert_eq!(svec![1, 2, 3, 4, 5, 6], v3);
1203 let v4: Vec<U4, _> = v3.truncate();
1204 assert_eq!(4, v4.len());
1205 assert_eq!(svec![1, 2, 3, 4,], v4);
1206 assert_eq!(2, v4[U1::new()]);
1207 }
1208
1209 #[test]
1210 fn serialise() {
1211 let v = svec![1, 2, 3, 4, 5];
1212 assert_eq!(v, from_str(&to_string(&v).unwrap()).unwrap());
1213 }
1214
1215 #[test]
1216 fn static_array_conversion() {
1217 let v = Vec::from([1, 2, 3, 4, 5]);
1218 assert_eq!(svec![1, 2, 3, 4, 5], v);
1219 }
1220
1221 proptest! {
1222 #[test]
1223 fn test_the_proptest(ref vec in sized_vec::<U16, _>(".*")) {
1224 assert_eq!(16, vec.len())
1225 }
1226 }
1227
1228}