|
| 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. |
| 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::fmt; |
| 12 | +use std::fmt::Show; |
| 13 | +use std::hash::Hash; |
| 14 | +use serialize::{Encodable, Decodable, Encoder, Decoder}; |
| 15 | + |
| 16 | +/// An owned smart pointer. |
| 17 | +pub struct P<T> { |
| 18 | + ptr: Box<T> |
| 19 | +} |
| 20 | + |
| 21 | +#[allow(non_snake_case)] |
| 22 | +/// Construct a P<T> from a T value. |
| 23 | +pub fn P<T: 'static>(value: T) -> P<T> { |
| 24 | + P { |
| 25 | + ptr: box value |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +impl<T: 'static> P<T> { |
| 30 | + pub fn and_then<U>(self, f: |T| -> U) -> U { |
| 31 | + f(*self.ptr) |
| 32 | + } |
| 33 | + |
| 34 | + pub fn map(self, f: |T| -> T) -> P<T> { |
| 35 | + self.and_then(|x| P(f(x))) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +impl<T> Deref<T> for P<T> { |
| 40 | + fn deref<'a>(&'a self) -> &'a T { |
| 41 | + &*self.ptr |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +impl<T: 'static + Clone> Clone for P<T> { |
| 46 | + fn clone(&self) -> P<T> { |
| 47 | + P((**self).clone()) |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl<T: PartialEq> PartialEq for P<T> { |
| 52 | + fn eq(&self, other: &P<T>) -> bool { |
| 53 | + **self == **other |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +impl<T: Eq> Eq for P<T> {} |
| 58 | + |
| 59 | +impl<T: Show> Show for P<T> { |
| 60 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 61 | + (**self).fmt(f) |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +impl<S, T: Hash<S>> Hash<S> for P<T> { |
| 66 | + fn hash(&self, state: &mut S) { |
| 67 | + (**self).hash(state); |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +impl<E, D: Decoder<E>, T: 'static + Decodable<D, E>> Decodable<D, E> for P<T> { |
| 72 | + fn decode(d: &mut D) -> Result<P<T>, E> { |
| 73 | + Decodable::decode(d).map(P) |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +impl<E, S: Encoder<E>, T: Encodable<S, E>> Encodable<S, E> for P<T> { |
| 78 | + fn encode(&self, s: &mut S) -> Result<(), E> { |
| 79 | + (**self).encode(s) |
| 80 | + } |
| 81 | +} |
0 commit comments