comparison lwlib/lw_strpool.c @ 495:5b8871fd7503

Merged previous lwcc development branch into mainline.
author William Astle <lost@l-w.ca>
date Mon, 05 Aug 2019 21:27:09 -0600
parents 670ea8f90212
children
comparison
equal deleted inserted replaced
493:6073f4a33475 495:5b8871fd7503
1 /*
2 lwlib/lw_strpool.c
3
4 Copyright © 2013 William Astle
5
6 This file is part of LWTOOLS.
7
8 LWTOOLS is free software: you can redistribute it and/or modify it under the
9 terms of the GNU General Public License as published by the Free Software
10 Foundation, either version 3 of the License, or (at your option) any later
11 version.
12
13 This program is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 more details.
17
18 You should have received a copy of the GNU General Public License along with
19 this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include "lw_alloc.h"
26 #include "lw_string.h"
27 #include "lw_strpool.h"
28
29 struct lw_strpool *lw_strpool_create(void)
30 {
31 struct lw_strpool *sp;
32
33 sp = lw_alloc(sizeof(struct lw_strpool));
34 sp -> nstrs = 0;
35 sp -> strs = NULL;
36 return sp;
37 }
38
39 extern void lw_strpool_free(struct lw_strpool *sp)
40 {
41 int i;
42
43 for (i = 0; i < sp -> nstrs; i++)
44 lw_free(sp -> strs[i]);
45 lw_free(sp -> strs);
46 lw_free(sp);
47 }
48
49 char *lw_strpool_strdup(struct lw_strpool *sp, const char *s)
50 {
51 int i;
52
53 if (!s)
54 return NULL;
55
56 /* first do a fast scan for a pointer match */
57 for (i = 0; i < sp -> nstrs; i++)
58 if (sp -> strs[i] == s)
59 return sp -> strs[i];
60
61 /* no match - do a slow scan for a string match */
62 for (i = 0; i < sp -> nstrs; i++)
63 if (strcmp(sp -> strs[i], s) == 0)
64 return sp -> strs[i];
65
66 /* no match - create a new string entry */
67 sp -> strs = lw_realloc(sp -> strs, sizeof(char *) * (sp -> nstrs + 1));
68 sp -> strs[sp -> nstrs] = lw_strdup(s);
69 sp -> nstrs++;
70 return sp -> strs[sp -> nstrs - 1];
71 }