From 5fb286da2261b4af0cb18fa1d9cf1428e7f7ea6a Mon Sep 17 00:00:00 2001 From: Tomasz Kurcz Date: Wed, 11 Sep 2024 13:50:25 +0200 Subject: [PATCH] feat: implement {ItemAccess, ColumnAccess}::get_or --- packages/storey/src/containers/column.rs | 22 ++++++++++++++++++++++ packages/storey/src/containers/item.rs | 19 +++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/packages/storey/src/containers/column.rs b/packages/storey/src/containers/column.rs index 0ed7f1b..91e8eb7 100644 --- a/packages/storey/src/containers/column.rs +++ b/packages/storey/src/containers/column.rs @@ -209,6 +209,28 @@ where self.get(key)?.ok_or(TryGetError::Empty) } + /// Get the value associated with the given key or a provided default. + /// + /// Returns the provided default value if the entry doesn't exist (has not been set yet). + /// + /// # Example + /// ``` + /// # use mocks::encoding::TestEncoding; + /// # use mocks::backend::TestStorage; + /// use storey::containers::Column; + /// + /// let mut storage = TestStorage::new(); + /// let column = Column::::new(0); + /// let mut access = column.access(&mut storage); + /// + /// assert_eq!(access.get_or(0, 42).unwrap(), 42); + /// access.push(&1337).unwrap(); + /// assert_eq!(access.get_or(0, 42).unwrap(), 1337); + /// ``` + pub fn get_or(&self, key: u32, default: T) -> Result { + self.get(key).map(|value| value.unwrap_or(default)) + } + /// Get the length of the column. This is the number of elements actually stored, /// taking the possibility of removed elements into account. /// diff --git a/packages/storey/src/containers/item.rs b/packages/storey/src/containers/item.rs index 4593753..4180d06 100644 --- a/packages/storey/src/containers/item.rs +++ b/packages/storey/src/containers/item.rs @@ -187,6 +187,25 @@ where pub fn try_get(&self) -> Result> { self.get()?.ok_or_else(|| TryGetError::Empty) } + + /// Get the value of the item or a provided default. + /// + /// Returns the value of the item if it exists, otherwise returns the provided default. + /// + /// # Example + /// ``` + /// # use mocks::encoding::TestEncoding; + /// # use mocks::backend::TestStorage; + /// use storey::containers::Item; + /// + /// let storage = TestStorage::new(); + /// let item = Item::::new(0); + /// + /// assert_eq!(item.access(&storage).get_or(42).unwrap(), 42); + /// ``` + pub fn get_or(&self, default: T) -> Result { + self.get().map(|opt| opt.unwrap_or(default)) + } } impl ItemAccess