use std::fmt::{self, Show};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::ptr;
use serialize::{Encodable, Decodable, Encoder, Decoder};
pub struct P<T> {
ptr: Box<T>
}
#[allow(non_snake_case)]
pub fn P<T: 'static>(value: T) -> P<T> {
P {
ptr: box value
}
}
impl<T: 'static> P<T> {
pub fn and_then<U, F>(self, f: F) -> U where
F: FnOnce(T) -> U,
{
f(*self.ptr)
}
pub fn map<F>(mut self, f: F) -> P<T> where
F: FnOnce(T) -> T,
{
unsafe {
let p = &mut *self.ptr;
ptr::write(p, f(ptr::read_and_zero(p)));
}
self
}
}
impl<T> Deref for P<T> {
type Target = 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: Hasher, T: Hash<S>> Hash<S> for P<T> {
fn hash(&self, state: &mut S) {
(**self).hash(state);
}
}
impl<T: 'static + Decodable> Decodable for P<T> {
fn decode<D: Decoder>(d: &mut D) -> Result<P<T>, D::Error> {
Decodable::decode(d).map(P)
}
}
impl<T: Encodable> Encodable for P<T> {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
(**self).encode(s)
}
}