dict: add SORTED flag and faster lookup in that case

This commit is contained in:
Wim Taymans 2019-10-03 09:29:51 +02:00
parent fb95e7660a
commit 1f700e7cdd
2 changed files with 26 additions and 8 deletions

View file

@ -41,6 +41,7 @@ struct spa_dict_item {
#define SPA_DICT_ITEM_INIT(key,value) (struct spa_dict_item) { key, value } #define SPA_DICT_ITEM_INIT(key,value) (struct spa_dict_item) { key, value }
struct spa_dict { struct spa_dict {
#define SPA_DICT_FLAG_SORTED (1<<0) /**< items are sorted */
uint32_t flags; uint32_t flags;
uint32_t n_items; uint32_t n_items;
const struct spa_dict_item *items; const struct spa_dict_item *items;
@ -54,13 +55,31 @@ struct spa_dict {
(item) < &(dict)->items[(dict)->n_items]; \ (item) < &(dict)->items[(dict)->n_items]; \
(item)++) (item)++)
static inline int spa_dict_item_compare(const void *i1, const void *i2)
{
const struct spa_dict_item *it1 = (const struct spa_dict_item *)i1,
*it2 = (const struct spa_dict_item *)i2;
return strcmp(it1->key, it2->key);
}
static inline const struct spa_dict_item *spa_dict_lookup_item(const struct spa_dict *dict, static inline const struct spa_dict_item *spa_dict_lookup_item(const struct spa_dict *dict,
const char *key) const char *key)
{ {
const struct spa_dict_item *item; const struct spa_dict_item *item;
spa_dict_for_each(item, dict) {
if (!strcmp(item->key, key)) if (SPA_FLAG_IS_SET(dict->flags, SPA_DICT_FLAG_SORTED)) {
struct spa_dict_item k = SPA_DICT_ITEM_INIT(key, NULL);
item = (const struct spa_dict_item *)bsearch(&k,
(const void *) dict->items, dict->n_items,
sizeof(struct spa_dict_item),
spa_dict_item_compare);
if (item != NULL)
return item; return item;
} else {
spa_dict_for_each(item, dict) {
if (!strcmp(item->key, key))
return item;
}
} }
return NULL; return NULL;
} }

View file

@ -62,12 +62,11 @@ static void clear_item(struct spa_dict_item *item)
static int find_index(const struct pw_properties *this, const char *key) static int find_index(const struct pw_properties *this, const char *key)
{ {
uint32_t i, len = this->dict.n_items; const struct spa_dict_item *item;
for (i = 0; i < len; i++) { item = spa_dict_lookup_item(&this->dict, key);
if (strcmp(this->dict.items[i].key, key) == 0) if (item == NULL)
return i; return -1;
} return item - this->dict.items;
return -1;
} }
static struct properties *properties_new(int prealloc) static struct properties *properties_new(int prealloc)