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};
24 pub unsafe trait Array {
26 type PartialStorage: Default + Unsize<[ManuallyDrop<Self::Element>]>;
30 unsafe impl<T> Array for [T; 1] {
32 type PartialStorage = [ManuallyDrop<T>; 1];
36 unsafe impl<T> Array for [T; 8] {
38 type PartialStorage = [ManuallyDrop<T>; 8];
42 pub struct ArrayVec<A: Array> {
44 values: A::PartialStorage
47 impl<A> Hash for ArrayVec<A>
50 fn hash<H>(&self, state: &mut H) where H: Hasher {
51 (&self[..]).hash(state);
55 impl<A> Clone for ArrayVec<A>
58 fn clone(&self) -> Self {
59 let mut v = ArrayVec::new();
60 v.extend(self.iter().cloned());
65 impl<A: Array> ArrayVec<A> {
66 pub fn new() -> Self {
69 values: Default::default(),
73 pub fn len(&self) -> usize {
77 pub unsafe fn set_len(&mut self, len: usize) {
81 /// Panics when the stack vector is full.
82 pub fn push(&mut self, el: A::Element) {
83 let arr = &mut self.values as &mut [ManuallyDrop<_>];
84 arr[self.count] = ManuallyDrop { value: el };
88 pub fn pop(&mut self) -> Option<A::Element> {
90 let arr = &mut self.values as &mut [ManuallyDrop<_>];
93 let value = ptr::read(&arr[self.count]);
101 pub fn drain<R>(&mut self, range: R) -> Drain<A>
102 where R: RangeArgument<usize>
106 // When the Drain is first created, it shortens the length of
107 // the source vector to make sure no uninitalized or moved-from elements
108 // are accessible at all if the Drain's destructor never gets to run.
110 // Drain will ptr::read out the values to remove.
111 // When finished, remaining tail of the vec is copied back to cover
112 // the hole, and the vector length is restored to the new length.
114 let len = self.len();
115 let start = match range.start() {
117 Excluded(&n) => n + 1,
120 let end = match range.end() {
121 Included(&n) => n + 1,
125 assert!(start <= end);
129 // set self.vec length's to start, to be safe in case Drain is leaked
131 // Use the borrow in the IterMut to indicate borrowing behavior of the
132 // whole Drain iterator (like &mut T).
134 let arr = &mut self.values as &mut [ManuallyDrop<_>];
135 slice::from_raw_parts_mut(arr.as_mut_ptr().offset(start as isize),
141 iter: range_slice.iter(),
142 array_vec: Shared::new(self as *mut _),
148 impl<A> Default for ArrayVec<A>
150 fn default() -> Self {
155 impl<A> fmt::Debug for ArrayVec<A>
157 A::Element: fmt::Debug {
158 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
163 impl<A: Array> Deref for ArrayVec<A> {
164 type Target = [A::Element];
165 fn deref(&self) -> &Self::Target {
167 slice::from_raw_parts(&self.values as *const _ as *const A::Element, self.count)
172 impl<A: Array> DerefMut for ArrayVec<A> {
173 fn deref_mut(&mut self) -> &mut [A::Element] {
175 slice::from_raw_parts_mut(&mut self.values as *mut _ as *mut A::Element, self.count)
180 impl<A: Array> Drop for ArrayVec<A> {
183 drop_in_place(&mut self[..])
188 impl<A: Array> Extend<A::Element> for ArrayVec<A> {
189 fn extend<I>(&mut self, iter: I) where I: IntoIterator<Item=A::Element> {
196 pub struct Iter<A: Array> {
197 indices: Range<usize>,
198 store: A::PartialStorage,
201 impl<A: Array> Drop for Iter<A> {
207 impl<A: Array> Iterator for Iter<A> {
208 type Item = A::Element;
210 fn next(&mut self) -> Option<A::Element> {
211 let arr = &self.store as &[ManuallyDrop<_>];
213 self.indices.next().map(|i| ptr::read(&arr[i]).value)
217 fn size_hint(&self) -> (usize, Option<usize>) {
218 self.indices.size_hint()
222 pub struct Drain<'a, A: Array>
227 iter: slice::Iter<'a, ManuallyDrop<A::Element>>,
228 array_vec: Shared<ArrayVec<A>>,
231 impl<'a, A: Array> Iterator for Drain<'a, A> {
232 type Item = A::Element;
235 fn next(&mut self) -> Option<A::Element> {
236 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const ManuallyDrop<_>).value })
239 fn size_hint(&self) -> (usize, Option<usize>) {
240 self.iter.size_hint()
244 impl<'a, A: Array> Drop for Drain<'a, A> {
246 // exhaust self first
247 while let Some(_) = self.next() {}
249 if self.tail_len > 0 {
251 let source_array_vec = &mut **self.array_vec;
252 // memmove back untouched tail, update to new length
253 let start = source_array_vec.len();
254 let tail = self.tail_start;
256 let mut arr = &mut source_array_vec.values as &mut [ManuallyDrop<_>];
257 let src = arr.as_ptr().offset(tail as isize);
258 let dst = arr.as_mut_ptr().offset(start as isize);
259 ptr::copy(src, dst, self.tail_len);
261 source_array_vec.set_len(start + self.tail_len);
267 impl<A: Array> IntoIterator for ArrayVec<A> {
268 type Item = A::Element;
269 type IntoIter = Iter<A>;
270 fn into_iter(self) -> Self::IntoIter {
272 ptr::read(&self.values)
274 let indices = 0..self.count;
283 impl<'a, A: Array> IntoIterator for &'a ArrayVec<A> {
284 type Item = &'a A::Element;
285 type IntoIter = slice::Iter<'a, A::Element>;
286 fn into_iter(self) -> Self::IntoIter {
291 impl<'a, A: Array> IntoIterator for &'a mut ArrayVec<A> {
292 type Item = &'a mut A::Element;
293 type IntoIter = slice::IterMut<'a, A::Element>;
294 fn into_iter(self) -> Self::IntoIter {
299 // FIXME: This should use repr(transparent) from rust-lang/rfcs#1758.
300 #[allow(unions_with_drop_fields)]
301 pub union ManuallyDrop<T> {
307 impl<T> ManuallyDrop<T> {
308 fn new() -> ManuallyDrop<T> {
315 impl<T> Default for ManuallyDrop<T> {
316 fn default() -> Self {