stringmap.c 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /*
  2. * Copyright (c) 2004 Anders Magnusson (ragge@ludd.luth.se).
  3. * Copyright (c) 2009 Joseph Adams (joeyadams3.14159@gmail.com).
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. The name of the author may not be used to endorse or promote products
  15. * derived from this software without specific prior written permission
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  18. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  19. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  20. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  21. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  22. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  23. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  26. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. /* This is a heavily modified version of the Patricia tree implementation
  29. in PCC at http://pcc.zentus.com/cgi-bin/cvsweb.cgi/cc/cpp/cpp.c?rev=1.96 */
  30. #include <ccan/stringmap/stringmap.h>
  31. //#define CONSISTENCY_CHECK
  32. #if 0
  33. #include <assert.h>
  34. #else
  35. #define assert(...) do {} while(0)
  36. #endif
  37. #define PEEK_BIT(key, bit) ((key[bit >> 3] >> (~bit & 7)) & 1)
  38. struct stringmap_node {
  39. uint32_t left_is_leaf:1, right_is_leaf:1, bitno:30;
  40. struct stringmap_node *lr[2];
  41. };
  42. struct T {
  43. char *str;
  44. size_t len;
  45. };
  46. static inline struct T *leaf(struct stringmap_node *n, int lr) {
  47. assert(lr ? n->right_is_leaf : n->left_is_leaf);
  48. return (struct T*)n->lr[lr];
  49. }
  50. /* Normal nodes diverge because there was a 0 or 1 difference. If left_ends(n),
  51. then the node diverges because one string ends and the rest don't. */
  52. static inline int left_ends(struct stringmap_node *n) {
  53. return (n->left_is_leaf && (leaf(n,0)->len << 3)==n->bitno);
  54. }
  55. static void *T_new(struct block_pool *bp, const char *key, size_t len, size_t T_size) {
  56. struct T *leaf = block_pool_alloc(bp, T_size);
  57. memset(leaf, 0, T_size);
  58. leaf->str = block_pool_alloc_align(bp, len+1, 1);
  59. memcpy(leaf->str, key, len);
  60. leaf->str[len] = 0;
  61. leaf->len = len;
  62. return leaf;
  63. }
  64. //used for diagnostics
  65. static int consistency_check(struct stringmap *t);
  66. static void emit_dot(struct stringmap *t);
  67. static void emit_subtree(struct stringmap_node *n, int is_leaf);
  68. void *stringmap_lookup_real(struct stringmap *t, const char *key, size_t len, int enterf, size_t T_size) {
  69. struct T *sp;
  70. struct stringmap_node *w, *new, *last;
  71. uint32_t cix, bit, svbit, ix, bitno, end_bit;
  72. const char *k, *m;
  73. (void) consistency_check;
  74. (void) emit_dot;
  75. #ifdef STRINGMAP_EMIT_DOT
  76. emit_dot(t);
  77. #endif
  78. #ifdef CONSISTENCY_CHECK
  79. consistency_check(t);
  80. #endif
  81. /* If key length wasn't supplied, calculate it. */
  82. if (len == (size_t)-1)
  83. len = strlen(key);
  84. end_bit = len << 3;
  85. /* If tree is empty, create the first node. */
  86. if (!t->root) {
  87. if (!enterf)
  88. return NULL;
  89. t->bp = block_pool_new(t->bp);
  90. t->root = T_new(t->bp, key, len, T_size);
  91. t->count = 1;
  92. return t->root;
  93. }
  94. /* Follow the tree down to what might be the target key. */
  95. if (t->count == 1) {
  96. w = t->root;
  97. svbit = 0;
  98. } else {
  99. w = t->root;
  100. for (;;) {
  101. if (!left_ends(w)) //0 or 1
  102. bit = w->bitno < end_bit ? PEEK_BIT(key, w->bitno) : 0;
  103. else //ends or doesn't end
  104. bit = (w->bitno != end_bit);
  105. svbit = bit ? w->right_is_leaf : w->left_is_leaf;
  106. w = w->lr[bit];
  107. if (svbit)
  108. break;
  109. }
  110. }
  111. /* See if the strings match. If not, set cix to the first bit offset
  112. where there's a difference, and bit to the side on which to put
  113. this leaf. */
  114. sp = (struct T *)w;
  115. m = sp->str;
  116. k = key;
  117. for (cix = 0; ; m++, k++, cix++) {
  118. if (cix>=sp->len || cix>=len) { //we reached the end of one or both strings
  119. if (cix==sp->len && cix==len) { //strings match
  120. //if (!enterf && sp->value == NULL)
  121. // return NULL;
  122. return sp;
  123. }
  124. cix <<= 3;
  125. //put the shorter key to the left
  126. bit = len > sp->len;
  127. break;
  128. }
  129. if (*m != *k) { //the strings have a differing character
  130. cix <<= 3;
  131. //advance cix to the first differing bit
  132. ix = *m ^ *k;
  133. while ((ix & 128) == 0)
  134. ix <<= 1, cix++;
  135. //choose left/right based on the differing bit
  136. bit = PEEK_BIT(key, cix);
  137. break;
  138. }
  139. }
  140. if (!enterf)
  141. return NULL; /* no string found and do not enter */
  142. /* Create new node */
  143. new = block_pool_alloc(t->bp, sizeof *new);
  144. new->right_is_leaf = bit;
  145. new->left_is_leaf = !bit;
  146. new->bitno = cix;
  147. new->lr[bit] = T_new(t->bp, key, len, T_size);
  148. if (t->count++ == 1) {
  149. new->lr[!bit] = t->root;
  150. new->right_is_leaf = 1;
  151. new->left_is_leaf = 1;
  152. t->root = new;
  153. return (struct T *)new->lr[bit];
  154. }
  155. w = t->root;
  156. last = NULL;
  157. for (;;) {
  158. bitno = w->bitno;
  159. if (bitno > cix)
  160. break;
  161. if (!left_ends(w)) { //0 or 1
  162. if (bitno == cix)
  163. break;
  164. svbit = PEEK_BIT(key, bitno);
  165. } else { //ends or doesn't end
  166. //because left is an end, we cannot split it, so we must turn right
  167. svbit = 1;
  168. }
  169. last = w;
  170. w = w->lr[svbit];
  171. if (svbit ? last->right_is_leaf : last->left_is_leaf) {
  172. //w is a leaf, so mark it accordingly in its parent structure
  173. if (!bit)
  174. new->right_is_leaf = 1;
  175. else
  176. new->left_is_leaf = 1;
  177. break;
  178. }
  179. }
  180. new->lr[!bit] = w;
  181. if (last == NULL) {
  182. t->root = new;
  183. } else {
  184. last->lr[svbit] = new;
  185. if (svbit)
  186. last->right_is_leaf = 0;
  187. else
  188. last->left_is_leaf = 0;
  189. }
  190. return (struct T *)new->lr[bit];
  191. }
  192. static int consistency_check_subtree(struct stringmap_node *n) {
  193. uint32_t bitno = n->bitno;
  194. int success = 1;
  195. //make sure bitnos ascend (must ascend unless left ends)
  196. if (!n->left_is_leaf && bitno >= n->lr[0]->bitno) {
  197. printf("Left leaf has bitno >= than parent\n");
  198. success = 0;
  199. }
  200. if (!n->right_is_leaf && bitno >= n->lr[1]->bitno) {
  201. if (left_ends(n) && bitno == n->lr[1]->bitno) {
  202. //fine, there's a shelf here
  203. } else {
  204. printf("Right leaf has bitno >= than parent\n");
  205. success = 0;
  206. }
  207. }
  208. //make sure eponymous bits are set properly
  209. if (n->left_is_leaf) {
  210. struct T *lf = leaf(n, 0);
  211. size_t len = lf->len << 3;
  212. if (len == n->bitno) {
  213. //this is a shelf
  214. } else if (len <= n->bitno) {
  215. printf("Left leaf is too short\n");
  216. success = 0;
  217. } else if (PEEK_BIT(lf->str, n->bitno) == 1) {
  218. printf("Left leaf has incorrect bit\n");
  219. success = 0;
  220. }
  221. }
  222. if (n->right_is_leaf) {
  223. struct T *lf = leaf(n, 1);
  224. size_t len = lf->len << 3;
  225. if (len <= n->bitno) {
  226. printf("Right leaf is too short\n");
  227. success = 0;
  228. } else if (PEEK_BIT(lf->str, n->bitno) == 0 && !left_ends(n)) {
  229. printf("Right leaf has incorrect bit\n");
  230. success = 0;
  231. }
  232. }
  233. if (!success) {
  234. //emit_subtree(n, 0);
  235. abort();
  236. }
  237. //recursively check
  238. return (!n->left_is_leaf ? consistency_check_subtree(n->lr[0]) : 1) &&
  239. (!n->right_is_leaf ? consistency_check_subtree(n->lr[1]) : 1);
  240. }
  241. static int consistency_check(struct stringmap *t) {
  242. if (t->count < 2)
  243. return 1;
  244. return consistency_check_subtree(t->root);
  245. }
  246. //The following can be used to create Graphviz "dot" files to visualize the tree
  247. static void leaf_to_dot(void *lp, FILE *f) {
  248. struct T *leaf = lp;
  249. size_t bit_count = leaf->len << 3;
  250. size_t i;
  251. fputs("\"", f);
  252. #if 1
  253. for (i=0; i<bit_count; i++) {
  254. putc(PEEK_BIT(leaf->str, i) ? '1' : '0', f);
  255. if (((i+1) & 7) == 0)
  256. fputs("\\n", f); //add newlines between bytes
  257. }
  258. putc(' ', f);
  259. #endif
  260. fprintf(f, "(%s)\"\n", leaf->str);
  261. }
  262. static void node_to_dot(struct stringmap_node *n, FILE *f, size_t level) {
  263. //don't draw ridiculously huge trees
  264. if (level > 4)
  265. return;
  266. fprintf(f, "%zu [label=\"[%zu] %u\"]\n", (size_t)n, level, n->bitno);
  267. if (n->left_is_leaf) {
  268. fprintf(f, "%zu -> ", (size_t)n);
  269. leaf_to_dot(n->lr[0], f);
  270. } else {
  271. fprintf(f, "%zu -> %zu \n", (size_t)n, (size_t)n->lr[0]);
  272. node_to_dot(n->lr[0], f, level+1);
  273. }
  274. if (n->right_is_leaf) {
  275. fprintf(f, "%zu -> ", (size_t)n);
  276. leaf_to_dot(n->lr[1], f);
  277. } else {
  278. fprintf(f, "%zu -> %zu \n", (size_t)n, (size_t)n->lr[1]);
  279. node_to_dot(n->lr[1], f, level+1);
  280. }
  281. }
  282. static void stringmap_subtree_to_dot(struct stringmap_node *n, int is_leaf, const char *filename_out) {
  283. FILE *f = fopen(filename_out, "w");
  284. fputs("digraph G {\n", f);
  285. if (is_leaf)
  286. leaf_to_dot(n, f);
  287. else
  288. node_to_dot(n, f, 0);
  289. fputs("}\n", f);
  290. fclose(f);
  291. }
  292. static size_t dot_file_number = 0;
  293. static void emit_subtree(struct stringmap_node *n, int is_leaf) {
  294. char buf[64];
  295. sprintf(buf, "dot/%04zu.dot", dot_file_number++);
  296. stringmap_subtree_to_dot(n, is_leaf, buf);
  297. }
  298. static void emit_dot(struct stringmap *t) {
  299. if (t->count)
  300. emit_subtree(t->root, t->count==1);
  301. }