Skip to content

Commit

Permalink
Sarthak | Adds KeyValue
Browse files Browse the repository at this point in the history
  • Loading branch information
SarthakMakhija committed Jul 14, 2024
1 parent 94c11f3 commit 147dc4c
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 0 deletions.
9 changes: 9 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
bytes = "1.6.1"
63 changes: 63 additions & 0 deletions src/key_value.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
use std::io::{Error, Read};
use std::mem;

use bytes::{Buf, BufMut, BytesMut};

const U16_SIZE: usize = mem::size_of::<u16>();

pub(crate) struct KeyValue {
key: Vec<u8>,
value: Vec<u8>,
}

impl KeyValue {
pub fn new(key: Vec<u8>, value: Vec<u8>) -> KeyValue {
assert!(key.len() > 0);
assert!(value.len() > 0);
KeyValue {key, value}
}

pub(crate) fn encode(&self) -> BytesMut {
let mut buffer = BytesMut::new();
buffer.put_u16_le(self.key.len() as u16);
buffer.put_u16_le(self.value.len() as u16);
buffer.put_slice(&self.key);
buffer.put_slice(&self.value);
return buffer
}

pub(crate) fn decode_from(mut buffer: BytesMut) -> Result<KeyValue, Error> {
let key_length = buffer.get_u16_le();
let value_length = buffer.get_u16_le();

let mut buffer_reader = buffer.reader();

let mut key = Vec::with_capacity(key_length as usize);
key.resize(key_length as usize, 0);
buffer_reader.read_exact(&mut key)?;

let mut value = Vec::with_capacity(value_length as usize);
value.resize(value_length as usize, 0);
buffer_reader.read_exact(&mut value)?;

println!("Key {:?}", key);
println!("Value {:?}", value);

return Ok(KeyValue::new(key, value))
}
}

#[cfg(test)]
mod tests {
use crate::key_value::KeyValue;

#[test]
fn encodes_and_decodes_key_value() {
let key_value = KeyValue::new(Vec::from(b"raft"), Vec::from(b"consensus"));
let encoded = key_value.encode();

let decoded = KeyValue::decode_from(encoded).expect("Failed to decode the key_value");
assert_eq!(b"raft", &decoded.key[..]);
assert_eq!(b"consensus", &decoded.value[..]);
}
}
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
mod memory;
pub mod key_value;

fn main() {
println!("Hello, world!");
Expand Down

0 comments on commit 147dc4c

Please sign in to comment.