File: stringpool.c

package info (click to toggle)
bock 0.20.2.1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,228 kB
  • ctags: 1,370
  • sloc: ansic: 7,367; java: 5,553; yacc: 963; lex: 392; makefile: 243; sh: 90; perl: 42
file content (93 lines) | stat: -rw-r--r-- 1,962 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/* stringpool.c -- keep track of all string constants in the program
 * Written by Charles Briscoe-Smith; refer to the file LEGAL for details.
 */

/* Interface definitions */

/* Enter a string in the string pool, returning its index.  The string
   is referenced, not copied, into the pool, so the string passed must
   not subsequently be changed.  */
extern int stringpool_intern(const char *);

/* Enter a wide string in the string pool, returning its index.  */
extern int stringpool_intern_wide(const char *);

/* Return the highest string index in the pool, or -1 if the pool
   is empty.  The first index is 0.  */
extern int stringpool_highestindex(void);

/* Return the string at a given string pool index.  */
extern const char *stringpool_fetch(int);


#ifndef SEEN_stringpool_h

#include <stdlib.h>
#include <string.h>
#include "error.h"
#include "xmalloc.h"

static const char **strings=0;
static int next=0;
static int size=10;

int
stringpool_intern_wide(const char *s)
{
	int i;
	int ssize=((int) (unsigned char) s[0])*256 + (int) (unsigned char) s[1];

	for (i=0; i<next; i++) {
		if (memcmp(s, strings[i], 2)==0
		    && memcmp(s, strings[i], ssize*2+2)==0)
		{
			return i;
		}
	}

	if (strings==0) {
		strings=xmalloc(size*sizeof(const char *));
	} else if (next>=size) {
		const char **newstrings;
		newstrings=xmalloc(2*size*sizeof(const char *));
		memcpy(newstrings, strings, size*sizeof(const char *));
		size*=2;
		strings=newstrings;
	}

	if (strings==0) {
		error("Can't expand string pool");
	}

	strings[i=next++]=s;
	return i;
}

int
stringpool_intern(const char *s)
{
	int len=strlen(s);
	char *newstr=xmalloc(len*2+2);
	char *scan=newstr;
	*scan++=(char) len/256;
	*scan++=(char) len%256;
	while (*s) {
		*scan++=0;
		*scan++=*s++;
	}
	return stringpool_intern_wide(newstr);
}

int
stringpool_highestindex(void)
{
	return next-1;
}

const char *
stringpool_fetch(int i)
{
	return strings[i];
}

#endif /* SEEN_stringpool_h */