oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/c/canonical.txt
2.0 KiB, 1 run
created by r1870400018:11932, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | #include <stdio.h> |
| 2 | #include <stdlib.h> |
| 3 | #include <string.h> |
| 4 | |
| 5 | #define MAX_LINE 1024 |
| 6 | #define HASH_SIZE 1024 |
| 7 | |
| 8 | typedef struct Entry { |
| 9 | char *key; |
| 10 | char *value; |
| 11 | struct Entry *next; |
| 12 | } Entry; |
| 13 | |
| 14 | typedef struct { |
| 15 | Entry *buckets[HASH_SIZE]; |
| 16 | int count; |
| 17 | } HashMap; |
| 18 | |
| 19 | static unsigned int hash(const char *s) { |
| 20 | unsigned int h = 5381; |
| 21 | int c; |
| 22 | while ((c = *s++)) |
| 23 | h = ((h << 5) + h) + c; |
| 24 | return h % HASH_SIZE; |
| 25 | } |
| 26 | |
| 27 | HashMap *hashmap_new(void) { |
| 28 | HashMap *map = calloc(1, sizeof(HashMap)); |
| 29 | if (!map) { |
| 30 | fprintf(stderr, "out of memory\n"); |
| 31 | exit(1); |
| 32 | } |
| 33 | return map; |
| 34 | } |
| 35 | |
| 36 | void hashmap_put(HashMap *map, const char *key, const char *value) { |
| 37 | unsigned int idx = hash(key); |
| 38 | Entry *e = map->buckets[idx]; |
| 39 | while (e) { |
| 40 | if (strcmp(e->key, key) == 0) { |
| 41 | free(e->value); |
| 42 | e->value = strdup(value); |
| 43 | return; |
| 44 | } |
| 45 | e = e->next; |
| 46 | } |
| 47 | Entry *new_entry = malloc(sizeof(Entry)); |
| 48 | new_entry->key = strdup(key); |
| 49 | new_entry->value = strdup(value); |
| 50 | new_entry->next = map->buckets[idx]; |
| 51 | map->buckets[idx] = new_entry; |
| 52 | map->count++; |
| 53 | } |
| 54 | |
| 55 | const char *hashmap_get(HashMap *map, const char *key) { |
| 56 | unsigned int idx = hash(key); |
| 57 | Entry *e = map->buckets[idx]; |
| 58 | while (e) { |
| 59 | if (strcmp(e->key, key) == 0) |
| 60 | return e->value; |
| 61 | e = e->next; |
| 62 | } |
| 63 | return NULL; |
| 64 | } |
| 65 | |
| 66 | void hashmap_free(HashMap *map) { |
| 67 | for (int i = 0; i < HASH_SIZE; i++) { |
| 68 | Entry *e = map->buckets[i]; |
| 69 | while (e) { |
| 70 | Entry *next = e->next; |
| 71 | free(e->key); |
| 72 | free(e->value); |
| 73 | free(e); |
| 74 | e = next; |
| 75 | } |
| 76 | } |
| 77 | free(map); |
| 78 | } |
| 79 | |
| 80 | int main(int argc, char *argv[]) { |
| 81 | HashMap *map = hashmap_new(); |
| 82 | hashmap_put(map, "name", "annealer"); |
| 83 | hashmap_put(map, "version", "0.1.0"); |
| 84 | |
| 85 | printf("name = %s\n", hashmap_get(map, "name")); |
| 86 | printf("version = %s\n", hashmap_get(map, "version")); |
| 87 | printf("count = %d\n", map->count); |
| 88 | |
| 89 | hashmap_free(map); |
| 90 | return 0; |
| 91 | } |