-
Notifications
You must be signed in to change notification settings - Fork 0
/
dictionary.cpp
69 lines (63 loc) · 1.41 KB
/
dictionary.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* SPDX-FileCopyrightText: © 2019,2021 Alexandros Theodotou <[email protected]>
*
* SPDX-License-Identifier: LicenseRef-ZrythmLicense
*/
#include "dictionary.h"
#include "mem.h"
#include "objects.h"
Dictionary *
dictionary_new (void)
{
Dictionary proto = { 0, 10, object_new_n (10, DictionaryEntry) };
Dictionary * d = object_new (Dictionary);
*d = proto;
return d;
}
static int
dictionary_find_index (Dictionary * dict, const char * key)
{
for (int i = 0; i < dict->len; i++)
{
if (!strcmp (dict->entry[i].key, key))
{
return i;
}
}
return -1;
}
void *
dictionary_find (Dictionary * dict, const char * key, void * def)
{
int idx = dictionary_find_index (dict, key);
return idx == -1 ? def : dict->entry[idx].val;
}
void
_dictionary_add (Dictionary * dict, const char * key, void * value)
{
int idx = dictionary_find_index (dict, key);
if (idx != -1)
{
dict->entry[idx].val = value;
return;
}
if (dict->len == (int) dict->size)
{
dict->entry = object_realloc_n (
dict->entry, dict->size, dict->size * 2, DictionaryEntry);
dict->size *= 2;
}
dict->entry[dict->len].key = g_strdup (key);
dict->entry[dict->len].val = value;
dict->len++;
}
void
dictionary_free (Dictionary * dict)
{
for (int i = 0; i < dict->len; i++)
{
g_free_and_null (dict->entry[i].key);
}
free (dict->entry);
free (dict);
}