2727#include <stdlib.h>
2828#include <string.h>
2929
30+ // FNV-1a 32-bit hash function
31+ static uint32_t hash_fnv1a_32 (const char * str )
32+ {
33+ uint32_t hash = 2166136261u ;
34+ int c ;
35+
36+ while ((c = (int ) * str ++ ))
37+ {
38+ hash ^= (uint32_t ) c ;
39+ hash *= 16777619u ;
40+ }
41+
42+ return hash ;
43+ }
44+
3045cJSON * mjrpc_response_ok (cJSON * result , cJSON * id )
3146{
3247 if (id == NULL )
@@ -100,8 +115,9 @@ static cJSON* invoke_callback(const mjrpc_handle_t* handle, const char* method_n
100115 ctx .error_code = 0 ;
101116 ctx .error_message = NULL ;
102117 int i = handle -> cb_count ;
118+ const uint32_t hash = hash_fnv1a_32 (method_name );
103119 while (i -- )
104- if (! strcmp ( handle -> cb_array [i ].name , method_name ) )
120+ if (handle -> cb_array [i ].hash == hash )
105121 {
106122 procedure_found = 1 ;
107123 ctx .data = handle -> cb_array [i ].arg ;
@@ -201,7 +217,7 @@ int mjrpc_add_method(mjrpc_handle_t* handle, mjrpc_func function_pointer, const
201217 if (function_pointer == NULL || method_name == NULL )
202218 return MJRPC_RET_ERROR_INVALID_PARAM ;
203219
204- int i = handle -> cb_count ++ ;
220+ const int i = handle -> cb_count ++ ;
205221 if (!handle -> cb_array )
206222 {
207223 handle -> cb_array = malloc (sizeof (struct mjrpc_cb ));
@@ -216,8 +232,7 @@ int mjrpc_add_method(mjrpc_handle_t* handle, mjrpc_func function_pointer, const
216232 return MJRPC_RET_ERROR_MEM_ALLOC_FAILED ;
217233 handle -> cb_array = ptr ;
218234 }
219- if ((handle -> cb_array [i ].name = strdup (method_name )) == NULL )
220- return MJRPC_RET_ERROR_MEM_ALLOC_FAILED ;
235+ handle -> cb_array [i ].hash = hash_fnv1a_32 (method_name );
221236 handle -> cb_array [i ].function = function_pointer ;
222237 handle -> cb_array [i ].arg = arg2func ;
223238
@@ -226,11 +241,6 @@ int mjrpc_add_method(mjrpc_handle_t* handle, mjrpc_func function_pointer, const
226241
227242static void cb_info_destroy (struct mjrpc_cb * info )
228243{
229- if (info -> name )
230- {
231- free (info -> name );
232- info -> name = NULL ;
233- }
234244 if (info -> arg )
235245 {
236246 free (info -> arg );
@@ -254,14 +264,15 @@ int mjrpc_del_method(mjrpc_handle_t* handle, const char* name)
254264
255265 if (handle -> cb_array )
256266 {
267+ const uint32_t hash = hash_fnv1a_32 (name );
257268 int found = 0 ;
258269 for (int i = 0 ; i < handle -> cb_count ; i ++ )
259270 {
260271 if (found )
261272 {
262273 handle -> cb_array [i - 1 ] = handle -> cb_array [i ];
263274 }
264- else if (! strcmp ( name , handle -> cb_array [i ].name ) )
275+ else if (hash == handle -> cb_array [i ].hash )
265276 {
266277 found = 1 ;
267278 cb_info_destroy (& (handle -> cb_array [i ]));
0 commit comments