Skip to content

Commit

Permalink
[storage] Add StorageHashMapKeyValue struct #198 (#199)
Browse files Browse the repository at this point in the history
* Update storage.rs

* Create storage_hash_map_key_value.rs

* Update storage_hash_map_key_value.rs

* Update pr.yaml
  • Loading branch information
michaelvlach authored Sep 18, 2022
1 parent a9cc7c6 commit 929c664
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
2 changes: 1 addition & 1 deletion .github/workflows/pr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ jobs:
- uses: actions/checkout@v3
- uses: taiki-e/install-action@cargo-llvm-cov
- run: rustup component add llvm-tools-preview
- run: cargo llvm-cov --fail-uncovered-regions 103 --fail-uncovered-functions 0 --fail-uncovered-lines 0
- run: cargo llvm-cov --fail-uncovered-regions 105 --fail-uncovered-functions 0 --fail-uncovered-lines 0

test:
runs-on: ubuntu-latest
Expand Down
1 change: 1 addition & 0 deletions src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ mod file_storage;
mod serialize;
mod stable_hash;
mod storage_hash_map;
mod storage_hash_map_key_value;
mod storage_impl;
mod storage_record;
mod storage_record_with_index;
Expand Down
57 changes: 57 additions & 0 deletions src/storage/storage_hash_map_key_value.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use super::serialize::Serialize;

#[derive(Debug, Default, PartialEq)]
pub(crate) struct StorageHashMapKeyValue<K: Serialize, T: Serialize> {
key: K,
value: T,
}

impl<K: Serialize, T: Serialize> Serialize for StorageHashMapKeyValue<K, T> {
fn deserialize(bytes: &[u8]) -> Result<Self, crate::DbError> {
Ok(Self {
key: K::deserialize(&bytes[0..])?,
value: T::deserialize(&bytes[std::mem::size_of::<K>()..])?,
})
}

fn serialize(&self) -> Vec<u8> {
let mut data = Vec::<u8>::new();
data.reserve(std::mem::size_of::<K>() + std::mem::size_of::<T>());
data.append(&mut self.key.serialize());
data.append(&mut self.value.serialize());

data
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn derived_from_debug() {
let key_value = StorageHashMapKeyValue::<i64, i64>::default();

format!("{:?}", key_value);
}

#[test]
fn derived_from_default() {
let key_value = StorageHashMapKeyValue::<i64, i64>::default();

assert_eq!(key_value.key, 0);
assert_eq!(key_value.value, 0);
}

#[test]
fn i64_i64() {
let key_value = StorageHashMapKeyValue {
key: 1_i64,
value: 10_i64,
};
let bytes = key_value.serialize();
let other = StorageHashMapKeyValue::deserialize(&bytes);

assert_eq!(other, Ok(key_value));
}
}

0 comments on commit 929c664

Please sign in to comment.