-
-
Save ratmice/39e062b13aa221fb87f4178f3b8658c5 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
This file contains 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
#![allow(dead_code)] | |
mod sealer_unsealer { | |
use std::rc::Rc; | |
use std::ptr; | |
pub struct Sealed<T> { | |
value: T, | |
brand: Rc<Brand> | |
} | |
pub struct SealerUnsealerPair { | |
brand: Rc<Brand> | |
} | |
struct Brand; | |
impl SealerUnsealerPair { | |
pub fn new() -> SealerUnsealerPair { | |
// Generate a fresh key. | |
SealerUnsealerPair { brand: Rc::new(Brand) } | |
} | |
pub fn seal<T>(&self, value: T) -> Sealed<T> { | |
Sealed { value, brand: self.brand.clone() } | |
} | |
pub fn unseal<T>(&self, sealed: Sealed<T>) -> Option<T> { | |
match ptr::eq(&*self.brand, &*sealed.brand) { | |
true => Some(sealed.value), | |
false => None, | |
} | |
} | |
} | |
} | |
#[test] | |
fn test() { | |
use sealer_unsealer::SealerUnsealerPair; | |
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