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 pub struct ArrayVec<A: Array> {
45 values: A::PartialStorage
48 impl<A> Hash for ArrayVec<A>
51 fn hash<H>(&self, state: &mut H) where H: Hasher {
52 (&self[..]).hash(state);
56 impl<A> Clone for ArrayVec<A>
59 fn clone(&self) -> Self {
60 let mut v = ArrayVec::new();
61 v.extend(self.iter().cloned());
66 impl<A: Array> ArrayVec<A> {
67 pub fn new() -> Self {
70 values: unsafe { ::std::mem::uninitialized() },
74 pub fn len(&self) -> usize {
78 pub unsafe fn set_len(&mut self, len: usize) {
82 /// Panics when the stack vector is full.
83 pub fn push(&mut self, el: A::Element) {
84 let arr = &mut self.values as &mut [ManuallyDrop<_>];
85 arr[self.count] = ManuallyDrop::new(el);
89 pub fn pop(&mut self) -> Option<A::Element> {
91 let arr = &mut self.values as &mut [ManuallyDrop<_>];
94 let value = ptr::read(&*arr[self.count]);
102 pub fn drain<R>(&mut self, range: R) -> Drain<A>
103 where R: RangeArgument<usize>
107 // When the Drain is first created, it shortens the length of
108 // the source vector to make sure no uninitalized or moved-from elements
109 // are accessible at all if the Drain's destructor never gets to run.
111 // Drain will ptr::read out the values to remove.
112 // When finished, remaining tail of the vec is copied back to cover
113 // the hole, and the vector length is restored to the new length.
115 let len = self.len();
116 let start = match range.start() {
118 Excluded(&n) => n + 1,
121 let end = match range.end() {
122 Included(&n) => n + 1,
126 assert!(start <= end);
130 // set self.vec length's to start, to be safe in case Drain is leaked
132 // Use the borrow in the IterMut to indicate borrowing behavior of the
133 // whole Drain iterator (like &mut T).
135 let arr = &mut self.values as &mut [ManuallyDrop<_>];
136 slice::from_raw_parts_mut(arr.as_mut_ptr().offset(start as isize),
142 iter: range_slice.iter(),
143 array_vec: Shared::new(self as *mut _),
149 impl<A> Default for ArrayVec<A>
151 fn default() -> Self {
156 impl<A> fmt::Debug for ArrayVec<A>
158 A::Element: fmt::Debug {
159 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
164 impl<A: Array> Deref for ArrayVec<A> {
165 type Target = [A::Element];
166 fn deref(&self) -> &Self::Target {
168 slice::from_raw_parts(&self.values as *const _ as *const A::Element, self.count)
173 impl<A: Array> DerefMut for ArrayVec<A> {
174 fn deref_mut(&mut self) -> &mut [A::Element] {
176 slice::from_raw_parts_mut(&mut self.values as *mut _ as *mut A::Element, self.count)
181 impl<A: Array> Drop for ArrayVec<A> {
184 drop_in_place(&mut self[..])
189 impl<A: Array> Extend<A::Element> for ArrayVec<A> {
190 fn extend<I>(&mut self, iter: I) where I: IntoIterator<Item=A::Element> {
197 pub struct Iter<A: Array> {
198 indices: Range<usize>,
199 store: A::PartialStorage,
202 impl<A: Array> Drop for Iter<A> {
208 impl<A: Array> Iterator for Iter<A> {
209 type Item = A::Element;
211 fn next(&mut self) -> Option<A::Element> {
212 let arr = &self.store as &[ManuallyDrop<_>];
214 self.indices.next().map(|i| ptr::read(&*arr[i]))
218 fn size_hint(&self) -> (usize, Option<usize>) {
219 self.indices.size_hint()
223 pub struct Drain<'a, A: Array>
228 iter: slice::Iter<'a, ManuallyDrop<A::Element>>,
229 array_vec: Shared<ArrayVec<A>>,
232 impl<'a, A: Array> Iterator for Drain<'a, A> {
233 type Item = A::Element;
236 fn next(&mut self) -> Option<A::Element> {
237 self.iter.next().map(|elt| unsafe { ptr::read(&**elt) })
240 fn size_hint(&self) -> (usize, Option<usize>) {
241 self.iter.size_hint()
245 impl<'a, A: Array> Drop for Drain<'a, A> {
247 // exhaust self first
248 while let Some(_) = self.next() {}
250 if self.tail_len > 0 {
252 let source_array_vec = &mut *self.array_vec.as_mut_ptr();
253 // memmove back untouched tail, update to new length
254 let start = source_array_vec.len();
255 let tail = self.tail_start;
257 let mut arr = &mut source_array_vec.values as &mut [ManuallyDrop<_>];
258 let src = arr.as_ptr().offset(tail as isize);
259 let dst = arr.as_mut_ptr().offset(start as isize);
260 ptr::copy(src, dst, self.tail_len);
262 source_array_vec.set_len(start + self.tail_len);
268 impl<A: Array> IntoIterator for ArrayVec<A> {
269 type Item = A::Element;
270 type IntoIter = Iter<A>;
271 fn into_iter(self) -> Self::IntoIter {
273 ptr::read(&self.values)
275 let indices = 0..self.count;
284 impl<'a, A: Array> IntoIterator for &'a ArrayVec<A> {
285 type Item = &'a A::Element;
286 type IntoIter = slice::Iter<'a, A::Element>;
287 fn into_iter(self) -> Self::IntoIter {
292 impl<'a, A: Array> IntoIterator for &'a mut ArrayVec<A> {
293 type Item = &'a mut A::Element;
294 type IntoIter = slice::IterMut<'a, A::Element>;
295 fn into_iter(self) -> Self::IntoIter {