refactor commands
This commit is contained in:
49
src/commands/set.rs
Normal file
49
src/commands/set.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use std::io::Cursor;
|
||||
|
||||
use bytes::{Buf as _, Bytes};
|
||||
|
||||
use crate::{
|
||||
Result,
|
||||
connection::Connection,
|
||||
database::{Database, Value},
|
||||
errors::AppError,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Set {
|
||||
key: String,
|
||||
value: Value,
|
||||
}
|
||||
|
||||
impl Set {
|
||||
pub async fn execute(self, db: &Database, connection: &mut Connection) -> Result<()> {
|
||||
db.set(self.key, self.value).await?;
|
||||
|
||||
connection.write(Bytes::from_static(&[1])).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn parse(bytes: &mut Cursor<&[u8]>) -> Result<Self> {
|
||||
let key_length = bytes.try_get_u16()? as usize;
|
||||
|
||||
if bytes.remaining() < key_length {
|
||||
return Err(AppError::IncompleteCommandBuffer);
|
||||
}
|
||||
|
||||
let key = String::from_utf8(bytes.copy_to_bytes(key_length).to_vec())?;
|
||||
|
||||
let value_length = bytes.try_get_u32()? as usize;
|
||||
|
||||
if bytes.remaining() < value_length {
|
||||
return Err(AppError::IncompleteCommandBuffer);
|
||||
}
|
||||
|
||||
let data = bytes.copy_to_bytes(value_length);
|
||||
|
||||
Ok(Self {
|
||||
key,
|
||||
value: Value::new(data),
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user