Skip to content

Commit

Permalink
syntax: add a custom owned smart pointer in ptr::P.
Browse files Browse the repository at this point in the history
  • Loading branch information
eddyb committed Sep 14, 2014
1 parent 79a5448 commit 1872c4c
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 10 deletions.
10 changes: 0 additions & 10 deletions src/libsyntax/ast.rs
Expand Up @@ -25,16 +25,6 @@ use std::rc::Rc;
use std::gc::{Gc, GC};
use serialize::{Encodable, Decodable, Encoder, Decoder};

/// A pointer abstraction.
// FIXME(eddyb) #10676 use Rc<T> in the future.
pub type P<T> = Gc<T>;

#[allow(non_snake_case)]
/// Construct a P<T> from a T value.
pub fn P<T: 'static>(value: T) -> P<T> {
box(GC) value
}

// FIXME #6993: in librustc, uses of "ident" should be replaced
// by just "Name".

Expand Down
1 change: 1 addition & 0 deletions src/libsyntax/lib.rs
Expand Up @@ -63,6 +63,7 @@ pub mod diagnostic;
pub mod fold;
pub mod owned_slice;
pub mod parse;
pub mod ptr;
pub mod visit;

pub mod print {
Expand Down
81 changes: 81 additions & 0 deletions src/libsyntax/ptr.rs
@@ -0,0 +1,81 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::fmt;
use std::fmt::Show;
use std::hash::Hash;
use serialize::{Encodable, Decodable, Encoder, Decoder};

/// An owned smart pointer.
pub struct P<T> {
ptr: Box<T>
}

#[allow(non_snake_case)]
/// Construct a P<T> from a T value.
pub fn P<T: 'static>(value: T) -> P<T> {
P {
ptr: box value
}
}

impl<T: 'static> P<T> {
pub fn and_then<U>(self, f: |T| -> U) -> U {
f(*self.ptr)
}

pub fn map(self, f: |T| -> T) -> P<T> {
self.and_then(|x| P(f(x)))
}
}

impl<T> Deref<T> for P<T> {
fn deref<'a>(&'a self) -> &'a T {
&*self.ptr
}
}

impl<T: 'static + Clone> Clone for P<T> {
fn clone(&self) -> P<T> {
P((**self).clone())
}
}

impl<T: PartialEq> PartialEq for P<T> {
fn eq(&self, other: &P<T>) -> bool {
**self == **other
}
}

impl<T: Eq> Eq for P<T> {}

impl<T: Show> Show for P<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
}
}

impl<S, T: Hash<S>> Hash<S> for P<T> {
fn hash(&self, state: &mut S) {
(**self).hash(state);
}
}

impl<E, D: Decoder<E>, T: 'static + Decodable<D, E>> Decodable<D, E> for P<T> {
fn decode(d: &mut D) -> Result<P<T>, E> {
Decodable::decode(d).map(P)
}
}

impl<E, S: Encoder<E>, T: Encodable<S, E>> Encodable<S, E> for P<T> {
fn encode(&self, s: &mut S) -> Result<(), E> {
(**self).encode(s)
}
}

0 comments on commit 1872c4c

Please sign in to comment.