rustdis/commands/
object.rs

1use bytes::Bytes;
2use std::sync::{Arc, Mutex};
3
4use crate::commands::executable::Executable;
5use crate::commands::{CommandParser, CommandParserError};
6use crate::frame::Frame;
7use crate::store::Store;
8use crate::Error;
9
10#[derive(Debug, PartialEq)]
11pub enum Object {
12    Encoding(Encoding),
13}
14
15/// Encoding returns the internal encoding for the Redis object stored at <key>.
16///
17/// Ref: <https://redis.io/docs/latest/commands/object-encoding>
18#[derive(Debug, PartialEq)]
19pub struct Encoding {
20    pub key: String,
21}
22
23impl Executable for Object {
24    fn exec(self, store: Arc<Mutex<Store>>) -> Result<Frame, Error> {
25        match self {
26            Self::Encoding(encoding) => encoding.exec(store),
27        }
28    }
29}
30
31impl TryFrom<&mut CommandParser> for Object {
32    type Error = Error;
33
34    fn try_from(parser: &mut CommandParser) -> Result<Self, Self::Error> {
35        let sub_command = parser.next_string()?;
36        let sub_command = sub_command.to_lowercase();
37
38        match sub_command.as_str() {
39            "encoding" => {
40                let key = parser.next_string()?;
41                Ok(Self::Encoding(Encoding { key }))
42            }
43            _ => Err(CommandParserError::UnknownCommand {
44                command: format!("OBJECT {}", sub_command.to_uppercase()),
45            }
46            .into()),
47        }
48    }
49}
50
51impl Executable for Encoding {
52    fn exec(self, store: Arc<Mutex<Store>>) -> Result<Frame, Error> {
53        let store = store.lock().unwrap();
54        let res = if store.exists(&self.key) {
55            Frame::Bulk(Bytes::from("raw"))
56        } else {
57            Frame::Null
58        };
59
60        Ok(res)
61    }
62}