]> git.proxmox.com Git - rustc.git/blob - src/librustc_data_structures/veccell/mod.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / librustc_data_structures / veccell / mod.rs
1 // Copyright 2012-2014 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.
4 //
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.
10
11 use std::cell::UnsafeCell;
12 use std::mem;
13
14 pub struct VecCell<T> {
15 data: UnsafeCell<Vec<T>>,
16 }
17
18 impl<T> VecCell<T> {
19 pub fn with_capacity(capacity: usize) -> VecCell<T> {
20 VecCell { data: UnsafeCell::new(Vec::with_capacity(capacity)) }
21 }
22
23 #[inline]
24 pub fn push(&self, data: T) -> usize {
25 // The logic here, and in `swap` below, is that the `push`
26 // method on the vector will not recursively access this
27 // `VecCell`. Therefore, we can temporarily obtain mutable
28 // access, secure in the knowledge that even if aliases exist
29 // -- indeed, even if aliases are reachable from within the
30 // vector -- they will not be used for the duration of this
31 // particular fn call. (Note that we also are relying on the
32 // fact that `VecCell` is not `Sync`.)
33 unsafe {
34 let v = self.data.get();
35 (*v).push(data);
36 (*v).len()
37 }
38 }
39
40 pub fn swap(&self, mut data: Vec<T>) -> Vec<T> {
41 unsafe {
42 let v = self.data.get();
43 mem::swap(&mut *v, &mut data);
44 }
45 data
46 }
47 }