stringstore.c

changeset 73
401322031c7e
child 74
60cb620a0341
equal deleted inserted replaced
72:7e69e5f7a013 73:401322031c7e
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
20
21 StringId stringstore_find(const char *str)
22 {
23 Rb_node node;
24 int found=0;
25
26 if(stringstore==NULL)
27 return STRINGID_NONE;
28
29 node=rb_find_key_n(stringstore, str, &found);
30
31 if(!found)
32 return STRINGID_NONE;
33
34 return (StringId)node;
35 }
36
37
38 StringId stringstore_alloc(const char *str)
39 {
40 Rb_node node=(Rb_node)stringstore_find(str);
41 char *s;
42
43 if(node!=NULL){
44 node->v.ival++;
45 return node;
46 }
47
48 if(stringstore==NULL){
49 stringstore=make_rb();
50 if(stringstore==NULL)
51 return STRINGID_NONE;
52 }
53
54 s=scopy(str);
55
56 if(s==NULL)
57 return STRINGID_NONE;
58
59 node=rb_insert(stringstore, s, NULL);
60
61 if(node==NULL)
62 return STRINGID_NONE;
63
64 node->v.ival=1;
65
66 return (StringId)node;
67 }
68
69
70 void stringstore_free(StringId id)
71 {
72 Rb_node node=(Rb_node)id;
73
74 if(node==NULL){
75 warn("Attempt to free un-allocated string from stringstore.");
76 return;
77 }
78
79 if(node->v.ival<=0){
80 warn("Stringstore reference count corrupted.");
81 return;
82 }
83
84 node->v.ival--;
85
86 if(node->v.ival==0){
87 char *s=(char*)(node->k.key);
88 rb_delete_node(node);
89 free(s);
90 }
91 }
92

mercurial