~brenns10/sc-examples

ref: c61550ab6e9ab49585a541fbbbaa327e788029cf sc-examples/hash-tester/hash-tester.c -rw-r--r-- 1.4 KiB
c61550abStephen Brennan Add 3-clause BSD license 2 years ago
                                                                                
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
/*
 * hash-tester.c: simple store or retrieve REPL to demo the hash table
 *
 * usage: hash-tester
 * > key=value
 * > key
 * value
 * > exit
 */
#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "sc-collections.h"

int main(int argc, char **argv)
{
	struct sc_hashtable hash;
	char *line = NULL, *key, *value, *oldvalue, *index;
	size_t len = 0;
	size_t keylen, vallen;

	sc_ht_init(&hash, sc_ht_string_hash, sc_ht_string_comp, sizeof(char *),
	           sizeof(char *));

	printf("> ");
	while (getline(&line, &len, stdin) != -1) {
		/* remove newline */
		index = strchr(line, '\n');
		if (index)
			*index = '\0';

		if (strcmp(line, "exit") == 0)
			break;

		index = strchr(line, '=');
		if (index) {
			/* Set key=val */
			*index = '\0';

			keylen = strlen(line);
			key = malloc(keylen + 1);
			strncpy(key, line, keylen + 1);

			index++;
			vallen = strlen(index);
			value = malloc(vallen + 1);
			strncpy(value, index, vallen + 1);

			oldvalue = sc_ht_get_ptr(&hash, key);
			if (oldvalue) {
				printf("deleting %s=%s\n", key, oldvalue);
				free(oldvalue);
			}
			sc_ht_insert_ptr(&hash, key, value);
		} else {
			value = sc_ht_get_ptr(&hash, line);
			if (value) {
				printf("%s\n", value);
			} else {
				printf("Not found!\n");
			}
		}
		printf("> ");
	}

	/* TODO: iteration over keys & values to free */

	free(line);
	sc_ht_destroy(&hash);
}