1 // Copyright 2017 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.
12 use std::ops::{Deref, Range};
14 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
15 use rustc_data_structures::sync::Lrc;
25 pub fn new(mut vec: Vec<T>) -> Self {
26 // By default, constructing RcVec from Vec gives it just enough capacity
27 // to hold the initial elements. Callers that anticipate needing to
28 // extend the vector may prefer RcVec::new_preserving_capacity.
30 Self::new_preserving_capacity(vec)
33 pub fn new_preserving_capacity(vec: Vec<T>) -> Self {
36 len: vec.len() as u32,
41 pub fn sub_slice(&self, range: Range<usize>) -> Self {
43 data: self.data.clone(),
44 offset: self.offset + range.start as u32,
45 len: (range.end - range.start) as u32,
49 /// If this RcVec has exactly one strong reference, returns ownership of the
50 /// underlying vector. Otherwise returns self unmodified.
51 pub fn try_unwrap(self) -> Result<Vec<T>, Self> {
52 match Lrc::try_unwrap(self.data) {
53 // If no other RcVec shares ownership of this data.
55 // Drop any elements after our view of the data.
56 vec.truncate(self.offset as usize + self.len as usize);
57 // Drop any elements before our view of the data. Do this after
58 // the `truncate` so that elements past the end of our view do
59 // not need to be copied around.
60 vec.drain(..self.offset as usize);
64 // If the data is shared.
65 Err(data) => Err(RcVec { data, ..self }),
70 impl<T> Deref for RcVec<T> {
72 fn deref(&self) -> &[T] {
73 &self.data[self.offset as usize..(self.offset + self.len) as usize]
77 impl<T: fmt::Debug> fmt::Debug for RcVec<T> {
78 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79 fmt::Debug::fmt(self.deref(), f)
83 impl<CTX, T> HashStable<CTX> for RcVec<T>
87 fn hash_stable<W: StableHasherResult>(&self, hcx: &mut CTX, hasher: &mut StableHasher<W>) {
88 (**self).hash_stable(hcx, hasher);