Created
March 8, 2014 00:36
-
-
Save kmcallister/9423251 to your computer and use it in GitHub Desktop.
phantom types for fake mut polymorphism
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::cast; | |
| use std::unstable::raw; | |
| struct Mutable; | |
| struct Immutable; | |
| struct Foobar<'t, Mutability> { | |
| /* priv */ ptr: raw::Slice<u8> | |
| } | |
| impl<'t, M> Foobar<'t, M> { | |
| /* priv */ fn get_immut(&self) -> &'t [u8] { | |
| unsafe { cast::transmute(self.ptr) } | |
| } | |
| pub fn get_first(&self) -> u8 { | |
| self.get_immut()[0] | |
| } | |
| } | |
| impl<'t> Foobar<'t, Immutable> { | |
| pub fn new_immut(vec: &'t [u8]) -> Foobar<'t, Immutable> { | |
| Foobar { ptr: unsafe { cast::transmute(vec) } } | |
| } | |
| } | |
| impl<'t> Foobar<'t, Mutable> { | |
| /* priv */ fn get_mut(&self) -> &'t mut [u8] { | |
| unsafe { cast::transmute(self.ptr) } | |
| } | |
| pub fn new_mut(vec: &'t mut [u8]) -> Foobar<'t, Mutable> { | |
| Foobar { ptr: unsafe { cast::transmute(vec) } } | |
| } | |
| pub fn set_first(&self, x: u8) { | |
| self.get_mut()[0] = x; | |
| } | |
| } |
kmcallister
commented
Mar 8, 2014
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment