xaizek / vifm (License: GPLv2+) (since 2018-12-07)
Vifm is a file manager with curses interface, which provides Vi[m]-like environment for managing objects within file systems, extended with some useful ideas from mutt.
<root> / src / utils / trie.c (fcda25787667c3958382249a0ca798042a49db2b) (9,803B) (mode 100644) [raw]
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
/* vifm
 * Copyright (C) 2015 xaizek.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include "trie.h"

#include <assert.h> /* assert() */
#include <stdlib.h> /* calloc() free() malloc() */
#include <string.h> /* memcpy() strlen() strncmp() */

#include "../compat/fs_limits.h"
#include "../compat/reallocarray.h"

#include "macros.h"

/*
 * This is an implementation of a compressed 3-way trie that doesn't support
 * deletion (not necessary for the application).  Each node contains the longest
 * key it can, but it's broken on addition of new keys which differ in their
 * suffix.
 *
 * In order to not look enumerate children linearly, every node contains links
 * to siblings with smaller/larger keys, which makes the trie similar to a
 * regular binary tree without balancing.
 *
 * For better performance memory management is optimized:
 *  - monolithic allocation of node structures in large amounts to not use
 *    allocator on every node creation and be able to destruct with several
 *    calls to free()
 *  - strings are similarly appended to relatively large buffers without NUL
 *    bytes and are reused on breaking nodes (so no string copying there)
 *    Note: this puts a limit on key length, which can't be longer than buffer.
 *
 * Another optimization is caching of the first character of the key to avoid
 * pointer dereferencing when we don't need it (first character decides if we
 * need to go to left or right sibling next).
 */

/* Number of elements in each trie_t::nodes[*]. */
#define NODES_PER_BANK 1024

/* Size of each trie_t::str_bufs[*]. */
#define STR_BUF_SIZE (PATH_MAX*2)

/* Trie node. */
typedef struct trie_node_t
{
	struct trie_node_t *left;  /* Nodes with keys less than query. */
	struct trie_node_t *right; /* Nodes with keys greater than query. */
	struct trie_node_t *down;  /* Child nodes which match prefix of the query. */

	const char *key; /* Key of the node (NO trailing '\0'!). */
	char first;      /* First character of the key for faster access. */
	char exists;     /* Whether this node exists or it's an intermediate node. */
	int key_len;     /* Length of the key. */
	void *data;      /* Data associated with the key. */
}
trie_node_t;

/* Trie.  Manages storage of nodes. */
struct trie_t
{
	trie_node_t *root; /* Root node. */

	trie_node_t **nodes; /* Node storage (NODES_PER_BANK elements per item). */
	int node_count;      /* Number of (allocated) nodes. */

	char **str_bufs;   /* String storage (STR_BUF_SIZE bytes per item). */
	int str_buf_count; /* Number of string buffers. */
	int last_offset;   /* Offset in current string buffer. */

	trie_free_func free_func; /* Function for freeing dynamic data. */
};

static trie_node_t * clone_nodes(trie_t *trie, const trie_node_t *node,
		int *error);
static void free_nodes_data(trie_node_t *node, trie_free_func free_func);
static trie_node_t * make_node(trie_t *trie);
static char * alloc_string(trie_t *trie, const char str[], int len);
static int trie_get_nodes(trie_node_t *node, const char str[], void **data);

trie_t *
trie_create(trie_free_func free_func)
{
	trie_t *trie = calloc(1U, sizeof(*trie));
	if(trie == NULL)
	{
		return NULL;
	}
	trie->free_func = free_func;
	return trie;
}

trie_t *
trie_clone(trie_t *trie)
{
	if(trie == NULL)
	{
		return NULL;
	}

	assert(trie->free_func == NULL && "Can't clone a trie with dynamic data!");

	trie_t *new_trie = trie_create(/*free_func=*/NULL);
	if(new_trie == NULL)
	{
		return NULL;
	}

	int error = 0;
	new_trie->root = clone_nodes(new_trie, trie->root, &error);
	if(error)
	{
		trie_free(new_trie);
		return NULL;
	}

	return new_trie;
}

/* Clones node and all its relatives.  Sets *error to non-zero on error.
 * Returns new node. */
static trie_node_t *
clone_nodes(trie_t *new_trie, const trie_node_t *node, int *error)
{
	if(node == NULL)
	{
		return NULL;
	}

	trie_node_t *new_node = make_node(new_trie);
	if(new_node == NULL)
	{
		*error = 1;
		return NULL;
	}

	new_node->left = clone_nodes(new_trie, node->left, error);
	new_node->right = clone_nodes(new_trie, node->right, error);
	new_node->down = clone_nodes(new_trie, node->down, error);
	new_node->key = alloc_string(new_trie, node->key, node->key_len);
	new_node->first = node->key[0];
	new_node->key_len = node->key_len;
	new_node->exists = node->exists;
	new_node->data = node->data;

	return new_node;
}

void
trie_free(trie_t *trie)
{
	if(trie == NULL)
	{
		return;
	}

	if(trie->free_func != NULL)
	{
		free_nodes_data(trie->root, trie->free_func);
	}

	int banks = DIV_ROUND_UP(trie->node_count, NODES_PER_BANK);
	int bank;
	for(bank = 0; bank < banks; ++bank)
	{
		free(trie->nodes[bank]);
	}
	free(trie->nodes);

	int i;
	for(i = 0; i < trie->str_buf_count; ++i)
	{
		free(trie->str_bufs[i]);
	}
	free(trie->str_bufs);

	free(trie);
}

/* Calls custom free function on data stored in every node. */
static void
free_nodes_data(trie_node_t *node, trie_free_func free_func)
{
	if(node != NULL)
	{
		free_nodes_data(node->left, free_func);
		free_nodes_data(node->right, free_func);
		free_nodes_data(node->down, free_func);
		free_func(node->data);
	}
}

int
trie_put(trie_t *trie, const char str[])
{
	return trie_set(trie, str, NULL);
}

int
trie_set(trie_t *trie, const char str[], const void *data)
{
	if(trie == NULL)
	{
		return -1;
	}

	trie_node_t **link = &trie->root;
	trie_node_t *node = trie->root;

	if(*str == '\0')
	{
		return -1;
	}

	while(1)
	{
		/* Create inexistent node. */
		if(node == NULL)
		{
			node = make_node(trie);
			if(node == NULL)
			{
				return -1;
			}
			node->key_len = strlen(str);
			node->key = alloc_string(trie, str, node->key_len);
			node->first = str[0];
			*link = node;
			break;
		}

		int i = 0;
		while(i < node->key_len && node->key[i] == str[i])
		{
			++i;
		}

		if(i == node->key_len)
		{
			link = &node->down;
			str += node->key_len;

			if(*str == '\0')
			{
				/* Found full match. */
				break;
			}
		}
		else if(i == 0)
		{
			link = (*str < node->first) ? &node->left : &node->right;
		}
		else
		{
			/* Break current node in two as me matched in the middle. */

			trie_node_t *new_node = make_node(trie);
			if(new_node == NULL)
			{
				return -1;
			}
			new_node->key = node->key + i;
			new_node->first = node->key[i];
			new_node->key_len = node->key_len - i;
			new_node->exists = node->exists;
			new_node->data = node->data;
			new_node->down = node->down;

			node->key_len = i;
			node->down = new_node;
			node->exists = 0;
			node->data = NULL;

			/* Return the leading part of the node we just broke in two. */
			if(str[i] == '\0')
			{
				break;
			}

			str += i;
			link = &node->down;
		}
		node = *link;
	}

	const int result = (node->exists != 0);
	node->exists = 1;
	node->data = (void *)data;
	return result;
}

/* Allocates a new node for the trie.  Returns pointer to the node or NULL. */
static trie_node_t *
make_node(trie_t *trie)
{
	const int bank = trie->node_count/NODES_PER_BANK;
	const int bank_index = trie->node_count%NODES_PER_BANK;

	if(bank_index == 0)
	{
		void *nodes = reallocarray(trie->nodes, bank + 1, sizeof(*trie->nodes));
		if(nodes == NULL)
		{
			return NULL;
		}

		trie->nodes = nodes;
		trie->nodes[bank] = calloc(NODES_PER_BANK, sizeof(**trie->nodes));
		if(trie->nodes[bank] == NULL)
		{
			return NULL;
		}
	}

	++trie->node_count;
	return &trie->nodes[bank][bank_index];
}

/* Allocates string in a trie.  Returns pointer to it or NULL if out of
 * memory. */
static char *
alloc_string(trie_t *trie, const char str[], int len)
{
	assert(len <= STR_BUF_SIZE && "Key is too large.");

	if(trie->last_offset + len > STR_BUF_SIZE || trie->str_buf_count == 0)
	{
		void *str_bufs = reallocarray(trie->str_bufs, trie->str_buf_count + 1,
				sizeof(*trie->str_bufs));
		if(str_bufs == NULL)
		{
			return NULL;
		}

		trie->str_bufs = str_bufs;
		trie->str_bufs[trie->str_buf_count] = malloc(STR_BUF_SIZE);

		++trie->str_buf_count;
		trie->last_offset = 0;
	}

	char *buf = trie->str_bufs[trie->str_buf_count - 1] + trie->last_offset;
	memcpy(buf, str, len);

	trie->last_offset += len;
	return buf;
}

int
trie_get(trie_t *trie, const char str[], void **data)
{
	if(trie == NULL)
	{
		return 1;
	}
	return trie_get_nodes(trie->root, str, data);
}

/* Looks up data for the str.  Node can be NULL.  Returns zero when found and
 * sets *data, otherwise returns non-zero. */
static int
trie_get_nodes(trie_node_t *node, const char str[], void **data)
{
	if(*str == '\0')
	{
		return 1;
	}

	int str_len = strlen(str);

	while(1)
	{
		if(node == NULL)
		{
			return 1;
		}

		if(*str == node->first)
		{
			if(str_len < node->key_len ||
					memcmp(node->key + 1, str + 1, node->key_len - 1) != 0)
			{
				return 1;
			}

			str += node->key_len;
			str_len -= node->key_len;

			if(*str == '\0')
			{
				/* Found full match. */
				if(!node->exists)
				{
					return 1;
				}
				*data = node->data;
				return 0;
			}

			node = node->down;
			continue;
		}

		node = (*str < node->first) ? node->left : node->right;
	}
}

/* vim: set tabstop=2 softtabstop=2 shiftwidth=2 noexpandtab cinoptions-=(0 : */
/* vim: set cinoptions+=t0 filetype=c : */
Hints

Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://code.reversed.top/user/xaizek/vifm

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@code.reversed.top/user/xaizek/vifm

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a pull request:
... clone the repository ...
... make some changes and some commits ...
git push origin master