2 * Copyright 1993, 1995 Christopher Seiwald.
4 * This file is part of Jam - see jam.c for Copyright information.
8 * newstr.c - string manipulation routines
10 * To minimize string copying, string creation, copying, and freeing
11 * is done through newstr.
15 * newstr() - return a malloc'ed copy of a string
16 * copystr() - return a copy of a string previously returned by newstr()
17 * freestr() - free a string returned by newstr() or copystr()
18 * donestr() - free string tables
20 * Once a string is passed to newstr(), the returned string is readonly.
22 * This implementation builds a hash table of all strings, so that multiple
23 * calls of newstr() on the same string allocate memory for the string once.
24 * Strings are never actually freed.
26 * 11/04/02 (seiwald) - const-ing for string literals
33 typedef const char *STRING
;
35 static struct hash
*strhash
= 0;
36 static int strtotal
= 0;
40 * newstr() - return a malloc'ed copy of a string
42 const char *newstr (const char *string
) {
43 STRING str
, *s
= &str
;
45 if (!strhash
) strhash
= hashinit(sizeof(STRING
), "strings");
47 if (hashenter(strhash
, (HASHDATA
**)&s
)) {
48 int l
= strlen(string
);
49 char *m
= (char *)malloc(l
+1);
51 if (DEBUG_MEM
) printf("newstr: allocating %d bytes\n", l
+1);
53 memcpy(m
, string
, l
+1);
61 * copystr() - return a copy of a string previously returned by newstr()
63 const char *copystr (const char *s
) {
69 * freestr() - free a string returned by newstr() or copystr()
71 void freestr (const char *s
) {
76 * donestr() - free string tables
80 if (DEBUG_MEM
) printf("%dK in strings\n", strtotal
/1024);