Last active
February 23, 2023 21:51
-
-
Save MadFaill/2e06f74bcd6cf2a4243004391f3ee362 to your computer and use it in GitHub Desktop.
An example of using state in Rust
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(unused)] | |
use std::collections::HashMap; | |
struct Locked; | |
struct Unlocked; | |
// PasswordManager<Locked> != PasswordManager<Unlocked> | |
struct PasswordManager<State = Locked> { | |
master_pass: String, | |
passwords: HashMap<String, String>, | |
state: std::marker::PhantomData<State>, | |
} | |
impl PasswordManager<Locked> { | |
pub fn unlock(self, master_pass: String) -> PasswordManager<Unlocked> { | |
PasswordManager { | |
master_pass: self.master_pass, | |
passwords: self.passwords, | |
state: std::marker::PhantomData::<Unlocked>, | |
} | |
} | |
} | |
impl PasswordManager<Unlocked> { | |
pub fn lock(self) -> PasswordManager<Locked> { | |
PasswordManager { | |
master_pass: self.master_pass, | |
passwords: self.passwords, | |
state: std::marker::PhantomData::<Locked>, | |
} | |
} | |
pub fn list_passwords(&self) -> &HashMap<String, String> { | |
&self.passwords | |
} | |
pub fn add_password(&mut self, username: String, password: String) { | |
self.passwords.insert(username, password); | |
} | |
} | |
impl<State> PasswordManager<State> { | |
pub fn encryption(&self) -> String { | |
todo!() | |
} | |
pub fn version(&self) -> String { | |
todo!() | |
} | |
} | |
impl PasswordManager { | |
pub fn new(master_pass: String) -> Self { | |
PasswordManager { | |
master_pass, | |
passwords: Default::default(), | |
state: Default::default(), | |
} | |
} | |
} | |
fn main() { | |
let mut manager = PasswordManager::new("password123".to_owned()); | |
let manager = manager.unlock("password123".to_owned()); | |
manager.list_passwords(); | |
manager.lock(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment