Skip to content

Commit

Permalink
fix: hgetall should return array
Browse files Browse the repository at this point in the history
  • Loading branch information
rcrwhyg committed Sep 10, 2024
1 parent 9db5aad commit 9b365c6
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 11 deletions.
30 changes: 19 additions & 11 deletions src/cmd/hmap.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{Backend, RespArray, RespFrame, RespMap};
use crate::{Backend, BulkString, RespArray, RespFrame};

use super::{
extract_args, validate_command, CommandError, CommandExecutor, HGet, HGetAll, HSet, RESP_OK,
Expand All @@ -19,14 +19,20 @@ impl CommandExecutor for HGetAll {

match hmap {
Some(hmap) => {
let mut map = RespMap::new();

let mut data = Vec::with_capacity(hmap.len());
for v in hmap.iter() {
let key = v.key().to_owned();
map.insert(key, v.value().clone());
data.push((key, v.value().clone()));
}
if self.sort {
data.sort_by(|a, b| a.0.cmp(&b.0));
}
let ret = data
.into_iter()
.flat_map(|(k, v)| vec![BulkString::from(k).into(), v])
.collect::<Vec<RespFrame>>();

map.into()
RespArray::new(ret).into()
}
None => RespArray::new([]).into(),
}
Expand Down Expand Up @@ -71,6 +77,7 @@ impl TryFrom<RespArray> for HGetAll {
match args.next() {
Some(RespFrame::BulkString(key)) => Ok(HGetAll {
key: String::from_utf8(key.0)?,
sort: false,
}),
_ => Err(CommandError::InvalidArgument("Invalid key".to_string())),
}
Expand Down Expand Up @@ -177,14 +184,15 @@ mod tests {

let cmd = HGetAll {
key: "map".to_string(),
sort: true,
};
let result = cmd.execute(&backend);
let mut expected = RespMap::new();
expected.insert("hello".to_string(), RespFrame::BulkString(b"world".into()));
expected.insert(
"hello1".to_string(),
RespFrame::BulkString(b"world1".into()),
);
let expected = RespArray::new([
BulkString::from("hello").into(),
BulkString::from("world").into(),
BulkString::from("hello1").into(),
BulkString::from("world1").into(),
]);
assert_eq!(result, expected.into());
Ok(())
}
Expand Down
1 change: 1 addition & 0 deletions src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ pub struct HSet {
#[derive(Debug)]
pub struct HGetAll {
key: String,
sort: bool,
}

#[derive(Debug)]
Expand Down
6 changes: 6 additions & 0 deletions src/resp/bulk_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ impl From<&str> for BulkString {
}
}

impl From<String> for BulkString {
fn from(s: String) -> Self {
BulkString(s.into_bytes())
}
}

impl From<&[u8]> for BulkString {
fn from(s: &[u8]) -> Self {
BulkString(s.to_vec())
Expand Down

0 comments on commit 9b365c6

Please # to comment.