ttl command
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
pub mod delete;
|
||||
mod delete;
|
||||
mod get;
|
||||
pub mod has;
|
||||
pub mod set;
|
||||
mod has;
|
||||
mod set;
|
||||
mod ttl;
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
@@ -10,6 +11,7 @@ use delete::Delete;
|
||||
use get::Get;
|
||||
use has::Has;
|
||||
use set::Set;
|
||||
use ttl::Ttl;
|
||||
|
||||
use crate::{Result, connection::Connection, database::Database, errors::AppError};
|
||||
|
||||
@@ -19,6 +21,7 @@ pub enum Command {
|
||||
Set(Set),
|
||||
Delete(Delete),
|
||||
Has(Has),
|
||||
Ttl(Ttl),
|
||||
}
|
||||
|
||||
impl Command {
|
||||
@@ -28,6 +31,7 @@ impl Command {
|
||||
Command::Set(set) => set.execute(db, connection).await,
|
||||
Command::Delete(delete) => delete.execute(db, connection).await,
|
||||
Command::Has(has) => has.execute(db, connection).await,
|
||||
Command::Ttl(ttl) => ttl.execute(db, connection).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +55,7 @@ impl Command {
|
||||
"set" => Self::Set(Set::parse(bytes)?),
|
||||
"delete" => Self::Delete(Delete::parse(bytes)?),
|
||||
"has" => Self::Has(Has::parse(bytes)?),
|
||||
"ttl" => Self::Ttl(Ttl::parse(bytes)?),
|
||||
_ => return Err(AppError::UnknownCommand(command_name)),
|
||||
};
|
||||
|
||||
|
||||
42
src/commands/ttl.rs
Normal file
42
src/commands/ttl.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use std::io::Cursor;
|
||||
|
||||
use bytes::{Buf as _, BufMut, Bytes, BytesMut};
|
||||
|
||||
use crate::{Result, connection::Connection, database::Database, errors::AppError};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Ttl {
|
||||
key: String,
|
||||
}
|
||||
|
||||
impl Ttl {
|
||||
pub async fn execute(self, db: &Database, connection: &mut Connection) -> Result<()> {
|
||||
let ttl = db.ttl(&self.key).await;
|
||||
|
||||
let Some(ttl) = ttl else {
|
||||
connection.write(Bytes::from_static(&[0])).await?;
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let mut buf = BytesMut::new();
|
||||
|
||||
buf.put_u8(1);
|
||||
buf.put_u64(ttl);
|
||||
|
||||
connection.write(buf.into()).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())?;
|
||||
|
||||
Ok(Self { key })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user