2 * Licensed under a two-clause BSD-style license.
3 * See LICENSE for details.
11 #include "string_pool.h"
13 typedef struct node_s node_t
;
14 static struct trp_root tree
= { ~0 };
18 struct trp_node children
;
21 /* Create two memory pools: one for node_t, and another for strings */
22 obj_pool_gen(node
, node_t
, 4096);
23 obj_pool_gen(string
, char, 4096);
25 static char *node_value(node_t
*node
)
27 return node
? string_pointer(node
->offset
) : NULL
;
30 static int node_cmp(node_t
*a
, node_t
*b
)
32 return strcmp(node_value(a
), node_value(b
));
35 /* Build a Treap from the node_s structure (a trp_node w/ offset) */
36 trp_gen(static, tree_
, node_t
, children
, node
, node_cmp
);
38 char *pool_fetch(uint32_t entry
)
40 return node_value(node_pointer(entry
));
43 uint32_t pool_intern(char *key
)
45 /* Canonicalize key */
50 key_len
= strlen(key
) + 1;
51 node_t
*node
= node_pointer(node_alloc(1));
52 node
->offset
= string_alloc(key_len
);
53 strcpy(node_value(node
), key
);
54 match
= tree_search(&tree
, node
);
56 tree_insert(&tree
, node
);
62 return node_offset(node
);
65 uint32_t pool_tok_r(char *str
, const char *delim
, char **saveptr
)
67 char *token
= strtok_r(str
, delim
, saveptr
);
68 return token
? pool_intern(token
) : ~0;
71 void pool_print_seq(uint32_t len
, uint32_t *seq
, char delim
, FILE *stream
)
74 for (i
= 0; i
< len
&& ~seq
[i
]; i
++) {
75 fputs(pool_fetch(seq
[i
]), stream
);
76 if (i
< len
- 1 && ~seq
[i
+ 1])
81 uint32_t pool_tok_seq(uint32_t max
, uint32_t *seq
, char *delim
, char *str
)
84 uint32_t length
= 0, token
= str
? pool_tok_r(str
, delim
, &context
) : ~0;
85 while (length
< max
) {
86 seq
[length
++] = token
;
89 token
= pool_tok_r(NULL
, delim
, &context
);
91 seq
[length
? length
- 1 : 0] = ~0;
100 for (node
= 0; node
< node_pool
.size
; node
++) {
101 tree_insert(&tree
, node_pointer(node
));
105 void pool_reset(void)