Skip to content

Commit

Permalink
Merge pull request #61 from CosmWasm/get-or-default
Browse files Browse the repository at this point in the history
Implement {ItemAccess, ColumnAccess}::get_or
  • Loading branch information
uint authored Sep 11, 2024
2 parents b838ce5 + 5fb286d commit fc6c065
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
22 changes: 22 additions & 0 deletions packages/storey/src/containers/column.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<u64, TestEncoding>::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<T, E::DecodeError> {
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.
///
Expand Down
19 changes: 19 additions & 0 deletions packages/storey/src/containers/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,25 @@ where
pub fn try_get(&self) -> Result<T, TryGetError<E::DecodeError>> {
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::<u64, TestEncoding>::new(0);
///
/// assert_eq!(item.access(&storage).get_or(42).unwrap(), 42);
/// ```
pub fn get_or(&self, default: T) -> Result<T, E::DecodeError> {
self.get().map(|opt| opt.unwrap_or(default))
}
}

impl<E, T, S> ItemAccess<E, T, S>
Expand Down

0 comments on commit fc6c065

Please sign in to comment.