1 // Copyright 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.
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.
13 //! Provides `P<T>`, a frozen owned smart pointer, as a replacement for `@T` in
16 //! # Motivations and benefits
18 //! * **Identity**: sharing AST nodes is problematic for the various analysis
19 //! passes (e.g. one may be able to bypass the borrow checker with a shared
20 //! `ExprKind::AddrOf` node taking a mutable borrow). The only reason `@T` in the
21 //! AST hasn't caused issues is because of inefficient folding passes which
22 //! would always deduplicate any such shared nodes. Even if the AST were to
23 //! switch to an arena, this would still hold, i.e. it couldn't use `&'a T`,
24 //! but rather a wrapper like `P<'a, T>`.
26 //! * **Immutability**: `P<T>` disallows mutating its inner `T`, unlike `Box<T>`
27 //! (unless it contains an `Unsafe` interior, but that may be denied later).
28 //! This mainly prevents mistakes, but can also enforces a kind of "purity".
30 //! * **Efficiency**: folding can reuse allocation space for `P<T>` and `Vec<T>`,
31 //! the latter even when the input and output types differ (as it would be the
32 //! case with arenas or a GADT AST using type parameters to toggle features).
34 //! * **Maintainability**: `P<T>` provides a fixed interface - `Deref`,
35 //! `and_then` and `map` - which can remain fully functional even if the
36 //! implementation changes (using a special thread-local heap, for example).
37 //! Moreover, a switch to, e.g. `P<'a, T>` would be easy and mostly automated.
39 use std
::fmt
::{self, Display, Debug}
;
40 use std
::iter
::FromIterator
;
42 use std
::{mem, ptr, slice, vec}
;
44 use serialize
::{Encodable, Decodable, Encoder, Decoder}
;
46 /// An owned smart pointer.
47 #[derive(Hash, PartialEq, Eq, PartialOrd, Ord)]
48 pub struct P
<T
: ?Sized
> {
52 #[allow(non_snake_case)]
53 /// Construct a `P<T>` from a `T` value.
54 pub fn P
<T
: '
static>(value
: T
) -> P
<T
> {
60 impl<T
: '
static> P
<T
> {
61 /// Move out of the pointer.
62 /// Intended for chaining transformations not covered by `map`.
63 pub fn and_then
<U
, F
>(self, f
: F
) -> U
where
68 /// Equivalent to and_then(|x| x)
69 pub fn unwrap(self) -> T
{
73 /// Transform the inner value, consuming `self` and producing a new `P<T>`.
74 pub fn map
<F
>(mut self, f
: F
) -> P
<T
> where
77 let p
: *mut T
= &mut *self.ptr
;
79 // Leak self in case of panic.
80 // FIXME(eddyb) Use some sort of "free guard" that
81 // only deallocates, without dropping the pointee,
82 // in case the call the `f` below ends in a panic.
86 ptr
::write(p
, f(ptr
::read(p
)));
88 // Recreate self from the raw pointer.
96 impl<T
: ?Sized
> Deref
for P
<T
> {
99 fn deref(&self) -> &T
{
104 impl<T
: '
static + Clone
> Clone
for P
<T
> {
105 fn clone(&self) -> P
<T
> {
110 impl<T
: ?Sized
+ Debug
> Debug
for P
<T
> {
111 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
112 Debug
::fmt(&self.ptr
, f
)
116 impl<T
: Display
> Display
for P
<T
> {
117 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
118 Display
::fmt(&**self, f
)
122 impl<T
> fmt
::Pointer
for P
<T
> {
123 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
124 fmt
::Pointer
::fmt(&self.ptr
, f
)
128 impl<T
: '
static + Decodable
> Decodable
for P
<T
> {
129 fn decode
<D
: Decoder
>(d
: &mut D
) -> Result
<P
<T
>, D
::Error
> {
130 Decodable
::decode(d
).map(P
)
134 impl<T
: Encodable
> Encodable
for P
<T
> {
135 fn encode
<S
: Encoder
>(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
141 pub fn new() -> P
<[T
]> {
142 P { ptr: Default::default() }
146 pub fn from_vec(v
: Vec
<T
>) -> P
<[T
]> {
147 P { ptr: v.into_boxed_slice() }
151 pub fn into_vec(self) -> Vec
<T
> {
156 impl<T
> Default
for P
<[T
]> {
157 /// Creates an empty `P<[T]>`.
158 fn default() -> P
<[T
]> {
163 impl<T
: Clone
> Clone
for P
<[T
]> {
164 fn clone(&self) -> P
<[T
]> {
165 P
::from_vec(self.to_vec())
169 impl<T
> From
<Vec
<T
>> for P
<[T
]> {
170 fn from(v
: Vec
<T
>) -> Self {
175 impl<T
> Into
<Vec
<T
>> for P
<[T
]> {
176 fn into(self) -> Vec
<T
> {
181 impl<T
> FromIterator
<T
> for P
<[T
]> {
182 fn from_iter
<I
: IntoIterator
<Item
=T
>>(iter
: I
) -> P
<[T
]> {
183 P
::from_vec(iter
.into_iter().collect())
187 impl<T
> IntoIterator
for P
<[T
]> {
189 type IntoIter
= vec
::IntoIter
<T
>;
191 fn into_iter(self) -> Self::IntoIter
{
192 self.into_vec().into_iter()
196 impl<'a
, T
> IntoIterator
for &'a P
<[T
]> {
198 type IntoIter
= slice
::Iter
<'a
, T
>;
199 fn into_iter(self) -> Self::IntoIter
{
204 impl<T
: Encodable
> Encodable
for P
<[T
]> {
205 fn encode
<S
: Encoder
>(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
206 Encodable
::encode(&**self, s
)
210 impl<T
: Decodable
> Decodable
for P
<[T
]> {
211 fn decode
<D
: Decoder
>(d
: &mut D
) -> Result
<P
<[T
]>, D
::Error
> {
212 Ok(P
::from_vec(match Decodable
::decode(d
) {
214 Err(e
) => return Err(e
)