expire command
This commit is contained in:
37
src/commands/expire.rs
Normal file
37
src/commands/expire.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
use std::io::Cursor;
|
||||
|
||||
use bytes::{Buf as _, Bytes};
|
||||
|
||||
use crate::{Result, connection::Connection, database::Database, errors::AppError};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Expire {
|
||||
key: String,
|
||||
seconds: u64,
|
||||
}
|
||||
|
||||
impl Expire {
|
||||
pub async fn execute(self, db: &Database, connection: &mut Connection) -> Result<()> {
|
||||
let value = db.expire(&self.key, self.seconds).await?;
|
||||
|
||||
connection
|
||||
.write(Bytes::from_static(if value { &[1] } else { &[0] }))
|
||||
.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 seconds = bytes.try_get_u64()?;
|
||||
|
||||
Ok(Self { key, seconds })
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
mod delete;
|
||||
mod expire;
|
||||
mod get;
|
||||
mod has;
|
||||
mod set;
|
||||
@@ -8,6 +9,7 @@ use std::io::Cursor;
|
||||
|
||||
use bytes::{Buf, BytesMut};
|
||||
use delete::Delete;
|
||||
use expire::Expire;
|
||||
use get::Get;
|
||||
use has::Has;
|
||||
use set::Set;
|
||||
@@ -22,6 +24,7 @@ pub enum Command {
|
||||
Delete(Delete),
|
||||
Has(Has),
|
||||
Ttl(Ttl),
|
||||
Expire(Expire),
|
||||
}
|
||||
|
||||
impl Command {
|
||||
@@ -32,6 +35,7 @@ impl Command {
|
||||
Command::Delete(delete) => delete.execute(db, connection).await,
|
||||
Command::Has(has) => has.execute(db, connection).await,
|
||||
Command::Ttl(ttl) => ttl.execute(db, connection).await,
|
||||
Command::Expire(expire) => expire.execute(db, connection).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,6 +60,7 @@ impl Command {
|
||||
"delete" => Self::Delete(Delete::parse(bytes)?),
|
||||
"has" => Self::Has(Has::parse(bytes)?),
|
||||
"ttl" => Self::Ttl(Ttl::parse(bytes)?),
|
||||
"expire" => Self::Expire(Expire::parse(bytes)?),
|
||||
_ => return Err(AppError::UnknownCommand(command_name)),
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user