Skip to content

Commit

Permalink
Add default impl for store set_partial_values
Browse files Browse the repository at this point in the history
WritableStorageTraits now needs ReadableStorageTraits.
  • Loading branch information
LDeakin committed Oct 17, 2023
1 parent cdf2a20 commit 6e69a4d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added `ReadableListableStorage`, `ReadableListableStorageTraits`, `StorageTransformerExtension::create_readable_listable_transformer`
- Added `ByteRange::to_range()` and `to_range_usize()`
- Added `StoreKeyStartValue::end()`
- Added default implementation for `WritableStorageTraits::set_partial_values`
- `WritableStorageTraits` now requires `ReadableStorageTraits`

### Changed
- **Breaking**: `array::data_type::DataType` is now marked `#[non_exhaustive]`
Expand Down
28 changes: 26 additions & 2 deletions src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub mod store;

use std::{path::PathBuf, sync::Arc};

use itertools::Itertools;
use thiserror::Error;

use crate::{
Expand Down Expand Up @@ -184,7 +185,7 @@ pub trait ListableStorageTraits: Send + Sync {
}

/// Writable storage traits.
pub trait WritableStorageTraits: Send + Sync {
pub trait WritableStorageTraits: Send + Sync + ReadableStorageTraits {
/// Store bytes at a [`StoreKey`].
///
/// # Errors
Expand All @@ -200,7 +201,30 @@ pub trait WritableStorageTraits: Send + Sync {
fn set_partial_values(
&self,
key_start_values: &[StoreKeyStartValue],
) -> Result<(), StorageError>;
) -> Result<(), StorageError> {
// Group by store key
for (key, group) in &key_start_values
.iter()
.group_by(|key_start_value| &key_start_value.key)
{
// Read the store key
let mut bytes = self.get(key)?.unwrap_or_default();

// Update the store key
for key_start_value in group {
let start: usize = key_start_value.start.try_into().unwrap();
let end: usize = key_start_value.end().try_into().unwrap();
if bytes.len() < end {
bytes.resize(end, 0);
}
bytes[start..end].copy_from_slice(key_start_value.value);
}

// Write the store key
self.set(key, &bytes)?;
}
Ok(())
}

/// Erase a [`StoreKey`].
///
Expand Down

0 comments on commit 6e69a4d

Please sign in to comment.