]> git.proxmox.com Git - rustc.git/blame - vendor/arrayvec/src/arrayvec.rs
New upstream version 1.55.0+dfsg1
[rustc.git] / vendor / arrayvec / src / arrayvec.rs
CommitLineData
cdc7bbd5
XL
1
2use std::cmp;
3use std::iter;
4use std::mem;
5use std::ops::{Bound, Deref, DerefMut, RangeBounds};
6use std::ptr;
7use std::slice;
8
9// extra traits
10use std::borrow::{Borrow, BorrowMut};
11use std::hash::{Hash, Hasher};
12use std::fmt;
13
14#[cfg(feature="std")]
15use std::io;
16
17use std::mem::ManuallyDrop;
18use std::mem::MaybeUninit;
19
20#[cfg(feature="serde")]
21use serde::{Serialize, Deserialize, Serializer, Deserializer};
22
23use crate::LenUint;
24use crate::errors::CapacityError;
25use crate::arrayvec_impl::ArrayVecImpl;
26use crate::utils::MakeMaybeUninit;
27
28/// A vector with a fixed capacity.
29///
30/// The `ArrayVec` is a vector backed by a fixed size array. It keeps track of
31/// the number of initialized elements. The `ArrayVec<T, CAP>` is parameterized
32/// by `T` for the element type and `CAP` for the maximum capacity.
33///
34/// `CAP` is of type `usize` but is range limited to `u32::MAX`; attempting to create larger
35/// arrayvecs with larger capacity will panic.
36///
37/// The vector is a contiguous value (storing the elements inline) that you can store directly on
38/// the stack if needed.
39///
40/// It offers a simple API but also dereferences to a slice, so that the full slice API is
41/// available. The ArrayVec can be converted into a by value iterator.
42pub struct ArrayVec<T, const CAP: usize> {
43 // the `len` first elements of the array are initialized
44 xs: [MaybeUninit<T>; CAP],
45 len: LenUint,
46}
47
48impl<T, const CAP: usize> Drop for ArrayVec<T, CAP> {
49 fn drop(&mut self) {
50 self.clear();
51
52 // MaybeUninit inhibits array's drop
53 }
54}
55
56macro_rules! panic_oob {
57 ($method_name:expr, $index:expr, $len:expr) => {
58 panic!(concat!("ArrayVec::", $method_name, ": index {} is out of bounds in vector of length {}"),
59 $index, $len)
60 }
61}
62
63impl<T, const CAP: usize> ArrayVec<T, CAP> {
64 /// Capacity
65 const CAPACITY: usize = CAP;
66
67 /// Create a new empty `ArrayVec`.
68 ///
69 /// The maximum capacity is given by the generic parameter `CAP`.
70 ///
71 /// ```
72 /// use arrayvec::ArrayVec;
73 ///
74 /// let mut array = ArrayVec::<_, 16>::new();
75 /// array.push(1);
76 /// array.push(2);
77 /// assert_eq!(&array[..], &[1, 2]);
78 /// assert_eq!(array.capacity(), 16);
79 /// ```
80 pub fn new() -> ArrayVec<T, CAP> {
81 assert_capacity_limit!(CAP);
82 unsafe {
83 ArrayVec { xs: MaybeUninit::uninit().assume_init(), len: 0 }
84 }
85 }
86
87 /// Create a new empty `ArrayVec` (const fn).
88 ///
89 /// The maximum capacity is given by the generic parameter `CAP`.
90 ///
91 /// ```
92 /// use arrayvec::ArrayVec;
93 ///
94 /// static ARRAY: ArrayVec<u8, 1024> = ArrayVec::new_const();
95 /// ```
96 pub const fn new_const() -> ArrayVec<T, CAP> {
97 assert_capacity_limit_const!(CAP);
98 ArrayVec { xs: MakeMaybeUninit::ARRAY, len: 0 }
99 }
100
101 /// Return the number of elements in the `ArrayVec`.
102 ///
103 /// ```
104 /// use arrayvec::ArrayVec;
105 ///
106 /// let mut array = ArrayVec::from([1, 2, 3]);
107 /// array.pop();
108 /// assert_eq!(array.len(), 2);
109 /// ```
110 #[inline(always)]
111 pub fn len(&self) -> usize { self.len as usize }
112
113 /// Returns whether the `ArrayVec` is empty.
114 ///
115 /// ```
116 /// use arrayvec::ArrayVec;
117 ///
118 /// let mut array = ArrayVec::from([1]);
119 /// array.pop();
120 /// assert_eq!(array.is_empty(), true);
121 /// ```
122 #[inline]
123 pub fn is_empty(&self) -> bool { self.len() == 0 }
124
125 /// Return the capacity of the `ArrayVec`.
126 ///
127 /// ```
128 /// use arrayvec::ArrayVec;
129 ///
130 /// let array = ArrayVec::from([1, 2, 3]);
131 /// assert_eq!(array.capacity(), 3);
132 /// ```
133 #[inline(always)]
134 pub fn capacity(&self) -> usize { CAP }
135
136 /// Return true if the `ArrayVec` is completely filled to its capacity, false otherwise.
137 ///
138 /// ```
139 /// use arrayvec::ArrayVec;
140 ///
141 /// let mut array = ArrayVec::<_, 1>::new();
142 /// assert!(!array.is_full());
143 /// array.push(1);
144 /// assert!(array.is_full());
145 /// ```
146 pub fn is_full(&self) -> bool { self.len() == self.capacity() }
147
148 /// Returns the capacity left in the `ArrayVec`.
149 ///
150 /// ```
151 /// use arrayvec::ArrayVec;
152 ///
153 /// let mut array = ArrayVec::from([1, 2, 3]);
154 /// array.pop();
155 /// assert_eq!(array.remaining_capacity(), 1);
156 /// ```
157 pub fn remaining_capacity(&self) -> usize {
158 self.capacity() - self.len()
159 }
160
161 /// Push `element` to the end of the vector.
162 ///
163 /// ***Panics*** if the vector is already full.
164 ///
165 /// ```
166 /// use arrayvec::ArrayVec;
167 ///
168 /// let mut array = ArrayVec::<_, 2>::new();
169 ///
170 /// array.push(1);
171 /// array.push(2);
172 ///
173 /// assert_eq!(&array[..], &[1, 2]);
174 /// ```
175 pub fn push(&mut self, element: T) {
176 ArrayVecImpl::push(self, element)
177 }
178
179 /// Push `element` to the end of the vector.
180 ///
181 /// Return `Ok` if the push succeeds, or return an error if the vector
182 /// is already full.
183 ///
184 /// ```
185 /// use arrayvec::ArrayVec;
186 ///
187 /// let mut array = ArrayVec::<_, 2>::new();
188 ///
189 /// let push1 = array.try_push(1);
190 /// let push2 = array.try_push(2);
191 ///
192 /// assert!(push1.is_ok());
193 /// assert!(push2.is_ok());
194 ///
195 /// assert_eq!(&array[..], &[1, 2]);
196 ///
197 /// let overflow = array.try_push(3);
198 ///
199 /// assert!(overflow.is_err());
200 /// ```
201 pub fn try_push(&mut self, element: T) -> Result<(), CapacityError<T>> {
202 ArrayVecImpl::try_push(self, element)
203 }
204
205 /// Push `element` to the end of the vector without checking the capacity.
206 ///
207 /// It is up to the caller to ensure the capacity of the vector is
208 /// sufficiently large.
209 ///
210 /// This method uses *debug assertions* to check that the arrayvec is not full.
211 ///
212 /// ```
213 /// use arrayvec::ArrayVec;
214 ///
215 /// let mut array = ArrayVec::<_, 2>::new();
216 ///
217 /// if array.len() + 2 <= array.capacity() {
218 /// unsafe {
219 /// array.push_unchecked(1);
220 /// array.push_unchecked(2);
221 /// }
222 /// }
223 ///
224 /// assert_eq!(&array[..], &[1, 2]);
225 /// ```
226 pub unsafe fn push_unchecked(&mut self, element: T) {
227 ArrayVecImpl::push_unchecked(self, element)
228 }
229
230 /// Shortens the vector, keeping the first `len` elements and dropping
231 /// the rest.
232 ///
233 /// If `len` is greater than the vector’s current length this has no
234 /// effect.
235 ///
236 /// ```
237 /// use arrayvec::ArrayVec;
238 ///
239 /// let mut array = ArrayVec::from([1, 2, 3, 4, 5]);
240 /// array.truncate(3);
241 /// assert_eq!(&array[..], &[1, 2, 3]);
242 /// array.truncate(4);
243 /// assert_eq!(&array[..], &[1, 2, 3]);
244 /// ```
245 pub fn truncate(&mut self, new_len: usize) {
246 ArrayVecImpl::truncate(self, new_len)
247 }
248
249 /// Remove all elements in the vector.
250 pub fn clear(&mut self) {
251 ArrayVecImpl::clear(self)
252 }
253
254
255 /// Get pointer to where element at `index` would be
256 unsafe fn get_unchecked_ptr(&mut self, index: usize) -> *mut T {
257 self.as_mut_ptr().add(index)
258 }
259
260 /// Insert `element` at position `index`.
261 ///
262 /// Shift up all elements after `index`.
263 ///
264 /// It is an error if the index is greater than the length or if the
265 /// arrayvec is full.
266 ///
267 /// ***Panics*** if the array is full or the `index` is out of bounds. See
268 /// `try_insert` for fallible version.
269 ///
270 /// ```
271 /// use arrayvec::ArrayVec;
272 ///
273 /// let mut array = ArrayVec::<_, 2>::new();
274 ///
275 /// array.insert(0, "x");
276 /// array.insert(0, "y");
277 /// assert_eq!(&array[..], &["y", "x"]);
278 ///
279 /// ```
280 pub fn insert(&mut self, index: usize, element: T) {
281 self.try_insert(index, element).unwrap()
282 }
283
284 /// Insert `element` at position `index`.
285 ///
286 /// Shift up all elements after `index`; the `index` must be less than
287 /// or equal to the length.
288 ///
289 /// Returns an error if vector is already at full capacity.
290 ///
291 /// ***Panics*** `index` is out of bounds.
292 ///
293 /// ```
294 /// use arrayvec::ArrayVec;
295 ///
296 /// let mut array = ArrayVec::<_, 2>::new();
297 ///
298 /// assert!(array.try_insert(0, "x").is_ok());
299 /// assert!(array.try_insert(0, "y").is_ok());
300 /// assert!(array.try_insert(0, "z").is_err());
301 /// assert_eq!(&array[..], &["y", "x"]);
302 ///
303 /// ```
304 pub fn try_insert(&mut self, index: usize, element: T) -> Result<(), CapacityError<T>> {
305 if index > self.len() {
306 panic_oob!("try_insert", index, self.len())
307 }
308 if self.len() == self.capacity() {
309 return Err(CapacityError::new(element));
310 }
311 let len = self.len();
312
313 // follows is just like Vec<T>
314 unsafe { // infallible
315 // The spot to put the new value
316 {
317 let p: *mut _ = self.get_unchecked_ptr(index);
318 // Shift everything over to make space. (Duplicating the
319 // `index`th element into two consecutive places.)
320 ptr::copy(p, p.offset(1), len - index);
321 // Write it in, overwriting the first copy of the `index`th
322 // element.
323 ptr::write(p, element);
324 }
325 self.set_len(len + 1);
326 }
327 Ok(())
328 }
329
330 /// Remove the last element in the vector and return it.
331 ///
332 /// Return `Some(` *element* `)` if the vector is non-empty, else `None`.
333 ///
334 /// ```
335 /// use arrayvec::ArrayVec;
336 ///
337 /// let mut array = ArrayVec::<_, 2>::new();
338 ///
339 /// array.push(1);
340 ///
341 /// assert_eq!(array.pop(), Some(1));
342 /// assert_eq!(array.pop(), None);
343 /// ```
344 pub fn pop(&mut self) -> Option<T> {
345 ArrayVecImpl::pop(self)
346 }
347
348 /// Remove the element at `index` and swap the last element into its place.
349 ///
350 /// This operation is O(1).
351 ///
352 /// Return the *element* if the index is in bounds, else panic.
353 ///
354 /// ***Panics*** if the `index` is out of bounds.
355 ///
356 /// ```
357 /// use arrayvec::ArrayVec;
358 ///
359 /// let mut array = ArrayVec::from([1, 2, 3]);
360 ///
361 /// assert_eq!(array.swap_remove(0), 1);
362 /// assert_eq!(&array[..], &[3, 2]);
363 ///
364 /// assert_eq!(array.swap_remove(1), 2);
365 /// assert_eq!(&array[..], &[3]);
366 /// ```
367 pub fn swap_remove(&mut self, index: usize) -> T {
368 self.swap_pop(index)
369 .unwrap_or_else(|| {
370 panic_oob!("swap_remove", index, self.len())
371 })
372 }
373
374 /// Remove the element at `index` and swap the last element into its place.
375 ///
376 /// This is a checked version of `.swap_remove`.
377 /// This operation is O(1).
378 ///
379 /// Return `Some(` *element* `)` if the index is in bounds, else `None`.
380 ///
381 /// ```
382 /// use arrayvec::ArrayVec;
383 ///
384 /// let mut array = ArrayVec::from([1, 2, 3]);
385 ///
386 /// assert_eq!(array.swap_pop(0), Some(1));
387 /// assert_eq!(&array[..], &[3, 2]);
388 ///
389 /// assert_eq!(array.swap_pop(10), None);
390 /// ```
391 pub fn swap_pop(&mut self, index: usize) -> Option<T> {
392 let len = self.len();
393 if index >= len {
394 return None;
395 }
396 self.swap(index, len - 1);
397 self.pop()
398 }
399
400 /// Remove the element at `index` and shift down the following elements.
401 ///
402 /// The `index` must be strictly less than the length of the vector.
403 ///
404 /// ***Panics*** if the `index` is out of bounds.
405 ///
406 /// ```
407 /// use arrayvec::ArrayVec;
408 ///
409 /// let mut array = ArrayVec::from([1, 2, 3]);
410 ///
411 /// let removed_elt = array.remove(0);
412 /// assert_eq!(removed_elt, 1);
413 /// assert_eq!(&array[..], &[2, 3]);
414 /// ```
415 pub fn remove(&mut self, index: usize) -> T {
416 self.pop_at(index)
417 .unwrap_or_else(|| {
418 panic_oob!("remove", index, self.len())
419 })
420 }
421
422 /// Remove the element at `index` and shift down the following elements.
423 ///
424 /// This is a checked version of `.remove(index)`. Returns `None` if there
425 /// is no element at `index`. Otherwise, return the element inside `Some`.
426 ///
427 /// ```
428 /// use arrayvec::ArrayVec;
429 ///
430 /// let mut array = ArrayVec::from([1, 2, 3]);
431 ///
432 /// assert!(array.pop_at(0).is_some());
433 /// assert_eq!(&array[..], &[2, 3]);
434 ///
435 /// assert!(array.pop_at(2).is_none());
436 /// assert!(array.pop_at(10).is_none());
437 /// ```
438 pub fn pop_at(&mut self, index: usize) -> Option<T> {
439 if index >= self.len() {
440 None
441 } else {
442 self.drain(index..index + 1).next()
443 }
444 }
445
446 /// Retains only the elements specified by the predicate.
447 ///
448 /// In other words, remove all elements `e` such that `f(&mut e)` returns false.
449 /// This method operates in place and preserves the order of the retained
450 /// elements.
451 ///
452 /// ```
453 /// use arrayvec::ArrayVec;
454 ///
455 /// let mut array = ArrayVec::from([1, 2, 3, 4]);
456 /// array.retain(|x| *x & 1 != 0 );
457 /// assert_eq!(&array[..], &[1, 3]);
458 /// ```
459 pub fn retain<F>(&mut self, mut f: F)
460 where F: FnMut(&mut T) -> bool
461 {
462 // Check the implementation of
463 // https://doc.rust-lang.org/std/vec/struct.Vec.html#method.retain
464 // for safety arguments (especially regarding panics in f and when
465 // dropping elements). Implementation closely mirrored here.
466
467 let original_len = self.len();
468 unsafe { self.set_len(0) };
469
470 struct BackshiftOnDrop<'a, T, const CAP: usize> {
471 v: &'a mut ArrayVec<T, CAP>,
472 processed_len: usize,
473 deleted_cnt: usize,
474 original_len: usize,
475 }
476
477 impl<T, const CAP: usize> Drop for BackshiftOnDrop<'_, T, CAP> {
478 fn drop(&mut self) {
479 if self.deleted_cnt > 0 {
480 unsafe {
481 ptr::copy(
482 self.v.as_ptr().add(self.processed_len),
483 self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt),
484 self.original_len - self.processed_len
485 );
486 }
487 }
488 unsafe {
489 self.v.set_len(self.original_len - self.deleted_cnt);
490 }
491 }
492 }
493
494 let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len };
495
496 while g.processed_len < original_len {
497 let cur = unsafe { g.v.as_mut_ptr().add(g.processed_len) };
498 if !f(unsafe { &mut *cur }) {
499 g.processed_len += 1;
500 g.deleted_cnt += 1;
501 unsafe { ptr::drop_in_place(cur) };
502 continue;
503 }
504 if g.deleted_cnt > 0 {
505 unsafe {
506 let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt);
507 ptr::copy_nonoverlapping(cur, hole_slot, 1);
508 }
509 }
510 g.processed_len += 1;
511 }
512
513 drop(g);
514 }
515
516 /// Set the vector’s length without dropping or moving out elements
517 ///
518 /// This method is `unsafe` because it changes the notion of the
519 /// number of “valid” elements in the vector. Use with care.
520 ///
521 /// This method uses *debug assertions* to check that `length` is
522 /// not greater than the capacity.
523 pub unsafe fn set_len(&mut self, length: usize) {
524 // type invariant that capacity always fits in LenUint
525 debug_assert!(length <= self.capacity());
526 self.len = length as LenUint;
527 }
528
529 /// Copy all elements from the slice and append to the `ArrayVec`.
530 ///
531 /// ```
532 /// use arrayvec::ArrayVec;
533 ///
534 /// let mut vec: ArrayVec<usize, 10> = ArrayVec::new();
535 /// vec.push(1);
536 /// vec.try_extend_from_slice(&[2, 3]).unwrap();
537 /// assert_eq!(&vec[..], &[1, 2, 3]);
538 /// ```
539 ///
540 /// # Errors
541 ///
542 /// This method will return an error if the capacity left (see
543 /// [`remaining_capacity`]) is smaller then the length of the provided
544 /// slice.
545 ///
546 /// [`remaining_capacity`]: #method.remaining_capacity
547 pub fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), CapacityError>
548 where T: Copy,
549 {
550 if self.remaining_capacity() < other.len() {
551 return Err(CapacityError::new(()));
552 }
553
554 let self_len = self.len();
555 let other_len = other.len();
556
557 unsafe {
558 let dst = self.get_unchecked_ptr(self_len);
559 ptr::copy_nonoverlapping(other.as_ptr(), dst, other_len);
560 self.set_len(self_len + other_len);
561 }
562 Ok(())
563 }
564
565 /// Create a draining iterator that removes the specified range in the vector
566 /// and yields the removed items from start to end. The element range is
567 /// removed even if the iterator is not consumed until the end.
568 ///
569 /// Note: It is unspecified how many elements are removed from the vector,
570 /// if the `Drain` value is leaked.
571 ///
572 /// **Panics** if the starting point is greater than the end point or if
573 /// the end point is greater than the length of the vector.
574 ///
575 /// ```
576 /// use arrayvec::ArrayVec;
577 ///
578 /// let mut v1 = ArrayVec::from([1, 2, 3]);
579 /// let v2: ArrayVec<_, 3> = v1.drain(0..2).collect();
580 /// assert_eq!(&v1[..], &[3]);
581 /// assert_eq!(&v2[..], &[1, 2]);
582 /// ```
583 pub fn drain<R>(&mut self, range: R) -> Drain<T, CAP>
584 where R: RangeBounds<usize>
585 {
586 // Memory safety
587 //
588 // When the Drain is first created, it shortens the length of
589 // the source vector to make sure no uninitialized or moved-from elements
590 // are accessible at all if the Drain's destructor never gets to run.
591 //
592 // Drain will ptr::read out the values to remove.
593 // When finished, remaining tail of the vec is copied back to cover
594 // the hole, and the vector length is restored to the new length.
595 //
596 let len = self.len();
597 let start = match range.start_bound() {
598 Bound::Unbounded => 0,
599 Bound::Included(&i) => i,
600 Bound::Excluded(&i) => i.saturating_add(1),
601 };
602 let end = match range.end_bound() {
603 Bound::Excluded(&j) => j,
604 Bound::Included(&j) => j.saturating_add(1),
605 Bound::Unbounded => len,
606 };
607 self.drain_range(start, end)
608 }
609
610 fn drain_range(&mut self, start: usize, end: usize) -> Drain<T, CAP>
611 {
612 let len = self.len();
613
614 // bounds check happens here (before length is changed!)
615 let range_slice: *const _ = &self[start..end];
616
617 // Calling `set_len` creates a fresh and thus unique mutable references, making all
618 // older aliases we created invalid. So we cannot call that function.
619 self.len = start as LenUint;
620
621 unsafe {
622 Drain {
623 tail_start: end,
624 tail_len: len - end,
625 iter: (*range_slice).iter(),
626 vec: self as *mut _,
627 }
628 }
629 }
630
631 /// Return the inner fixed size array, if it is full to its capacity.
632 ///
633 /// Return an `Ok` value with the array if length equals capacity,
634 /// return an `Err` with self otherwise.
635 pub fn into_inner(self) -> Result<[T; CAP], Self> {
636 if self.len() < self.capacity() {
637 Err(self)
638 } else {
136023e0 639 unsafe { Ok(self.into_inner_unchecked()) }
cdc7bbd5
XL
640 }
641 }
642
136023e0
XL
643 /// Return the inner fixed size array.
644 ///
645 /// Safety:
646 /// This operation is safe if and only if length equals capacity.
647 pub unsafe fn into_inner_unchecked(self) -> [T; CAP] {
648 debug_assert_eq!(self.len(), self.capacity());
649 let self_ = ManuallyDrop::new(self);
650 let array = ptr::read(self_.as_ptr() as *const [T; CAP]);
651 array
652 }
653
654 /// Returns the ArrayVec, replacing the original with a new empty ArrayVec.
655 ///
656 /// ```
657 /// use arrayvec::ArrayVec;
658 ///
659 /// let mut v = ArrayVec::from([0, 1, 2, 3]);
660 /// assert_eq!([0, 1, 2, 3], v.take().into_inner().unwrap());
661 /// assert!(v.is_empty());
662 /// ```
663 pub fn take(&mut self) -> Self {
664 mem::replace(self, Self::new())
665 }
666
cdc7bbd5
XL
667 /// Return a slice containing all elements of the vector.
668 pub fn as_slice(&self) -> &[T] {
669 ArrayVecImpl::as_slice(self)
670 }
671
672 /// Return a mutable slice containing all elements of the vector.
673 pub fn as_mut_slice(&mut self) -> &mut [T] {
674 ArrayVecImpl::as_mut_slice(self)
675 }
676
677 /// Return a raw pointer to the vector's buffer.
678 pub fn as_ptr(&self) -> *const T {
679 ArrayVecImpl::as_ptr(self)
680 }
681
682 /// Return a raw mutable pointer to the vector's buffer.
683 pub fn as_mut_ptr(&mut self) -> *mut T {
684 ArrayVecImpl::as_mut_ptr(self)
685 }
686}
687
688impl<T, const CAP: usize> ArrayVecImpl for ArrayVec<T, CAP> {
689 type Item = T;
690 const CAPACITY: usize = CAP;
691
692 fn len(&self) -> usize { self.len() }
693
694 unsafe fn set_len(&mut self, length: usize) {
695 debug_assert!(length <= CAP);
696 self.len = length as LenUint;
697 }
698
699 fn as_ptr(&self) -> *const Self::Item {
700 self.xs.as_ptr() as _
701 }
702
703 fn as_mut_ptr(&mut self) -> *mut Self::Item {
704 self.xs.as_mut_ptr() as _
705 }
706}
707
708impl<T, const CAP: usize> Deref for ArrayVec<T, CAP> {
709 type Target = [T];
710 #[inline]
711 fn deref(&self) -> &Self::Target {
712 self.as_slice()
713 }
714}
715
716impl<T, const CAP: usize> DerefMut for ArrayVec<T, CAP> {
717 #[inline]
718 fn deref_mut(&mut self) -> &mut Self::Target {
719 self.as_mut_slice()
720 }
721}
722
723
724/// Create an `ArrayVec` from an array.
725///
726/// ```
727/// use arrayvec::ArrayVec;
728///
729/// let mut array = ArrayVec::from([1, 2, 3]);
730/// assert_eq!(array.len(), 3);
731/// assert_eq!(array.capacity(), 3);
732/// ```
733impl<T, const CAP: usize> From<[T; CAP]> for ArrayVec<T, CAP> {
734 fn from(array: [T; CAP]) -> Self {
735 let array = ManuallyDrop::new(array);
736 let mut vec = <ArrayVec<T, CAP>>::new();
737 unsafe {
738 (&*array as *const [T; CAP] as *const [MaybeUninit<T>; CAP])
739 .copy_to_nonoverlapping(&mut vec.xs as *mut [MaybeUninit<T>; CAP], 1);
740 vec.set_len(CAP);
741 }
742 vec
743 }
744}
745
746
747/// Try to create an `ArrayVec` from a slice. This will return an error if the slice was too big to
748/// fit.
749///
750/// ```
751/// use arrayvec::ArrayVec;
752/// use std::convert::TryInto as _;
753///
754/// let array: ArrayVec<_, 4> = (&[1, 2, 3] as &[_]).try_into().unwrap();
755/// assert_eq!(array.len(), 3);
756/// assert_eq!(array.capacity(), 4);
757/// ```
758impl<T, const CAP: usize> std::convert::TryFrom<&[T]> for ArrayVec<T, CAP>
759 where T: Clone,
760{
761 type Error = CapacityError;
762
763 fn try_from(slice: &[T]) -> Result<Self, Self::Error> {
764 if Self::CAPACITY < slice.len() {
765 Err(CapacityError::new(()))
766 } else {
767 let mut array = Self::new();
768 array.extend_from_slice(slice);
769 Ok(array)
770 }
771 }
772}
773
774
775/// Iterate the `ArrayVec` with references to each element.
776///
777/// ```
778/// use arrayvec::ArrayVec;
779///
780/// let array = ArrayVec::from([1, 2, 3]);
781///
782/// for elt in &array {
783/// // ...
784/// }
785/// ```
786impl<'a, T: 'a, const CAP: usize> IntoIterator for &'a ArrayVec<T, CAP> {
787 type Item = &'a T;
788 type IntoIter = slice::Iter<'a, T>;
789 fn into_iter(self) -> Self::IntoIter { self.iter() }
790}
791
792/// Iterate the `ArrayVec` with mutable references to each element.
793///
794/// ```
795/// use arrayvec::ArrayVec;
796///
797/// let mut array = ArrayVec::from([1, 2, 3]);
798///
799/// for elt in &mut array {
800/// // ...
801/// }
802/// ```
803impl<'a, T: 'a, const CAP: usize> IntoIterator for &'a mut ArrayVec<T, CAP> {
804 type Item = &'a mut T;
805 type IntoIter = slice::IterMut<'a, T>;
806 fn into_iter(self) -> Self::IntoIter { self.iter_mut() }
807}
808
809/// Iterate the `ArrayVec` with each element by value.
810///
811/// The vector is consumed by this operation.
812///
813/// ```
814/// use arrayvec::ArrayVec;
815///
816/// for elt in ArrayVec::from([1, 2, 3]) {
817/// // ...
818/// }
819/// ```
820impl<T, const CAP: usize> IntoIterator for ArrayVec<T, CAP> {
821 type Item = T;
822 type IntoIter = IntoIter<T, CAP>;
823 fn into_iter(self) -> IntoIter<T, CAP> {
824 IntoIter { index: 0, v: self, }
825 }
826}
827
828
829/// By-value iterator for `ArrayVec`.
830pub struct IntoIter<T, const CAP: usize> {
831 index: usize,
832 v: ArrayVec<T, CAP>,
833}
834
835impl<T, const CAP: usize> Iterator for IntoIter<T, CAP> {
836 type Item = T;
837
838 fn next(&mut self) -> Option<Self::Item> {
839 if self.index == self.v.len() {
840 None
841 } else {
842 unsafe {
843 let index = self.index;
844 self.index = index + 1;
845 Some(ptr::read(self.v.get_unchecked_ptr(index)))
846 }
847 }
848 }
849
850 fn size_hint(&self) -> (usize, Option<usize>) {
851 let len = self.v.len() - self.index;
852 (len, Some(len))
853 }
854}
855
856impl<T, const CAP: usize> DoubleEndedIterator for IntoIter<T, CAP> {
857 fn next_back(&mut self) -> Option<Self::Item> {
858 if self.index == self.v.len() {
859 None
860 } else {
861 unsafe {
862 let new_len = self.v.len() - 1;
863 self.v.set_len(new_len);
864 Some(ptr::read(self.v.get_unchecked_ptr(new_len)))
865 }
866 }
867 }
868}
869
870impl<T, const CAP: usize> ExactSizeIterator for IntoIter<T, CAP> { }
871
872impl<T, const CAP: usize> Drop for IntoIter<T, CAP> {
873 fn drop(&mut self) {
874 // panic safety: Set length to 0 before dropping elements.
875 let index = self.index;
876 let len = self.v.len();
877 unsafe {
878 self.v.set_len(0);
879 let elements = slice::from_raw_parts_mut(
880 self.v.get_unchecked_ptr(index),
881 len - index);
882 ptr::drop_in_place(elements);
883 }
884 }
885}
886
887impl<T, const CAP: usize> Clone for IntoIter<T, CAP>
888where T: Clone,
889{
890 fn clone(&self) -> IntoIter<T, CAP> {
891 let mut v = ArrayVec::new();
892 v.extend_from_slice(&self.v[self.index..]);
893 v.into_iter()
894 }
895}
896
897impl<T, const CAP: usize> fmt::Debug for IntoIter<T, CAP>
898where
899 T: fmt::Debug,
900{
901 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
902 f.debug_list()
903 .entries(&self.v[self.index..])
904 .finish()
905 }
906}
907
908/// A draining iterator for `ArrayVec`.
909pub struct Drain<'a, T: 'a, const CAP: usize> {
910 /// Index of tail to preserve
911 tail_start: usize,
912 /// Length of tail
913 tail_len: usize,
914 /// Current remaining range to remove
915 iter: slice::Iter<'a, T>,
916 vec: *mut ArrayVec<T, CAP>,
917}
918
919unsafe impl<'a, T: Sync, const CAP: usize> Sync for Drain<'a, T, CAP> {}
920unsafe impl<'a, T: Send, const CAP: usize> Send for Drain<'a, T, CAP> {}
921
922impl<'a, T: 'a, const CAP: usize> Iterator for Drain<'a, T, CAP> {
923 type Item = T;
924
925 fn next(&mut self) -> Option<Self::Item> {
926 self.iter.next().map(|elt|
927 unsafe {
928 ptr::read(elt as *const _)
929 }
930 )
931 }
932
933 fn size_hint(&self) -> (usize, Option<usize>) {
934 self.iter.size_hint()
935 }
936}
937
938impl<'a, T: 'a, const CAP: usize> DoubleEndedIterator for Drain<'a, T, CAP>
939{
940 fn next_back(&mut self) -> Option<Self::Item> {
941 self.iter.next_back().map(|elt|
942 unsafe {
943 ptr::read(elt as *const _)
944 }
945 )
946 }
947}
948
949impl<'a, T: 'a, const CAP: usize> ExactSizeIterator for Drain<'a, T, CAP> {}
950
951impl<'a, T: 'a, const CAP: usize> Drop for Drain<'a, T, CAP> {
952 fn drop(&mut self) {
953 // len is currently 0 so panicking while dropping will not cause a double drop.
954
955 // exhaust self first
956 while let Some(_) = self.next() { }
957
958 if self.tail_len > 0 {
959 unsafe {
960 let source_vec = &mut *self.vec;
961 // memmove back untouched tail, update to new length
962 let start = source_vec.len();
963 let tail = self.tail_start;
964 let src = source_vec.as_ptr().add(tail);
965 let dst = source_vec.as_mut_ptr().add(start);
966 ptr::copy(src, dst, self.tail_len);
967 source_vec.set_len(start + self.tail_len);
968 }
969 }
970 }
971}
972
973struct ScopeExitGuard<T, Data, F>
974 where F: FnMut(&Data, &mut T)
975{
976 value: T,
977 data: Data,
978 f: F,
979}
980
981impl<T, Data, F> Drop for ScopeExitGuard<T, Data, F>
982 where F: FnMut(&Data, &mut T)
983{
984 fn drop(&mut self) {
985 (self.f)(&self.data, &mut self.value)
986 }
987}
988
989
990
991/// Extend the `ArrayVec` with an iterator.
992///
993/// ***Panics*** if extending the vector exceeds its capacity.
994impl<T, const CAP: usize> Extend<T> for ArrayVec<T, CAP> {
995 /// Extend the `ArrayVec` with an iterator.
996 ///
997 /// ***Panics*** if extending the vector exceeds its capacity.
998 fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
999 unsafe {
1000 self.extend_from_iter::<_, true>(iter)
1001 }
1002 }
1003}
1004
1005#[inline(never)]
1006#[cold]
1007fn extend_panic() {
1008 panic!("ArrayVec: capacity exceeded in extend/from_iter");
1009}
1010
1011impl<T, const CAP: usize> ArrayVec<T, CAP> {
1012 /// Extend the arrayvec from the iterable.
1013 ///
1014 /// ## Safety
1015 ///
1016 /// Unsafe because if CHECK is false, the length of the input is not checked.
1017 /// The caller must ensure the length of the input fits in the capacity.
1018 pub(crate) unsafe fn extend_from_iter<I, const CHECK: bool>(&mut self, iterable: I)
1019 where I: IntoIterator<Item = T>
1020 {
1021 let take = self.capacity() - self.len();
1022 let len = self.len();
1023 let mut ptr = raw_ptr_add(self.as_mut_ptr(), len);
1024 let end_ptr = raw_ptr_add(ptr, take);
1025 // Keep the length in a separate variable, write it back on scope
1026 // exit. To help the compiler with alias analysis and stuff.
1027 // We update the length to handle panic in the iteration of the
1028 // user's iterator, without dropping any elements on the floor.
1029 let mut guard = ScopeExitGuard {
1030 value: &mut self.len,
1031 data: len,
1032 f: move |&len, self_len| {
1033 **self_len = len as LenUint;
1034 }
1035 };
1036 let mut iter = iterable.into_iter();
1037 loop {
1038 if let Some(elt) = iter.next() {
1039 if ptr == end_ptr && CHECK { extend_panic(); }
1040 debug_assert_ne!(ptr, end_ptr);
1041 ptr.write(elt);
1042 ptr = raw_ptr_add(ptr, 1);
1043 guard.data += 1;
1044 } else {
1045 return; // success
1046 }
1047 }
1048 }
1049
1050 /// Extend the ArrayVec with clones of elements from the slice;
1051 /// the length of the slice must be <= the remaining capacity in the arrayvec.
1052 pub(crate) fn extend_from_slice(&mut self, slice: &[T])
1053 where T: Clone
1054 {
1055 let take = self.capacity() - self.len();
1056 debug_assert!(slice.len() <= take);
1057 unsafe {
1058 let slice = if take < slice.len() { &slice[..take] } else { slice };
1059 self.extend_from_iter::<_, false>(slice.iter().cloned());
1060 }
1061 }
1062}
1063
1064/// Rawptr add but uses arithmetic distance for ZST
1065unsafe fn raw_ptr_add<T>(ptr: *mut T, offset: usize) -> *mut T {
1066 if mem::size_of::<T>() == 0 {
1067 // Special case for ZST
1068 (ptr as usize).wrapping_add(offset) as _
1069 } else {
1070 ptr.add(offset)
1071 }
1072}
1073
1074/// Create an `ArrayVec` from an iterator.
1075///
1076/// ***Panics*** if the number of elements in the iterator exceeds the arrayvec's capacity.
1077impl<T, const CAP: usize> iter::FromIterator<T> for ArrayVec<T, CAP> {
1078 /// Create an `ArrayVec` from an iterator.
1079 ///
1080 /// ***Panics*** if the number of elements in the iterator exceeds the arrayvec's capacity.
1081 fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> Self {
1082 let mut array = ArrayVec::new();
1083 array.extend(iter);
1084 array
1085 }
1086}
1087
1088impl<T, const CAP: usize> Clone for ArrayVec<T, CAP>
1089 where T: Clone
1090{
1091 fn clone(&self) -> Self {
1092 self.iter().cloned().collect()
1093 }
1094
1095 fn clone_from(&mut self, rhs: &Self) {
1096 // recursive case for the common prefix
1097 let prefix = cmp::min(self.len(), rhs.len());
1098 self[..prefix].clone_from_slice(&rhs[..prefix]);
1099
1100 if prefix < self.len() {
1101 // rhs was shorter
136023e0 1102 self.truncate(prefix);
cdc7bbd5
XL
1103 } else {
1104 let rhs_elems = &rhs[self.len()..];
1105 self.extend_from_slice(rhs_elems);
1106 }
1107 }
1108}
1109
1110impl<T, const CAP: usize> Hash for ArrayVec<T, CAP>
1111 where T: Hash
1112{
1113 fn hash<H: Hasher>(&self, state: &mut H) {
1114 Hash::hash(&**self, state)
1115 }
1116}
1117
1118impl<T, const CAP: usize> PartialEq for ArrayVec<T, CAP>
1119 where T: PartialEq
1120{
1121 fn eq(&self, other: &Self) -> bool {
1122 **self == **other
1123 }
1124}
1125
1126impl<T, const CAP: usize> PartialEq<[T]> for ArrayVec<T, CAP>
1127 where T: PartialEq
1128{
1129 fn eq(&self, other: &[T]) -> bool {
1130 **self == *other
1131 }
1132}
1133
1134impl<T, const CAP: usize> Eq for ArrayVec<T, CAP> where T: Eq { }
1135
1136impl<T, const CAP: usize> Borrow<[T]> for ArrayVec<T, CAP> {
1137 fn borrow(&self) -> &[T] { self }
1138}
1139
1140impl<T, const CAP: usize> BorrowMut<[T]> for ArrayVec<T, CAP> {
1141 fn borrow_mut(&mut self) -> &mut [T] { self }
1142}
1143
1144impl<T, const CAP: usize> AsRef<[T]> for ArrayVec<T, CAP> {
1145 fn as_ref(&self) -> &[T] { self }
1146}
1147
1148impl<T, const CAP: usize> AsMut<[T]> for ArrayVec<T, CAP> {
1149 fn as_mut(&mut self) -> &mut [T] { self }
1150}
1151
1152impl<T, const CAP: usize> fmt::Debug for ArrayVec<T, CAP> where T: fmt::Debug {
1153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) }
1154}
1155
1156impl<T, const CAP: usize> Default for ArrayVec<T, CAP> {
1157 /// Return an empty array
1158 fn default() -> ArrayVec<T, CAP> {
1159 ArrayVec::new()
1160 }
1161}
1162
1163impl<T, const CAP: usize> PartialOrd for ArrayVec<T, CAP> where T: PartialOrd {
1164 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
1165 (**self).partial_cmp(other)
1166 }
1167
1168 fn lt(&self, other: &Self) -> bool {
1169 (**self).lt(other)
1170 }
1171
1172 fn le(&self, other: &Self) -> bool {
1173 (**self).le(other)
1174 }
1175
1176 fn ge(&self, other: &Self) -> bool {
1177 (**self).ge(other)
1178 }
1179
1180 fn gt(&self, other: &Self) -> bool {
1181 (**self).gt(other)
1182 }
1183}
1184
1185impl<T, const CAP: usize> Ord for ArrayVec<T, CAP> where T: Ord {
1186 fn cmp(&self, other: &Self) -> cmp::Ordering {
1187 (**self).cmp(other)
1188 }
1189}
1190
1191#[cfg(feature="std")]
1192/// `Write` appends written data to the end of the vector.
1193///
1194/// Requires `features="std"`.
1195impl<const CAP: usize> io::Write for ArrayVec<u8, CAP> {
1196 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1197 let len = cmp::min(self.remaining_capacity(), data.len());
1198 let _result = self.try_extend_from_slice(&data[..len]);
1199 debug_assert!(_result.is_ok());
1200 Ok(len)
1201 }
1202 fn flush(&mut self) -> io::Result<()> { Ok(()) }
1203}
1204
1205#[cfg(feature="serde")]
1206/// Requires crate feature `"serde"`
1207impl<T: Serialize, const CAP: usize> Serialize for ArrayVec<T, CAP> {
1208 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1209 where S: Serializer
1210 {
1211 serializer.collect_seq(self)
1212 }
1213}
1214
1215#[cfg(feature="serde")]
1216/// Requires crate feature `"serde"`
1217impl<'de, T: Deserialize<'de>, const CAP: usize> Deserialize<'de> for ArrayVec<T, CAP> {
1218 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1219 where D: Deserializer<'de>
1220 {
1221 use serde::de::{Visitor, SeqAccess, Error};
1222 use std::marker::PhantomData;
1223
1224 struct ArrayVecVisitor<'de, T: Deserialize<'de>, const CAP: usize>(PhantomData<(&'de (), [T; CAP])>);
1225
1226 impl<'de, T: Deserialize<'de>, const CAP: usize> Visitor<'de> for ArrayVecVisitor<'de, T, CAP> {
1227 type Value = ArrayVec<T, CAP>;
1228
1229 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1230 write!(formatter, "an array with no more than {} items", CAP)
1231 }
1232
1233 fn visit_seq<SA>(self, mut seq: SA) -> Result<Self::Value, SA::Error>
1234 where SA: SeqAccess<'de>,
1235 {
1236 let mut values = ArrayVec::<T, CAP>::new();
1237
1238 while let Some(value) = seq.next_element()? {
1239 if let Err(_) = values.try_push(value) {
1240 return Err(SA::Error::invalid_length(CAP + 1, &self));
1241 }
1242 }
1243
1244 Ok(values)
1245 }
1246 }
1247
1248 deserializer.deserialize_seq(ArrayVecVisitor::<T, CAP>(PhantomData))
1249 }
1250}