1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A stack-allocated vector, allowing storage of N elements on the stack.
13 use std::marker::Unsize;
14 use std::iter::Extend;
15 use std::ptr::{self, drop_in_place, Shared};
16 use std::ops::{Deref, DerefMut, Range};
17 use std::hash::{Hash, Hasher};
21 use std::collections::range::RangeArgument;
22 use std::collections::Bound::{Excluded, Included, Unbounded};
23 use std::mem::ManuallyDrop;
25 pub unsafe trait Array {
27 type PartialStorage: Unsize<[ManuallyDrop<Self::Element>]>;
31 unsafe impl<T> Array for [T; 1] {
33 type PartialStorage = [ManuallyDrop<T>; 1];
37 unsafe impl<T> Array for [T; 8] {
39 type PartialStorage = [ManuallyDrop<T>; 8];
43 unsafe impl<T> Array for [T; 32] {
45 type PartialStorage = [ManuallyDrop<T>; 32];
46 const LEN: usize = 32;
49 pub struct ArrayVec<A: Array> {
51 values: A::PartialStorage
54 impl<A> Hash for ArrayVec<A>
57 fn hash<H>(&self, state: &mut H) where H: Hasher {
58 (&self[..]).hash(state);
62 impl<A> Clone for ArrayVec<A>
65 fn clone(&self) -> Self {
66 let mut v = ArrayVec::new();
67 v.extend(self.iter().cloned());
72 impl<A: Array> ArrayVec<A> {
73 pub fn new() -> Self {
76 values: unsafe { ::std::mem::uninitialized() },
80 pub fn len(&self) -> usize {
84 pub unsafe fn set_len(&mut self, len: usize) {
88 /// Panics when the stack vector is full.
89 pub fn push(&mut self, el: A::Element) {
90 let arr = &mut self.values as &mut [ManuallyDrop<_>];
91 arr[self.count] = ManuallyDrop::new(el);
95 pub fn pop(&mut self) -> Option<A::Element> {
97 let arr = &mut self.values as &mut [ManuallyDrop<_>];
100 let value = ptr::read(&*arr[self.count]);
108 pub fn drain<R>(&mut self, range: R) -> Drain<A>
109 where R: RangeArgument<usize>
113 // When the Drain is first created, it shortens the length of
114 // the source vector to make sure no uninitalized or moved-from elements
115 // are accessible at all if the Drain's destructor never gets to run.
117 // Drain will ptr::read out the values to remove.
118 // When finished, remaining tail of the vec is copied back to cover
119 // the hole, and the vector length is restored to the new length.
121 let len = self.len();
122 let start = match range.start() {
124 Excluded(&n) => n + 1,
127 let end = match range.end() {
128 Included(&n) => n + 1,
132 assert!(start <= end);
136 // set self.vec length's to start, to be safe in case Drain is leaked
138 // Use the borrow in the IterMut to indicate borrowing behavior of the
139 // whole Drain iterator (like &mut T).
141 let arr = &mut self.values as &mut [ManuallyDrop<_>];
142 slice::from_raw_parts_mut(arr.as_mut_ptr().offset(start as isize),
148 iter: range_slice.iter(),
149 array_vec: Shared::new(self as *mut _),
155 impl<A> Default for ArrayVec<A>
157 fn default() -> Self {
162 impl<A> fmt::Debug for ArrayVec<A>
164 A::Element: fmt::Debug {
165 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
170 impl<A: Array> Deref for ArrayVec<A> {
171 type Target = [A::Element];
172 fn deref(&self) -> &Self::Target {
174 slice::from_raw_parts(&self.values as *const _ as *const A::Element, self.count)
179 impl<A: Array> DerefMut for ArrayVec<A> {
180 fn deref_mut(&mut self) -> &mut [A::Element] {
182 slice::from_raw_parts_mut(&mut self.values as *mut _ as *mut A::Element, self.count)
187 impl<A: Array> Drop for ArrayVec<A> {
190 drop_in_place(&mut self[..])
195 impl<A: Array> Extend<A::Element> for ArrayVec<A> {
196 fn extend<I>(&mut self, iter: I) where I: IntoIterator<Item=A::Element> {
203 pub struct Iter<A: Array> {
204 indices: Range<usize>,
205 store: A::PartialStorage,
208 impl<A: Array> Drop for Iter<A> {
214 impl<A: Array> Iterator for Iter<A> {
215 type Item = A::Element;
217 fn next(&mut self) -> Option<A::Element> {
218 let arr = &self.store as &[ManuallyDrop<_>];
220 self.indices.next().map(|i| ptr::read(&*arr[i]))
224 fn size_hint(&self) -> (usize, Option<usize>) {
225 self.indices.size_hint()
229 pub struct Drain<'a, A: Array>
234 iter: slice::Iter<'a, ManuallyDrop<A::Element>>,
235 array_vec: Shared<ArrayVec<A>>,
238 impl<'a, A: Array> Iterator for Drain<'a, A> {
239 type Item = A::Element;
242 fn next(&mut self) -> Option<A::Element> {
243 self.iter.next().map(|elt| unsafe { ptr::read(&**elt) })
246 fn size_hint(&self) -> (usize, Option<usize>) {
247 self.iter.size_hint()
251 impl<'a, A: Array> Drop for Drain<'a, A> {
253 // exhaust self first
254 while let Some(_) = self.next() {}
256 if self.tail_len > 0 {
258 let source_array_vec = &mut *self.array_vec.as_mut_ptr();
259 // memmove back untouched tail, update to new length
260 let start = source_array_vec.len();
261 let tail = self.tail_start;
263 let mut arr = &mut source_array_vec.values as &mut [ManuallyDrop<_>];
264 let src = arr.as_ptr().offset(tail as isize);
265 let dst = arr.as_mut_ptr().offset(start as isize);
266 ptr::copy(src, dst, self.tail_len);
268 source_array_vec.set_len(start + self.tail_len);
274 impl<A: Array> IntoIterator for ArrayVec<A> {
275 type Item = A::Element;
276 type IntoIter = Iter<A>;
277 fn into_iter(self) -> Self::IntoIter {
279 ptr::read(&self.values)
281 let indices = 0..self.count;
290 impl<'a, A: Array> IntoIterator for &'a ArrayVec<A> {
291 type Item = &'a A::Element;
292 type IntoIter = slice::Iter<'a, A::Element>;
293 fn into_iter(self) -> Self::IntoIter {
298 impl<'a, A: Array> IntoIterator for &'a mut ArrayVec<A> {
299 type Item = &'a mut A::Element;
300 type IntoIter = slice::IterMut<'a, A::Element>;
301 fn into_iter(self) -> Self::IntoIter {