实现 xy_map_get/each()

This commit is contained in:
Aoran Zeng 2025-08-20 16:37:35 +08:00
parent ad087be36a
commit 560a47f358
No known key found for this signature in database
GPG Key ID: 8F8BA8488E10ED98

View File

@ -1237,6 +1237,7 @@ xy_seq_each (XySeq_t *seq, void (*func)(void *))
}
#define _XY_Map_Buckets_Count 97
struct _XyHashBucket_t
@ -1267,6 +1268,14 @@ xy_map_new ()
}
uint32_t
xy_map_len (XyMap_t *map)
{
xy_cant_be_null (map);
return map->length;
}
unsigned long
xy_hash (const char* str)
{
@ -1278,6 +1287,9 @@ xy_hash (const char* str)
}
/**
* @flavor JavaScript: map.set
*/
void
xy_map_set (XyMap_t *map, const char *key, void *value)
{
@ -1288,7 +1300,7 @@ xy_map_set (XyMap_t *map, const char *key, void *value)
uint32_t index = hash % _XY_Map_Buckets_Count;
// 若 key 已经存在
_XyHashBucket_t *maybe = map->buckets[index];
struct _XyHashBucket_t *maybe = map->buckets[index];
while (maybe)
{
if (xy_streql (maybe->key, key))
@ -1300,7 +1312,7 @@ xy_map_set (XyMap_t *map, const char *key, void *value)
}
// 若 key 不存在
_XyHashBucket_t *bucket = xy_malloc0 (sizeof (struct _XyHashBucket_t));
struct _XyHashBucket_t *bucket = xy_malloc0 (sizeof (struct _XyHashBucket_t));
bucket->key = xy_strdup (key);
bucket->value = value;
@ -1311,4 +1323,51 @@ xy_map_set (XyMap_t *map, const char *key, void *value)
}
/**
* @flavor JavaScript: map.get
*/
void *
xy_map_get (XyMap_t *map, const char *key)
{
xy_cant_be_null (map);
xy_cant_be_null (key);
unsigned long hash = xy_hash (key);
uint32_t index = hash % _XY_Map_Buckets_Count;
struct _XyHashBucket_t *maybe = map->buckets[index];
while (maybe)
{
if (xy_streql (maybe->key, key))
{
return maybe->value;
}
maybe = maybe->next;
}
return NULL;
}
/**
* @flavor Ruby: Hash#each
*/
void
xy_map_each (XyMap_t *map, void (*func)(const char *key, void *value))
{
xy_cant_be_null (map);
xy_cant_be_null (func);
for (uint32_t i = 0; i < _XY_Map_Buckets_Count; i++)
{
struct _XyHashBucket_t *bucket = map->buckets[i];
while (bucket)
{
func (bucket->key, bucket->value);
bucket = bucket->next;
}
}
}
#endif