aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-07 04:42:12 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-07 04:42:12 +0000
commitf151b796a66adfb1d6b7bf151f2d85fd78cc0a64 (patch)
treeba530b977e6e853d6e1582adbfe1e840d03ffd38 /src
downloadlab-06-f151b796a66adfb1d6b7bf151f2d85fd78cc0a64.tar.gz
publishHEADmaster
Diffstat (limited to 'src')
-rw-r--r--src/dictionary.c234
-rw-r--r--src/dynamic-array.h56
-rw-r--r--src/hash-table.c150
-rw-r--r--src/hash-table.h18
-rw-r--r--src/red-black-tree.c443
-rw-r--r--src/red-black-tree.h17
-rw-r--r--src/utils.h21
7 files changed, 939 insertions, 0 deletions
diff --git a/src/dictionary.c b/src/dictionary.c
new file mode 100644
index 0000000..291c200
--- /dev/null
+++ b/src/dictionary.c
@@ -0,0 +1,234 @@
1#include <stdlib.h>
2#include <stdio.h>
3#include <stdint.h>
4#include <string.h>
5#include <wchar.h>
6#include <wctype.h>
7#include <locale.h>
8#include "utils.h"
9#include "hash-table.h"
10#include "red-black-tree.h"
11
12#define MENU_ENTRIES_GENERAL(X, ...) \
13 X(__VA_ARGS__, EXIT, "EXIT")
14
15#define MENU_ENTRIES_HASH_TABLE(X, ...) \
16 X(__VA_ARGS__, PRINT, "PRINT" ) \
17 X(__VA_ARGS__, INSERT, "INSERT" ) \
18 X(__VA_ARGS__, DELETE, "DELETE" ) \
19 X(__VA_ARGS__, SEARCH, "SEARCH" ) \
20 X(__VA_ARGS__, CLEAR, "CLEAR" ) \
21 X(__VA_ARGS__, LOAD_FROM_FILE, "LOAD_FROM_FILE")
22
23#define MENU_ENTRIES_RED_BLACK_TREE(X, ...) \
24 X(__VA_ARGS__, PRINT, "PRINT" ) \
25 X(__VA_ARGS__, INSERT, "INSERT" ) \
26 X(__VA_ARGS__, DELETE, "DELETE" ) \
27 X(__VA_ARGS__, SEARCH, "SEARCH" ) \
28 X(__VA_ARGS__, CLEAR, "CLEAR" ) \
29 X(__VA_ARGS__, LOAD_FROM_FILE, "LOAD_FROM_FILE")
30
31#define MENU_ENTRY_ENUM(PREFIX, SYMBOL, ...) PREFIX ## _ ## SYMBOL,
32
33enum menu_entry {
34 MENU_ENTRIES_GENERAL (MENU_ENTRY_ENUM, GENERAL )
35 MENU_ENTRIES_HASH_TABLE (MENU_ENTRY_ENUM, HASH_TABLE )
36 MENU_ENTRIES_RED_BLACK_TREE (MENU_ENTRY_ENUM, RED_BLACK_TREE)
37 MENU_ENTRY_COUNT
38};
39
40#define MENU_ENTRY_LABEL(SYMBOL_PREFIX, LABEL_PREFIX, SYMBOL, LABEL, ...) \
41 [SYMBOL_PREFIX ## _ ## SYMBOL] = LABEL_PREFIX LABEL,
42
43const char *menu_entry_labels[MENU_ENTRY_COUNT] = {
44 MENU_ENTRIES_GENERAL (MENU_ENTRY_LABEL, GENERAL, "GENERAL:.........")
45 MENU_ENTRIES_HASH_TABLE (MENU_ENTRY_LABEL, HASH_TABLE, "HASH-TABLE:......")
46 MENU_ENTRIES_RED_BLACK_TREE (MENU_ENTRY_LABEL, RED_BLACK_TREE, "RED-BLACK-TREE:..")
47};
48
49static inline uint8_t
50log10u8 (uint8_t value)
51{
52 return ((value >= 100u) ? 2 :
53 (value >= 10u) ? 1
54 : 0);
55}
56
57static inline void
58input_line (const char *what, char **line, size_t *line_size)
59{
60 printf ("%s: ", what);
61 size_t length = getline (line, line_size, stdin);
62 (*line)[length - 1] = '\0';
63}
64
65static inline char *input_word ()
66{
67 static char *word = NULL;
68 static size_t word_size = 0;
69
70 input_line ("WORD", &word, &word_size);
71 return word;
72}
73
74static inline char *input_filename ()
75{
76 static char *filename = NULL;
77 static size_t filename_size = 0;
78
79 input_line ("FILENAME", &filename, &filename_size);
80 return filename;
81}
82
83static void
84load_from_file (const char *filename,
85 void (*inserter) (void *context, const char *key, const char *value),
86 void *context)
87{
88 static char *line = NULL;
89 static size_t line_size = 0;
90 static size_t line_length = 0;
91
92 FILE *stream = fopen (filename, "r");
93 if (!stream) {
94 puts ("UNABLE TO OPEN FILE FOR READING");
95 return;
96 }
97
98 size_t entry_count = 0;
99 wchar_t wword[1024];
100 char word[2048];
101 for (;;) {
102 wint_t wc;
103 do wc = fgetwc (stream);
104 while (wc != WEOF && !wcschr (L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", wc));
105 ungetwc (wc, stream);
106
107 if (fwscanf (stream, L"%l[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ]", wword) != 1)
108 break;
109
110 for (wchar_t *head = wword; *head; ++head)
111 *head = towlower (*head);
112
113 wcstombs (word, wword, 2048);
114 inserter (context, strdup (word), strdup (""));
115 entry_count += 1;
116 } fclose (stream);
117
118 printf ("FILE LOADED (%zu ENTRIES)\n", entry_count);
119}
120
121int
122main (void)
123{
124 setlocale (LC_ALL, "");
125
126 // HASH_TABLE hash_table = hash_table_init (193);
127 HASH_TABLE hash_table = hash_table_init (13);
128 RED_BLACK_TREE red_black_tree = red_black_tree_init ();
129
130 load_from_file ("dictionary.txt", (void *) hash_table_insert, hash_table);
131 load_from_file ("dictionary.txt", (void *) red_black_tree_insert, red_black_tree);
132
133 static char *line = NULL;
134 static size_t line_size = 0;
135 for (;;) {
136 enum menu_entry selection = MENU_ENTRY_COUNT;
137 do {
138 printf ("\nSELECT:\n");
139 for (enum menu_entry entry = 0; entry < MENU_ENTRY_COUNT; ++entry) {
140 printf (" [%0*u] %s\n", log10u8 (MENU_ENTRY_COUNT) + 1, entry,
141 menu_entry_labels[entry]);
142 } printf ("> ");
143 getline (&line, &line_size, stdin);
144
145 sscanf (line, "%u", &selection);
146 } while (selection == MENU_ENTRY_COUNT);
147
148 switch (selection) {
149 case GENERAL_EXIT: {
150 puts ("EXITING...");
151 hash_table_free (hash_table);
152 red_black_tree_free (red_black_tree);
153 return EXIT_SUCCESS;
154 } break;
155
156 case HASH_TABLE_PRINT: {
157 hash_table_print (hash_table, "hash-table.dot");
158 puts ("hash-table.dot:0:0: HASH TABLE PRINTED");
159 } break;
160
161 case HASH_TABLE_INSERT: {
162 const char *word = input_word ();
163 hash_table_insert (hash_table, word, strdup (""));
164 puts ("ENTRY INSERTED");
165 } break;
166
167 case HASH_TABLE_DELETE: {
168 const char *word = input_word ();
169 if (hash_table_delete (hash_table, word))
170 puts ("ENTRY DELETED");
171 else
172 puts ("ENTRY NOT FOUND");
173 } break;
174
175 case HASH_TABLE_SEARCH: {
176 const char *key = input_word ();
177 const char *value = hash_table_search (hash_table, key);
178 if (value)
179 puts ("ENTRY FOUND");
180 else
181 puts ("ENTRY NOT FOUND");
182 } break;
183
184 case HASH_TABLE_CLEAR: {
185 hash_table_clear (hash_table);
186 puts ("HASH TABLE CLEARED");
187 } break;
188
189 case HASH_TABLE_LOAD_FROM_FILE: {
190 const char *filename = input_filename ();
191 load_from_file (filename, (void *) hash_table_insert, hash_table);
192 } break;
193
194 case RED_BLACK_TREE_PRINT: {
195 red_black_tree_print (red_black_tree, "red-black-tree.dot");
196 puts ("red-black-tree.dot:0:0: RED BLACK TREE PRINTED");
197 } break;
198
199 case RED_BLACK_TREE_INSERT: {
200 const char *word = input_word ();
201 red_black_tree_insert (red_black_tree, word, strdup (""));
202 puts ("ENTRY INSERTED");
203 } break;
204
205 case RED_BLACK_TREE_DELETE: {
206 const char *key = input_word ();
207 if (red_black_tree_delete (red_black_tree, key))
208 puts ("ENTRY DELETED");
209 else
210 puts ("ENTRY NOT FOUND");
211 } break;
212
213 case RED_BLACK_TREE_SEARCH: {
214 const char *key = input_word ();
215 const char *value = red_black_tree_search (red_black_tree, key);
216 if (value)
217 puts ("ENTRY FOUND");
218 else
219 puts ("ENTRY NOT FOUND");
220 } break;
221
222 case RED_BLACK_TREE_CLEAR: {
223 red_black_tree_clear (red_black_tree);
224 puts ("RED BLACK TREE CLEARED");
225 } break;
226
227 case RED_BLACK_TREE_LOAD_FROM_FILE: {
228 const char *filename = input_filename ();
229 load_from_file (filename, (void *) red_black_tree_insert, red_black_tree);
230 } break;
231 default: break;
232 }
233 }
234}
diff --git a/src/dynamic-array.h b/src/dynamic-array.h
new file mode 100644
index 0000000..212e9f4
--- /dev/null
+++ b/src/dynamic-array.h
@@ -0,0 +1,56 @@
1#ifndef INCLUDED_DYNAMIC_ARRAY_H
2#define INCLUDED_DYNAMIC_ARRAY_H
3
4#include "utils.h"
5
6#ifndef DYNAMIC_ARRAY_INIT_CAP
7#define DYNAMIC_ARRAY_INIT_CAP 256
8#endif
9
10#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \
11 ({ \
12 if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \
13 if ((DYNAMIC_ARRAY).capacity == 0) \
14 (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \
15 while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \
16 (DYNAMIC_ARRAY).capacity *= 2; \
17 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
18 (DYNAMIC_ARRAY).capacity * \
19 sizeof (*(DYNAMIC_ARRAY).items)); \
20 ASSERT((DYNAMIC_ARRAY).items); \
21 } \
22 })
23
24#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \
25 ({ \
26 (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \
27 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
28 (DYNAMIC_ARRAY).capacity * \
29 sizeof (*(DYNAMIC_ARRAY).items)); \
30 ASSERT((DYNAMIC_ARRAY).items); \
31 \
32 })
33
34#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \
35 ({ \
36 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \
37 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \
38 })
39
40#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \
41 ({ \
42 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \
43 memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \
44 (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \
45 (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \
46 })
47
48#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; })
49
50#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items)
51
52#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \
53 typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \
54 ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM)
55
56#endif
diff --git a/src/hash-table.c b/src/hash-table.c
new file mode 100644
index 0000000..7b6c983
--- /dev/null
+++ b/src/hash-table.c
@@ -0,0 +1,150 @@
1#include "hash-table.h"
2#include <string.h>
3#include <stdio.h>
4
5typedef struct entry *ENTRY;
6struct entry {
7 ENTRY next;
8 char *key;
9 char *value;
10};
11
12struct hash_table {
13 size_t bucket_count;
14 ENTRY buckets[];
15};
16
17// NOTE(cmmm): hash * 33 ^ c might be better
18static inline size_t
19hash_function_djb2 (const char *str)
20{
21 size_t hash = 5381;
22 unsigned char c;
23
24 while ((c = *str++))
25 hash = ((hash << 5) + hash) + c; // hash * 33 + c
26
27 return hash;
28}
29
30void
31hash_table_print (HASH_TABLE hash_table, const char *filename)
32{
33 FILE *stream = fopen (filename, "w");
34 fprintf (stream, "digraph hash_table {\n");
35 fprintf (stream, "\trankdir = LR\n");
36 fprintf (stream, "\tnode [shape = record]\n\n");
37 size_t entry_idx = 0;
38 size_t bucket_idx = 0;
39 for (ENTRY *bucket = hash_table->buckets;
40 bucket < hash_table->buckets + hash_table->bucket_count; ++bucket)
41 {
42 fprintf (stream, "\tbucket%zu [label = \"%zu\"]\n", bucket_idx, bucket_idx);
43
44 size_t saved_idx = entry_idx;
45 for (ENTRY entry = *bucket; entry; entry = entry->next)
46 fprintf (stream, "\tentry%zu [label = \"%s\"]\n", entry_idx++, entry->key);
47
48 entry_idx = saved_idx;
49 for (ENTRY entry = *bucket; entry; entry = entry->next) {
50 if (entry == *bucket)
51 fprintf (stream, "\tbucket%zu -> ", bucket_idx);
52 fprintf (stream, "entry%zu", entry_idx++);
53 if (entry->next)
54 fprintf (stream, " -> ");
55 } fprintf (stream, "\n\n");
56
57 bucket_idx += 1;
58 } fprintf (stream, "}\n");
59 fclose (stream);
60}
61
62HASH_TABLE
63hash_table_init (size_t bucket_count)
64{
65 HASH_TABLE hash_table = malloc (sizeof (*hash_table) +
66 bucket_count*sizeof (*hash_table->buckets));
67
68 hash_table->bucket_count = bucket_count;
69 memset (hash_table->buckets, 0,
70 hash_table->bucket_count*sizeof (*hash_table->buckets));
71
72 return hash_table;
73}
74
75void
76hash_table_clear (HASH_TABLE hash_table)
77{
78 if (!hash_table)
79 return;
80
81 for (ENTRY *bucket = hash_table->buckets;
82 bucket < hash_table->buckets + hash_table->bucket_count; ++bucket) {
83 for (ENTRY entry = *bucket, next; entry; entry = next) {
84 next = entry->next;
85 free (entry->key);
86 free (entry->value);
87 free (entry);
88 } *bucket = NULL;
89 }
90}
91
92void
93hash_table_free (HASH_TABLE hash_table)
94{
95 hash_table_clear (hash_table);
96 free (hash_table);
97}
98
99void
100hash_table_insert (HASH_TABLE hash_table, const char *key, const char *value)
101{
102 size_t hash = hash_function_djb2 (key) % hash_table->bucket_count;
103
104 ENTRY *entry = &hash_table->buckets[hash];
105 while (*entry) {
106 if (!strcmp (key, (*entry)->key)) { // found
107 free ((*entry)->value);
108 (*entry)->value = strdup (value);
109 return;
110 } else entry = &(*entry)->next;
111 }
112
113 // not found
114 *entry = malloc (sizeof (**entry));
115 (*entry)->next = NULL;
116 (*entry)->key = strdup (key);
117 (*entry)->value = strdup (value);
118}
119
120bool
121hash_table_delete (HASH_TABLE hash_table, const char *key)
122{
123 size_t hash = hash_function_djb2 (key) % hash_table->bucket_count;
124 ENTRY *entry = &hash_table->buckets[hash];
125 while (*entry) {
126 if (!strcmp (key, (*entry)->key)) { // found
127 ENTRY next = (*entry)->next;
128
129 free ((*entry)->key);
130 free ((*entry)->value);
131 free (*entry);
132
133 *entry = next;
134
135 return true;
136 } else entry = &(*entry)->next;
137 } return false;
138}
139
140const char *
141hash_table_search (HASH_TABLE hash_table, const char *key)
142{
143 size_t hash = hash_function_djb2 (key) % hash_table->bucket_count;
144 ENTRY entry = hash_table->buckets[hash];
145 while (entry) {
146 if (!strcmp (key, entry->key))
147 return entry->value;
148 else entry = entry->next;
149 } return NULL;
150}
diff --git a/src/hash-table.h b/src/hash-table.h
new file mode 100644
index 0000000..b8f14bc
--- /dev/null
+++ b/src/hash-table.h
@@ -0,0 +1,18 @@
1#ifndef INCLUDED_HASH_TABLE_H
2#define INCLUDED_HASH_TABLE_H
3
4#include <stdlib.h>
5#include <stdbool.h>
6
7typedef struct hash_table *HASH_TABLE;
8
9HASH_TABLE hash_table_init (size_t bucket_count);
10void hash_table_print (HASH_TABLE, const char *filename);
11void hash_table_clear (HASH_TABLE);
12void hash_table_free (HASH_TABLE);
13
14void hash_table_insert (HASH_TABLE, const char *key, const char *value);
15bool hash_table_delete (HASH_TABLE, const char *key);
16const char *hash_table_search (HASH_TABLE, const char *key);
17
18#endif
diff --git a/src/red-black-tree.c b/src/red-black-tree.c
new file mode 100644
index 0000000..62be0d8
--- /dev/null
+++ b/src/red-black-tree.c
@@ -0,0 +1,443 @@
1#include "red-black-tree.h"
2#include "dynamic-array.h"
3#include <stdlib.h>
4#include <stdint.h>
5#include <stdio.h>
6#include <string.h>
7
8enum color {
9 COLOR_RED,
10 COLOR_BLACK,
11};
12
13typedef struct node *NODE;
14struct node {
15 enum color color;
16 NODE parent;
17 NODE left;
18 NODE right;
19 char *key;
20 char *value;
21};
22
23struct red_black_tree {
24 NODE root;
25};
26
27struct nodes {
28 NODE *items;
29 uint32_t count;
30 uint32_t capacity;
31};
32
33void
34red_black_tree_print (RED_BLACK_TREE red_black_tree, const char *filename)
35{
36 FILE *file = fopen (filename, "w");
37 fprintf (file, "digraph red_black_tree {\n");
38 fprintf (file, "\tnode [style = filled, fillcolor = black, fontcolor = white]\n");
39
40 struct nodes stack1 = {0};
41 struct nodes stack2 = {0};
42 struct nodes *front_stack = &stack1;
43 struct nodes *back_stack = &stack2;
44 if (red_black_tree->root)
45 DYNAMIC_ARRAY_APPEND (*front_stack, red_black_tree->root);
46 size_t null_count = 0;
47 while (front_stack->count) {
48 DYNAMIC_ARRAY_RESET (*back_stack);
49 DYNAMIC_ARRAY_FOREACH(node, *front_stack) {
50 fprintf (file, "\t\"%s\" [fillcolor = %s]\n", (*node)->key, (*node)->color ? "black" : "webmaroon");
51
52 if ((*node)->left) {
53 DYNAMIC_ARRAY_APPEND (*back_stack, (*node)->left);
54 fprintf (file, "\t\"%s\" -> \"%s\"\n", (*node)->key, (*node)->left->key);
55 } else {
56 fprintf (file, "\tnull%zu [shape = circle, label = \"\", width = 0.2]\n", null_count);
57 fprintf (file, "\t\"%s\" -> null%zu\n", (*node)->key, null_count);
58 null_count += 1;
59 }
60
61 if ((*node)->right) {
62 DYNAMIC_ARRAY_APPEND (*back_stack, (*node)->right);
63 fprintf (file, "\t\"%s\" -> \"%s\"\n", (*node)->key, (*node)->right->key);
64 } else {
65 fprintf (file, "\tnull%zu [shape = circle, label = \"\", width = 0.2]\n", null_count);
66 fprintf (file, "\t\"%s\" -> null%zu\n", (*node)->key, null_count);
67 null_count += 1;
68 }
69 } SWAP (front_stack, back_stack);
70 } fprintf (file, "}\n");
71 fclose (file);
72}
73
74RED_BLACK_TREE
75red_black_tree_init (void)
76{
77 return calloc (1, sizeof (struct red_black_tree));
78}
79
80void
81red_black_tree_clear (RED_BLACK_TREE red_black_tree)
82{
83 if (!red_black_tree || !red_black_tree->root)
84 return;
85
86 struct nodes stack = {0};
87 DYNAMIC_ARRAY_APPEND (stack, red_black_tree->root);
88 while (stack.count) {
89 NODE node = stack.items[stack.count - 1];
90 stack.count -= 1;
91
92 if (node->left)
93 DYNAMIC_ARRAY_APPEND (stack, node->left);
94
95 if (node->right)
96 DYNAMIC_ARRAY_APPEND (stack, node->right);
97
98 free (node->key );
99 free (node->value);
100 free (node );
101 } red_black_tree->root = NULL;
102}
103
104void
105red_black_tree_free (RED_BLACK_TREE red_black_tree)
106{
107 red_black_tree_clear (red_black_tree);
108 free (red_black_tree);
109}
110
111static inline void
112rotate_left (RED_BLACK_TREE red_black_tree, NODE node)
113{
114 NODE y = node->right;
115 if (!y) return;
116 node->right = y->left;
117 if (y->left)
118 y->left->parent = node;
119
120 y->parent = node->parent;
121 if (!node->parent) {
122 red_black_tree->root = y;
123 } else if (node == node->parent->left) {
124 node->parent->left = y;
125 } else {
126 node->parent->right = y;
127 }
128
129 y->left = node;
130 node->parent = y;
131}
132
133static inline void
134rotate_right (RED_BLACK_TREE red_black_tree, NODE node)
135{
136 NODE y = node->left;
137 node->left = y->right;
138 if (y->right) {
139 y->right->parent = node;
140 }
141 y->parent = node->parent;
142 if (!node->parent) {
143 red_black_tree->root = y;
144 } else if (node == node->parent->right) {
145 node->parent->right = y;
146 } else {
147 node->parent->left = y;
148 }
149 y->right = node;
150 node->parent = y;
151}
152
153void
154red_black_tree_insert (RED_BLACK_TREE red_black_tree,
155 const char *key, const char *value)
156{
157 // change value if already exists
158 for (NODE head = red_black_tree->root, next; head; head = next) {
159 int difference = strcmp (head->key, key);
160 if (!difference) {
161 free (head->value);
162 head->value = strdup (value);
163 return;
164 }
165 next = difference > 0 ? head->left : head->right;
166 }
167
168 NODE node = calloc (1, sizeof (*node));
169 node->key = strdup (key);
170 node->value = strdup (value);
171
172 // find parent
173 for (NODE head = red_black_tree->root, next; head; head = next) {
174 node->parent = head;
175 next = strcmp (node->key, head->key) < 0 ? head->left
176 : head->right;
177 }
178
179 // no parent
180 if (!node->parent) {
181 node->color = COLOR_BLACK;
182 red_black_tree->root = node;
183 return;
184 }
185
186 // attach
187 if (strcmp (node->key, node->parent->key) < 0) {
188 node->parent->left = node;
189 } else {
190 node->parent->right = node;
191 }
192
193 // no grandparent
194 if (!node->parent->parent) {
195 return;
196 }
197
198 // fix insert
199 NODE u;
200 while (node->parent->color == COLOR_RED) {
201 if (node->parent == node->parent->parent->right) {
202 u = node->parent->parent->left; // uncle
203 if (u && u->color == COLOR_RED) { // case 3.1
204 u->color = COLOR_BLACK;
205 node->parent->color = COLOR_BLACK;
206 node->parent->parent->color = COLOR_RED;
207 node = node->parent->parent;
208 } else {
209 if (node == node->parent->left) { // case 3.2.2
210 node = node->parent;
211 rotate_right (red_black_tree, node);
212 }
213
214 // case 3.2.1
215 node->parent->color = COLOR_BLACK;
216 node->parent->parent->color = COLOR_RED;
217 rotate_left (red_black_tree, node->parent->parent);
218 }
219 } else {
220 u = node->parent->parent->right; // uncle
221
222 if (u && u->color == COLOR_RED) { // mirror case 3.1
223 u->color = COLOR_BLACK;
224 node->parent->color = COLOR_BLACK;
225 node->parent->parent->color = COLOR_RED;
226 node = node->parent->parent;
227 } else {
228 if (node == node->parent->right) { // mirror case 3.2.2
229 node = node->parent;
230 rotate_left (red_black_tree, node);
231 }
232
233 // mirror case 3.2.1
234 node->parent->color = COLOR_BLACK;
235 node->parent->parent->color = COLOR_RED;
236 rotate_right (red_black_tree, node->parent->parent);
237 }
238 }
239 if (node == red_black_tree->root) {
240 break;
241 }
242 }
243 red_black_tree->root->color = COLOR_BLACK;
244}
245
246
247static inline NODE
248minimum (NODE node)
249{
250 if (!node)
251 return NULL; // patch
252
253 while (node->left)
254 node = node->left;
255
256 return node;
257}
258
259// https://github.com/xieqing/red-black-tree
260bool
261red_black_tree_delete (RED_BLACK_TREE red_black_tree, const char *key)
262{
263 NODE node = NULL;
264 NODE target = NULL;
265 NODE child = NULL;
266
267 for (NODE head = red_black_tree->root, next; head; head = next) {
268 if (!strcmp (head->key, key)) {
269 node = head;
270 break;
271 }
272 next = strcmp (head->key, key) <= 0 ? head->right : head->left;
273 }
274
275 if (!node)
276 return false;
277
278 /* choose node's in-order successor if it has two children */
279 if (!node->left || !node->right) {
280 target = node;
281 } else {
282 target = node->right ? minimum (node->right) : node; /* node->right must not be NIL, thus move down */
283
284 /* data swapped */
285 SWAP (node->key, target->key);
286 SWAP (node->value, target->value);
287 }
288
289 child = !target->left ? target->right : target->left; /* child may be NIL */
290
291 /*
292 * deletion from red-black tree
293 * 4-children cluster (RED target node) becomes 3-children cluster
294 * done
295 * 3-children cluster (RED target node) becomes 2-children cluster
296 * done
297 * 3-children cluster (BLACK target node, RED child node) becomes 2-children cluster
298 * paint child node BLACK, and done
299 *
300 * 2-children root cluster (BLACK target node, BLACK child node) becomes 0-children root cluster
301 * done
302 *
303 * 2-children cluster (BLACK target node, 4-children sibling cluster) becomes 3-children cluster
304 * transfer, and done
305 * 2-children cluster (BLACK target node, 3-children sibling cluster) becomes 2-children cluster
306 * transfer, and done
307 *
308 * 2-children cluster (BLACK target node, 2-children sibling cluster, 3/4-children parent cluster) becomes 3-children cluster
309 * fuse, paint parent node BLACK, and done
310 * 2-children cluster (BLACK target node, 2-children sibling cluster, 2-children parent cluster) becomes 3-children cluster
311 * fuse, and delete parent node from parent cluster
312 */
313 if (target->color == COLOR_BLACK) {
314 if (child && child->color == COLOR_RED) {
315 /* deletion from 3-children cluster (BLACK target node, RED child node) */
316 child->color = COLOR_BLACK;
317 } else if (target == red_black_tree->root) {
318 /* deletion from 2-children root cluster (BLACK target node, BLACK child node) */
319 } else {
320 /* deletion from 2-children cluster (BLACK target node, ...) */
321 // REPAIR
322 NODE current = target;
323 NODE sibling;
324 do {
325 if (current == current->parent->left) {
326 sibling = current->parent->right;
327
328 if (sibling && sibling->color == COLOR_RED) {
329 /* perform an adjustment (3-children parent cluster has two representations) */
330 sibling->color = COLOR_BLACK;
331 current->parent->color = COLOR_RED;
332 rotate_left (red_black_tree, current->parent);
333 sibling = current->parent->right;
334 }
335
336 /* sibling node must be BLACK now */
337 if ((!sibling->right || sibling->right->color == COLOR_BLACK) &&
338 (!sibling->left || sibling->left ->color == COLOR_BLACK)) {
339 /* 2-children sibling cluster, fuse by recoloring */
340 sibling->color = COLOR_RED;
341 if (current->parent->color == COLOR_RED) { /* 3/4-children parent cluster */
342 current->parent->color = COLOR_BLACK;
343 break; /* goto break */
344 } else { /* 2-children parent cluster */
345 current = current->parent; /* goto loop */
346 }
347 } else {
348 /* 3/4-children sibling cluster */
349
350 /* perform an adjustment (3-children sibling cluster has two representations) */
351 if (!sibling->right || sibling->right->color == COLOR_BLACK) {
352 sibling->left->color = COLOR_BLACK;
353 sibling->color = COLOR_RED;
354 rotate_right (red_black_tree, sibling);
355 sibling = current->parent->right;
356 }
357
358 /* transfer by rotation and recoloring */
359 sibling->color = current->parent->color;
360 current->parent->color = COLOR_BLACK;
361 sibling->right->color = COLOR_BLACK;
362 rotate_left (red_black_tree, current->parent);
363 break; /* goto break */
364 }
365 } else {
366 sibling = current->parent->left;
367
368 if (sibling->color == COLOR_RED) {
369 /* perform an adjustment (3-children parent cluster has two representations) */
370 sibling->color = COLOR_BLACK;
371 current->parent->color = COLOR_RED;
372 rotate_right (red_black_tree, current->parent);
373 sibling = current->parent->left;
374 }
375
376 /* sibling node must be BLACK now */
377
378 if ((!sibling->right || sibling->right->color == COLOR_BLACK) &&
379 (!sibling->left || sibling->left ->color == COLOR_BLACK)) {
380 /* 2-children sibling cluster, fuse by recoloring */
381 sibling->color = COLOR_RED;
382 if (current->parent->color == COLOR_RED) { /* 3/4-children parent cluster */
383 current->parent->color = COLOR_BLACK;
384 break; /* goto break */
385 } else { /* 2-children parent cluster */
386 current = current->parent; /* goto loop */
387 }
388 } else {
389 /* 3/4-children sibling cluster */
390
391 /* perform an adjustment (3-children sibling cluster has two representations) */
392 if (!sibling->left || sibling->left->color == COLOR_BLACK) {
393 sibling->right->color = COLOR_BLACK;
394 sibling->color = COLOR_RED;
395 rotate_left (red_black_tree, sibling);
396 sibling = current->parent->left;
397 }
398
399 /* transfer by rotation and recoloring */
400 sibling->color = current->parent->color;
401 current->parent->color = COLOR_BLACK;
402 sibling->left->color = COLOR_BLACK;
403 rotate_right (red_black_tree, current->parent);
404 break; /* goto break */
405 }
406 }
407 } while (current != red_black_tree->root);
408 }
409 } else {
410 /* deletion from 4-children cluster (RED target node) */
411 /* deletion from 3-children cluster (RED target node) */
412 }
413
414 if (child)
415 child->parent = target->parent;
416
417 if (target->parent) {
418 if (target == target->parent->left)
419 target->parent->left = child;
420 else if (target == target->parent->right)
421 target->parent->right = child;
422 } else {
423 red_black_tree->root = child;
424 }
425
426 free (target->key);
427 free (target->value);
428 free (target);
429
430 return true;
431}
432
433const char *
434red_black_tree_search (RED_BLACK_TREE red_black_tree, const char *key)
435{
436 for (NODE head = red_black_tree->root, next; head; head = next) {
437 int difference = strcmp (head->key, key);
438 if (!difference) return head->value;
439 next = difference > 0 ? head->left : head->right;
440 }
441
442 return NULL;
443}
diff --git a/src/red-black-tree.h b/src/red-black-tree.h
new file mode 100644
index 0000000..a18984e
--- /dev/null
+++ b/src/red-black-tree.h
@@ -0,0 +1,17 @@
1#ifndef INCLUDED_RED_BLACK_TREE_H
2#define INCLUDED_RED_BLACK_TREE_H
3
4#include <stdbool.h>
5
6typedef struct red_black_tree *RED_BLACK_TREE;
7
8RED_BLACK_TREE red_black_tree_init (void);
9void red_black_tree_print (RED_BLACK_TREE, const char *filename);
10void red_black_tree_clear (RED_BLACK_TREE);
11void red_black_tree_free (RED_BLACK_TREE);
12
13void red_black_tree_insert (RED_BLACK_TREE, const char *key, const char *value);
14bool red_black_tree_delete (RED_BLACK_TREE, const char *key);
15const char *red_black_tree_search (RED_BLACK_TREE, const char *key);
16
17#endif
diff --git a/src/utils.h b/src/utils.h
new file mode 100644
index 0000000..d4d451f
--- /dev/null
+++ b/src/utils.h
@@ -0,0 +1,21 @@
1#ifndef INCLUDED_UTILS_H
2#define INCLUDED_UTILS_H
3
4#include <assert.h>
5#include <stdlib.h>
6
7#define MALLOC malloc
8#define REALLOC realloc
9#define FREE free
10#define ASSERT assert
11
12#define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP)
13
14#define SWAP(A, B) \
15 ({ \
16 typeof (A) tmp = (A); \
17 (A) = (B); \
18 (B) = tmp; \
19 })
20
21#endif