@@ -875,13 +875,16 @@ void randomWithCountCommand(client *c) {
875
875
long l ;
876
876
unsigned long count ;
877
877
unsigned long numkeys = 0 ;
878
+ int canDuplicated = 0 ;
879
+ dict * section_dict ;
878
880
879
881
if (getRangeLongFromObjectOrReply (c , c -> argv [2 ], - LONG_MAX , LONG_MAX , & l , NULL ) != C_OK ) return ;
880
882
if (l >= 0 ) {
881
883
count = (unsigned long )l ;
882
884
} else {
883
885
/* A negative count means: return the same elements multiple times */
884
886
count = - l ;
887
+ canDuplicated = 1 ;
885
888
}
886
889
887
890
/* If count is zero, serve it ASAP to avoid special cases later. */
@@ -890,11 +893,13 @@ void randomWithCountCommand(client *c) {
890
893
return ;
891
894
}
892
895
893
- int maxtries = 100 * count ;
896
+ if (canDuplicated ) {
897
+ section_dict = dictCreate (& stringSetDictType );
898
+ dictExpand (section_dict , count );
899
+ }
894
900
901
+ int maxtries = 100 * count ;
895
902
void * replylen = addReplyDeferredLen (c );
896
- dict * section_dict = dictCreate (& stringSetDictType );
897
- dictExpand (section_dict , 100 );
898
903
while (maxtries -- > 0 && count > 0 ) {
899
904
void * entry ;
900
905
int randomDictIndex = kvstoreGetFairRandomHashtableIndex (c -> db -> keys );
@@ -904,14 +909,21 @@ void randomWithCountCommand(client *c) {
904
909
}
905
910
robj * valkey = entry ;
906
911
sds key = objectGetKey (valkey );
907
- if (dictAdd (section_dict , key , NULL ) != DICT_OK ) {
908
- continue ;
912
+ if (canDuplicated ) {
913
+ sds dictKey = sdsdup (key );
914
+ if (dictAdd (section_dict , dictKey , NULL ) != DICT_OK ) {
915
+ sdsfree (dictKey );
916
+ continue ;
917
+ }
909
918
}
910
919
addReplyBulkCBuffer (c , key , sdslen (key ));
911
920
numkeys ++ ;
912
921
count -- ;
913
922
}
914
923
setDeferredArrayLen (c , replylen , numkeys );
924
+ if (canDuplicated ) {
925
+ dictRelease (section_dict );
926
+ }
915
927
}
916
928
917
929
/************************************************************
0 commit comments