From 9569142dfab73ae166c356275c87d99aa09d19e6 Mon Sep 17 00:00:00 2001 From: Brad Clawsie Date: Fri, 13 Nov 2026 16:12:04 -0600 Subject: feat: learn_5 commit 41de86cc8ccb66760c49f272d9e81d5efcbafb09 Author: Brad Clawsie Date: Fri Nov 13 16:11:51 2026 -0600 feat: learn_5 --- learn_5/src/main.rs | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 learn_5/src/main.rs (limited to 'learn_5/src/main.rs') diff --git a/learn_5/src/main.rs b/learn_5/src/main.rs new file mode 100644 index 0000000..d774553 --- /dev/null +++ b/learn_5/src/main.rs @@ -0,0 +1,81 @@ +struct Slot { + value: Option, +} + +impl Slot { + pub fn new() -> Self { + Self { + value: None, + } + } + + pub fn insert(&mut self, value: T) -> Option { + let current_value = self.value.take(); + self.value = Some(value); + current_value + } + + pub fn get(&self) -> Option<&T> { + self.value.as_ref() + } + + pub fn take(&mut self) -> Option { + self.value.take() + } + + pub fn is_empty(&self) -> bool { + self.value.is_none() + } +} + +fn main() { + () +} + +#[cfg(test)] +mod tests { + use crate::*; + + #[test] + fn test_new() { + assert!(Slot::::new().value.is_none()); + } + + struct Record { + id: u32, + } + + #[test] + fn test_insert() { + let mut slot = Slot::::new(); + let prev0 = slot.insert(Record{id:1}); + assert!(prev0.is_none()); + let prev1 = slot.insert(Record{id:2}); + assert!(prev1.is_some_and(|x| x.id == 1)) + } + + #[test] + fn test_get() { + let mut slot = Slot::::new(); + assert!(slot.get().is_none()); + let prev0 = slot.insert(Record{id:1}); + assert!(slot.get().is_some_and(|x| x.id == 1)) + } + + #[test] + fn test_take() { + let mut slot = Slot::::new(); + assert!(slot.take().is_none()); + let _ = slot.insert(Record{id:1}); + assert!(slot.take().is_some_and(|x| x.id == 1)); + assert!(slot.get().is_none()); + } + + #[test] + fn test_is_empty() { + let mut slot = Slot::::new(); + assert!(slot.is_empty()); + let _ = slot.insert(Record{id:1}); + assert!(!slot.is_empty()); + } +} -- cgit v1.2.3