1 /** 2 * \file z-quark.c 3 * \brief Save memory by storing strings in a global array, ensuring 4 * that each is only allocated once. 5 * 6 * Copyright (c) 1997 Ben Harrison 7 * Copyright (c) 2007 "Elly" 8 * 9 * This work is free software; you can redistribute it and/or modify it 10 * under the terms of either: 11 * 12 * a) the GNU General Public License as published by the Free Software 13 * Foundation, version 2, or 14 * 15 * b) the "Angband licence": 16 * This software may be copied and distributed for educational, research, 17 * and not for profit purposes provided that this copyright and statement 18 * are included in all such copies. Other copyrights may also apply. 19 */ 20 #include "z-virt.h" 21 #include "z-quark.h" 22 #include "init.h" 23 24 static char **quarks; 25 static size_t nr_quarks = 1; 26 static size_t alloc_quarks = 0; 27 28 #define QUARKS_INIT 16 29 quark_add(const char * str)30quark_t quark_add(const char *str) 31 { 32 quark_t q; 33 34 for (q = 1; q < nr_quarks; q++) { 35 if (!strcmp(quarks[q], str)) 36 return q; 37 } 38 39 if (nr_quarks == alloc_quarks) { 40 alloc_quarks *= 2; 41 quarks = mem_realloc(quarks, alloc_quarks * sizeof(char *)); 42 } 43 44 q = nr_quarks++; 45 quarks[q] = string_make(str); 46 47 return q; 48 } 49 quark_str(quark_t q)50const char *quark_str(quark_t q) 51 { 52 return (q >= nr_quarks ? NULL : quarks[q]); 53 } 54 quarks_init(void)55void quarks_init(void) 56 { 57 nr_quarks = 1; 58 alloc_quarks = QUARKS_INIT; 59 quarks = mem_zalloc(alloc_quarks * sizeof(char*)); 60 } 61 quarks_free(void)62void quarks_free(void) 63 { 64 size_t i; 65 66 /* quarks[0] is special */ 67 for (i = 1; i < nr_quarks; i++) 68 string_free(quarks[i]); 69 70 mem_free(quarks); 71 } 72 73 struct init_module z_quark_module = { 74 .name = "z-quark", 75 .init = quarks_init, 76 .cleanup = quarks_free 77 }; 78