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