1 // HACK(eddyb) this is a copy of `syntax::ptr`, minus the mutation (the HIR is
2 // frozen anyway). The only reason for doing this instead of replacing `P<T>`
3 // with `Box<T>` in HIR, is that `&Box<[T]>` doesn't implement `IntoIterator`.
5 use std::fmt::{self, Display, Debug};
6 use std::iter::FromIterator;
10 use rustc_serialize::{Encodable, Decodable, Encoder, Decoder};
12 use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
13 /// An owned smart pointer.
14 #[derive(PartialEq, Eq)]
15 pub struct P<T: ?Sized> {
19 /// Construct a `P<T>` from a `T` value.
20 #[allow(non_snake_case)]
21 pub fn P<T: 'static>(value: T) -> P<T> {
27 impl<T: 'static> P<T> {
28 // HACK(eddyb) used by HIR lowering in a few places still.
29 // NOTE: do not make this more public than `pub(super)`.
30 pub(super) fn into_inner(self) -> T {
35 impl<T: ?Sized> Deref for P<T> {
38 fn deref(&self) -> &T {
43 impl<T: ?Sized + Debug> Debug for P<T> {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 Debug::fmt(&self.ptr, f)
49 impl<T: Display> Display for P<T> {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 Display::fmt(&**self, f)
55 impl<T: 'static + Decodable> Decodable for P<T> {
56 fn decode<D: Decoder>(d: &mut D) -> Result<P<T>, D::Error> {
57 Decodable::decode(d).map(P)
61 impl<T: Encodable> Encodable for P<T> {
62 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
68 pub const fn new() -> P<[T]> {
69 // HACK(eddyb) bypass the lack of a `const fn` to create an empty `Box<[T]>`
70 // (as trait methods, `default` in this case, can't be `const fn` yet).
73 use std::ptr::NonNull;
74 std::mem::transmute(NonNull::<[T; 0]>::dangling() as NonNull<[T]>)
80 pub fn from_vec(v: Vec<T>) -> P<[T]> {
81 P { ptr: v.into_boxed_slice() }
84 // HACK(eddyb) used by HIR lowering in a few places still.
85 // NOTE: do not make this more public than `pub(super)`,
86 // and do not make this into an `IntoIterator` impl.
87 pub(super) fn into_iter(self) -> vec::IntoIter<T> {
88 self.ptr.into_vec().into_iter()
93 impl<T> Default for P<[T]> {
94 /// Creates an empty `P<[T]>`.
95 fn default() -> P<[T]> {
100 impl<T> From<Vec<T>> for P<[T]> {
101 fn from(v: Vec<T>) -> Self {
106 impl<T> FromIterator<T> for P<[T]> {
107 fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> P<[T]> {
108 P::from_vec(iter.into_iter().collect())
112 impl<'a, T> IntoIterator for &'a P<[T]> {
114 type IntoIter = slice::Iter<'a, T>;
115 fn into_iter(self) -> Self::IntoIter {
120 impl<T: Encodable> Encodable for P<[T]> {
121 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
122 Encodable::encode(&**self, s)
126 impl<T: Decodable> Decodable for P<[T]> {
127 fn decode<D: Decoder>(d: &mut D) -> Result<P<[T]>, D::Error> {
128 Ok(P::from_vec(Decodable::decode(d)?))
132 impl<CTX, T> HashStable<CTX> for P<T>
133 where T: ?Sized + HashStable<CTX>
135 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
136 (**self).hash_stable(hcx, hasher);