Skip to content

Instantly share code, notes, and snippets.

Created September 8, 2017 15:39
Show Gist options
  • Save anonymous/f9f4cba8248ca4a7045772f11313efb3 to your computer and use it in GitHub Desktop.
Save anonymous/f9f4cba8248ca4a7045772f11313efb3 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
use std::ptr;
use std::marker::PhantomData;
struct Sealed<T> {
brand: *const *const i32,
value: T,
}
struct SealerUnsealerPair<T> {
brand: *const i32,
phantom: PhantomData<T>,
}
impl<T> SealerUnsealerPair<T> {
pub fn seal(&self, value: T) -> Sealed<T> {
Sealed {
brand: &self.brand,
value: value,
}
}
pub fn unseal(&self, it: Sealed<T>) -> Option<T> {
if ptr::eq(&self.brand, it.brand) {
Some(it.value)
} else {
None
}
}
pub fn new() -> SealerUnsealerPair<T> {
SealerUnsealerPair {
brand: ptr::null(),
phantom: PhantomData,
}
}
}
fn main() {
let sealer1 = SealerUnsealerPair::new();
let sealer2 = SealerUnsealerPair::new();
let sealed1 = sealer1.seal("foo");
let sealed2 = sealer2.seal("bar");
let sealed1_2 = sealer1.seal("abc");
let sealed2_2 = sealer2.seal("xyz");
assert!(sealer1.unseal(sealed1).is_some());
assert!(sealer1.unseal(sealed2).is_none());
assert!(sealer2.unseal(sealed2_2).is_some());
assert!(sealer2.unseal(sealed1_2).is_none());
()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment