Skip to content

Commit d69e9eb

Browse files
committed
fix: hgetall should return array
1 parent 9de5026 commit d69e9eb

File tree

4 files changed

+28
-10
lines changed

4 files changed

+28
-10
lines changed

dump.rdb

-149 Bytes
Binary file not shown.

src/cmd/hmap.rs

+21-10
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use super::{extract_args, validate_command, CommandExecutor, HGet, HGetAll, HSet, RESP_OK};
2-
use crate::{cmd::CommandError, RespArray, RespFrame, RespMap};
2+
use crate::{cmd::CommandError, BulkString, RespArray, RespFrame};
33

44
impl CommandExecutor for HGet {
55
fn execute(self, backend: &crate::Backend) -> RespFrame {
@@ -16,12 +16,20 @@ impl CommandExecutor for HGetAll {
1616

1717
match hmap {
1818
Some(hmap) => {
19-
let mut map = RespMap::new();
19+
let mut data = Vec::with_capacity(hmap.len());
2020
for v in hmap.iter() {
2121
let key = v.key().to_owned();
22-
map.insert(key, v.value().clone());
22+
data.push((key, v.value().clone()));
2323
}
24-
map.into()
24+
if self.sort {
25+
data.sort_by(|a, b| a.0.cmp(&b.0));
26+
}
27+
let ret = data
28+
.into_iter()
29+
.flat_map(|(k, v)| vec![BulkString::from(k).into(), v])
30+
.collect::<Vec<RespFrame>>();
31+
32+
RespArray::new(ret).into()
2533
}
2634
None => RespArray::new([]).into(),
2735
}
@@ -62,6 +70,7 @@ impl TryFrom<RespArray> for HGetAll {
6270
match args.next() {
6371
Some(RespFrame::BulkString(key)) => Ok(HGetAll {
6472
key: String::from_utf8(key.0)?,
73+
sort: false,
6574
}),
6675
_ => Err(CommandError::InvalidArgument("Invalid key".to_string())),
6776
}
@@ -166,14 +175,16 @@ mod tests {
166175

167176
let cmd = HGetAll {
168177
key: "map".to_string(),
178+
sort: true,
169179
};
170180
let result = cmd.execute(&backend);
171-
let mut expected = RespMap::new();
172-
expected.insert("hello".to_string(), RespFrame::BulkString(b"world".into()));
173-
expected.insert(
174-
"hello1".to_string(),
175-
RespFrame::BulkString(b"world1".into()),
176-
);
181+
182+
let expected = RespArray::new([
183+
BulkString::from("hello").into(),
184+
BulkString::from("world").into(),
185+
BulkString::from("hello1").into(),
186+
BulkString::from("world1").into(),
187+
]);
177188
assert_eq!(result, expected.into());
178189
Ok(())
179190
}

src/cmd/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ pub struct HSet {
6969
#[derive(Debug)]
7070
pub struct HGetAll {
7171
key: String,
72+
sort: bool,
7273
}
7374

7475
#[derive(Debug)]

src/resp/bulk_string.rs

+6
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,12 @@ impl From<&str> for BulkString {
8989
}
9090
}
9191

92+
impl From<String> for BulkString {
93+
fn from(s: String) -> Self {
94+
BulkString(s.into_bytes())
95+
}
96+
}
97+
9298
impl From<&[u8]> for BulkString {
9399
fn from(s: &[u8]) -> Self {
94100
BulkString(s.to_vec())

0 commit comments

Comments
 (0)