From b9aa396d8cb53c20a9e54c99b8cb856a17fea638 Mon Sep 17 00:00:00 2001 From: Brad Clawsie Date: Sun, 22 Nov 2026 15:23:41 -0600 Subject: feat: learn_18 commit 05688db16c5652d2c35480b749f08e2a56850d0e Author: Brad Clawsie Date: Sun Nov 22 15:23:23 2026 -0600 feat: learn_18 --- learn_18/src/main.rs | 87 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 learn_18/src/main.rs (limited to 'learn_18/src') diff --git a/learn_18/src/main.rs b/learn_18/src/main.rs new file mode 100644 index 0000000..2fdab98 --- /dev/null +++ b/learn_18/src/main.rs @@ -0,0 +1,87 @@ +use std::borrow::Borrow; +use std::collections::HashMap; + +#[derive(Debug, PartialEq, Eq, Hash)] +struct Username(String); + +impl Username { + fn new(name: String) -> Self { + Self(name) + } +} + +impl Borrow for Username { + fn borrow(&self) -> &str { + &self.0 + } +} + +struct UserRegistry { + users: HashMap, +} + +impl UserRegistry { + fn new() -> Self { + Self { + users: HashMap::new(), + } + } + + fn insert(&mut self, username: Username, id: u64) -> Option { + self.users.insert(username, id) + } + + fn get(&self, username: &str) -> Option { + self.users.get(username).copied() + } + + fn remove(&mut self, username: &str) -> Option { + self.users.remove(username) + } + + fn len(&self) -> usize { + self.users.len() + } +} + +fn main() { + () +} + +#[cfg(test)] +mod tests { + use crate::*; + + #[test] + fn test_username_new() { + let un = Username::new("Joe".to_string()); + assert_eq!(un.0, "Joe".to_string()); + } + + #[test] + fn test_userregistry_new() { + let ur = UserRegistry::new(); + assert!(ur.users.is_empty()); + } + + #[test] + fn test_userregistry_ops() { + let mut ur = UserRegistry::new(); + assert!(ur.users.is_empty()); + + assert!(&ur.insert(Username::new("Joe".to_string()),1).is_none()); + assert!(&ur.insert(Username::new("Joe".to_string()),2).is_some_and(|x| x == 1)); + assert!(&ur.get("Joe").is_some_and(|x| x == 2)); + assert!(&ur.get("Jim").is_none()); + assert!(&ur.insert(Username::new("Jim".to_string()),3).is_none()); + assert_eq!(ur.len(), 2 as usize); + assert!(&ur.remove("Joe").is_some_and(|x| x == 2)); + assert_eq!(ur.len(), 1 as usize); + assert!(&ur.remove("Jay").is_none()); + assert_eq!(ur.len(), 1 as usize); + assert!(&ur.insert(Username::new("Joe".to_string()),2).is_none()); + assert_eq!(ur.len(), 2 as usize); + assert!(&ur.get("Joe".to_string().as_str()).is_some_and(|x| x == 2)); + + } +} -- cgit v1.2.3