@@ -51,18 +51,36 @@ impl Command for AllocSetCommand {
5151 // 2. Allocate data [OK]
5252 // 3. Set the key to the data [OK]
5353 // 4. Activate custom allocator and compare Redis memory usage [OK]
54- // 5. Handle deallocation of existing value
54+ // 5. Handle deallocation of existing value [OK]
5555
5656 let key = r. open_key_writable ( key) ;
57- key. check_type ( & MY_TYPE ) ?;
58-
59- // TODO: If there is an existing value, reuse it or deallocate it.
60-
61- let my = Box :: into_raw ( Box :: new (
62- MyType {
63- data : "A" . repeat ( size as usize )
57+ let key_type = key. verify_and_get_type ( & MY_TYPE ) ?;
58+
59+ let my = match key_type {
60+ raw:: KeyType :: Empty => {
61+ // Create a new value
62+ Box :: new (
63+ MyType {
64+ data : "A" . repeat ( size as usize )
65+ }
66+ )
67+ }
68+ _ => {
69+ // There is an existing value, reuse it
70+ let my = key. get_value ( ) as * mut MyType ;
71+
72+ if my. is_null ( ) {
73+ r. reply_integer ( 0 ) ?;
74+ return Ok ( ( ) ) ;
75+ }
76+
77+ let mut my = unsafe { Box :: from_raw ( my) } ;
78+ my. data = "B" . repeat ( size as usize ) ;
79+ my
6480 }
65- ) ) ;
81+ } ;
82+
83+ let my = Box :: into_raw ( my) ;
6684
6785 key. set_value ( & MY_TYPE , my as * mut c_void ) ?;
6886 r. reply_integer ( size) ?;
@@ -105,9 +123,7 @@ impl Command for AllocGetCommand {
105123 let key = args[ 1 ] ;
106124
107125 let key = r. open_key ( key) ;
108-
109- key. check_type ( & MY_TYPE ) ?;
110-
126+ key. verify_and_get_type ( & MY_TYPE ) ?;
111127 let my = key. get_value ( ) as * mut MyType ;
112128
113129 if my. is_null ( ) {
@@ -179,7 +195,7 @@ pub extern "C" fn AllocDelCommand_Redis(
179195fn module_on_load ( ctx : * mut raw:: RedisModuleCtx ) -> Result < ( ) , & ' static str > {
180196 module_init ( ctx, MODULE_NAME , MODULE_VERSION ) ?;
181197
182- // TODO: Call this from inside module_init
198+ // TODO: Call this from inside module_init
183199 redismodule:: use_redis_alloc ( ) ;
184200
185201 MY_TYPE . create_data_type ( ctx, "mytype123" ) ?;
0 commit comments