Sun, 20 Jun 2004 13:46:00 +0200
trunk: changeset 1585
Oops.
73 | 1 | /* |
2 | * libtu/stringstore.c | |
3 | * | |
4 | * Copyright (c) Tuomo Valkonen 2004. | |
5 | * | |
6 | * You may distribute and modify this library under the terms of either | |
7 | * the Clarified Artistic License or the GNU LGPL, version 2.1 or later. | |
8 | */ | |
9 | ||
10 | #include <stdlib.h> | |
11 | ||
12 | #include "misc.h" | |
13 | #include "output.h" | |
14 | #include "rb.h" | |
15 | #include "stringstore.h" | |
16 | ||
17 | ||
18 | static Rb_node stringstore=NULL; | |
19 | ||
74 | 20 | |
21 | const char *stringstore_get(StringId id) | |
22 | { | |
23 | return (const char*)(((Rb_node)id)->k.key); | |
24 | } | |
25 | ||
73 | 26 | |
27 | StringId stringstore_find(const char *str) | |
28 | { | |
29 | Rb_node node; | |
30 | int found=0; | |
31 | ||
32 | if(stringstore==NULL) | |
33 | return STRINGID_NONE; | |
34 | ||
35 | node=rb_find_key_n(stringstore, str, &found); | |
36 | ||
37 | if(!found) | |
38 | return STRINGID_NONE; | |
39 | ||
40 | return (StringId)node; | |
41 | } | |
42 | ||
43 | ||
44 | StringId stringstore_alloc(const char *str) | |
45 | { | |
46 | Rb_node node=(Rb_node)stringstore_find(str); | |
47 | char *s; | |
48 | ||
49 | if(node!=NULL){ | |
50 | node->v.ival++; | |
51 | return node; | |
52 | } | |
53 | ||
54 | if(stringstore==NULL){ | |
55 | stringstore=make_rb(); | |
56 | if(stringstore==NULL) | |
57 | return STRINGID_NONE; | |
58 | } | |
59 | ||
60 | s=scopy(str); | |
61 | ||
62 | if(s==NULL) | |
63 | return STRINGID_NONE; | |
64 | ||
65 | node=rb_insert(stringstore, s, NULL); | |
66 | ||
67 | if(node==NULL) | |
68 | return STRINGID_NONE; | |
69 | ||
70 | node->v.ival=1; | |
71 | ||
72 | return (StringId)node; | |
73 | } | |
74 | ||
75 | ||
76 | void stringstore_free(StringId id) | |
77 | { | |
78 | Rb_node node=(Rb_node)id; | |
79 | ||
80 | if(node==NULL){ | |
81 | warn("Attempt to free un-allocated string from stringstore."); | |
82 | return; | |
83 | } | |
84 | ||
85 | if(node->v.ival<=0){ | |
86 | warn("Stringstore reference count corrupted."); | |
87 | return; | |
88 | } | |
89 | ||
90 | node->v.ival--; | |
91 | ||
92 | if(node->v.ival==0){ | |
93 | char *s=(char*)(node->k.key); | |
94 | rb_delete_node(node); | |
95 | free(s); | |
96 | } | |
97 | } | |
98 |