Skip to content

Commit

Permalink
feat: add KV Storage
Browse files Browse the repository at this point in the history
  • Loading branch information
shekohex committed Oct 30, 2024
1 parent e1751e3 commit 0f4eaa8
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 0 deletions.
84 changes: 84 additions & 0 deletions src/kv/mem.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
use std::collections::HashMap;

/// In-memory key-value store.
#[derive(Debug, Clone)]
pub struct MemKVStore<K, V> {
store: HashMap<K, V>,
}

impl<K, V> MemKVStore<K, V>
where
K: Eq + std::hash::Hash,
{
/// Create a new `MemKVStore`.
pub fn new() -> Self {
MemKVStore {
store: HashMap::new(),
}
}

/// Insert a key-value pair into the store.
pub fn insert(&mut self, key: K, value: V) {
self.store.insert(key, value);
}

/// Get the value associated with a key.
pub fn get(&self, key: &K) -> Option<&V> {
self.store.get(key)
}

/// Remove a key-value pair from the store.
pub fn remove(&mut self, key: &K) -> Option<V> {
self.store.remove(key)
}

/// Check if the store contains a key.
pub fn contains_key(&self, key: &K) -> bool {
self.store.contains_key(key)
}

/// Get the number of key-value pairs in the store.
pub fn len(&self) -> usize {
self.store.len()
}

/// Check if the store is empty.
pub fn is_empty(&self) -> bool {
self.store.is_empty()
}
}

impl<K, V> Default for MemKVStore<K, V>
where
K: Eq + std::hash::Hash,
{
fn default() -> Self {
MemKVStore::new()
}
}

impl<K, V> super::KVStore for MemKVStore<K, V>
where
K: Eq + std::hash::Hash + Clone + AsRef<[u8]>,
V: Clone + AsRef<[u8]>,
{
type Key = K;

type Value = V;

fn get(&self, key: &Self::Key) -> Option<&Self::Value> {
MemKVStore::get(self, key)
}

fn set(&mut self, key: Self::Key, value: Self::Value) {
self.insert(key, value);
}

fn del(&mut self, key: &Self::Key) {
self.remove(key);
}

fn ex(&self, key: &Self::Key) -> bool {
self.contains_key(key)
}
}
16 changes: 16 additions & 0 deletions src/kv/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/// In-memory storage for the key-value store.
mod mem;

pub trait KVStore {
type Key: AsRef<[u8]>;
type Value: AsRef<[u8]>;

/// Get the value of a key.
fn get(&self, key: &Self::Key) -> Option<&Self::Value>;
/// Set the value of a key.
fn set(&mut self, key: Self::Key, value: Self::Value);
/// Remove a key, if it exists.
fn del(&mut self, key: &Self::Key);
/// Check if the key exists in the store.
fn ex(&self, key: &Self::Key) -> bool;
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use sdk::ctx::{KeystoreContext, ServicesContext, TangleClientContext};

/// FROST Keygen module
pub mod keygen;
/// Key-Value Storage module
mod kv;
/// FROST Signing module
pub mod sign;

Expand Down

0 comments on commit 0f4eaa8

Please sign in to comment.