Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement {ItemAccess, ColumnAccess}::get_or #61

Merged
merged 1 commit into from
Sep 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading