From 7c0acc3ecfe476bb66681200ee021cb32a04ca43 Mon Sep 17 00:00:00 2001 From: 409 <409dev@protonmail.com> Date: Tue, 17 Jun 2025 21:21:16 +0200 Subject: [PATCH] refactor `set` command --- src/commands/set.rs | 23 +++++++++-------------- src/database.rs | 15 +++++++-------- 2 files changed, 16 insertions(+), 22 deletions(-) diff --git a/src/commands/set.rs b/src/commands/set.rs index 33db36b..88ac7a3 100644 --- a/src/commands/set.rs +++ b/src/commands/set.rs @@ -1,24 +1,18 @@ -use std::{io::Cursor, time::Duration}; +use std::io::Cursor; +use crate::{Result, connection::Connection, database::Database, errors::AppError}; use bytes::{Buf as _, Bytes}; -use tokio::time::Instant; - -use crate::{ - Result, - connection::Connection, - database::{Database, Value}, - errors::AppError, -}; #[derive(Debug, Clone)] pub struct Set { key: String, - value: Value, + data: Box<[u8]>, + expiration: Option, } impl Set { pub async fn execute(self, db: &Database, connection: &mut Connection) -> Result<()> { - db.set(self.key, self.value).await?; + db.set(self.key, self.data, self.expiration).await?; connection.write(Bytes::from_static(&[1])).await?; @@ -42,15 +36,16 @@ impl Set { let data = bytes.copy_to_bytes(value_length); - let expiration: Option = match bytes.try_get_u8()? { - 1 => Some(Instant::now() + Duration::from_secs(bytes.try_get_u64()?)), + let expiration: Option = match bytes.try_get_u8()? { + 1 => Some(bytes.try_get_u64()?), 0 => None, _ => return Err(AppError::UnexpectedCommandData), }; Ok(Self { key, - value: Value::new(data, expiration), + data: (*data).into(), + expiration, }) } } diff --git a/src/database.rs b/src/database.rs index 7b0d5e8..ae5bca0 100644 --- a/src/database.rs +++ b/src/database.rs @@ -4,7 +4,7 @@ use std::{ time::Duration, }; -use bytes::{BufMut, Bytes, BytesMut}; +use bytes::{BufMut, BytesMut}; use byteyarn::Yarn; use tokio::{ sync::{Mutex, Notify}, @@ -33,11 +33,8 @@ pub struct Value { } impl Value { - pub fn new(data: Bytes, expiration: Option) -> Self { - Self { - data: data.into_iter().collect(), - expiration, - } + pub fn new(data: Box<[u8]>, expiration: Option) -> Self { + Self { data, expiration } } pub fn from_string(data: String, expiration: Option) -> Self { @@ -69,13 +66,15 @@ impl Database { state.entries.get(key).map(|v| v.data.clone()) } - pub async fn set(&self, key: String, value: Value) -> Result<()> { + pub async fn set(&self, key: String, data: Box<[u8]>, expiration: Option) -> Result<()> { let mut state = self.state.lock().await; - let expiration = value.expiration.clone(); + let expiration = expiration.map(|seconds| Instant::now() + Duration::from_secs(seconds)); let key = Yarn::from(key.clone()); + let value = Value::new(data, expiration); + let previous = state.entries.insert(key.clone(), value); let mut notify = false;