1
1
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 } ;
3
3
4
4
impl CommandExecutor for HGet {
5
5
fn execute ( self , backend : & crate :: Backend ) -> RespFrame {
@@ -16,12 +16,20 @@ impl CommandExecutor for HGetAll {
16
16
17
17
match hmap {
18
18
Some ( hmap) => {
19
- let mut map = RespMap :: new ( ) ;
19
+ let mut data = Vec :: with_capacity ( hmap . len ( ) ) ;
20
20
for v in hmap. iter ( ) {
21
21
let key = v. key ( ) . to_owned ( ) ;
22
- map . insert ( key, v. value ( ) . clone ( ) ) ;
22
+ data . push ( ( key, v. value ( ) . clone ( ) ) ) ;
23
23
}
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 ( )
25
33
}
26
34
None => RespArray :: new ( [ ] ) . into ( ) ,
27
35
}
@@ -62,6 +70,7 @@ impl TryFrom<RespArray> for HGetAll {
62
70
match args. next ( ) {
63
71
Some ( RespFrame :: BulkString ( key) ) => Ok ( HGetAll {
64
72
key : String :: from_utf8 ( key. 0 ) ?,
73
+ sort : false ,
65
74
} ) ,
66
75
_ => Err ( CommandError :: InvalidArgument ( "Invalid key" . to_string ( ) ) ) ,
67
76
}
@@ -166,14 +175,16 @@ mod tests {
166
175
167
176
let cmd = HGetAll {
168
177
key : "map" . to_string ( ) ,
178
+ sort : true ,
169
179
} ;
170
180
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
+ ] ) ;
177
188
assert_eq ! ( result, expected. into( ) ) ;
178
189
Ok ( ( ) )
179
190
}
0 commit comments