Skip to content

Instantly share code, notes, and snippets.

@kmcallister
Created March 8, 2014 00:36
Show Gist options
  • Select an option

  • Save kmcallister/9423251 to your computer and use it in GitHub Desktop.

Select an option

Save kmcallister/9423251 to your computer and use it in GitHub Desktop.
phantom types for fake mut polymorphism
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

Copy link
Copy Markdown
Author
<sfackler> kmc: that implementation is unsound; the lifetime parameter isn't used so it'll be ignored
<sfackler> kmc: you just need to add a marker type like http://static.rust-lang.org/doc/master/std/kinds/marker/struct.ContravariantLifetime.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment