2 * Copyright 1993, 1995 Christopher Seiwald.
4 * This file is part of Jam - see jam.c for Copyright information.
7 * newstr.c - string manipulation routines
9 * To minimize string copying, string creation, copying, and freeing
10 * is done through newstr.
14 * newstr() - return a malloc'ed copy of a string
15 * copystr() - return a copy of a string previously returned by newstr()
16 * freestr() - free a string returned by newstr() or copystr()
17 * donestr() - free string tables
19 * Once a string is passed to newstr(), the returned string is readonly.
21 * This implementation builds a hash table of all strings, so that multiple
22 * calls of newstr() on the same string allocate memory for the string once.
23 * Strings are never actually freed.
25 * 11/04/02 (seiwald) - const-ing for string literals
31 typedef const char *STRING
;
33 static struct hash
*strhash
= 0;
34 static int strtotal
= 0;
38 * newstr() - return a malloc'ed copy of a string
40 const char *newstr (const char *string
) {
41 STRING str
, *s
= &str
;
43 if (!strhash
) strhash
= hashinit(sizeof(STRING
), "strings");
45 if (hashenter(strhash
, (HASHDATA
**)&s
)) {
46 int l
= strlen(string
);
47 char *m
= (char *)malloc(l
+1);
48 if (DEBUG_MEM
) printf("newstr: allocating %d bytes\n", l
+1);
50 memcpy(m
, string
, l
+1);
58 * copystr() - return a copy of a string previously returned by newstr()
60 const char *copystr (const char *s
) {
66 * freestr() - free a string returned by newstr() or copystr()
68 void freestr (const char *s
) {
73 * donestr() - free string tables
77 if (DEBUG_MEM
) printf("%dK in strings\n", strtotal
/1024);