cosmetix in lz unpacker
[k8jam.git] / src / newstr.c
bloba82b4a34d34650167f1d706e0c3ee82ac3385356
1 /*
2 * Copyright 1993, 1995 Christopher Seiwald.
4 * This file is part of Jam - see jam.c for Copyright information.
5 */
6 /*
7 * newstr.c - string manipulation routines
9 * To minimize string copying, string creation, copying, and freeing
10 * is done through newstr.
12 * External functions:
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
27 #include "jam.h"
28 #include "newstr.h"
29 #include "hash.h"
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");
44 *s = string;
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);
49 strtotal += l+1;
50 memcpy(m, string, l+1);
51 *s = m;
53 return *s;
58 * copystr() - return a copy of a string previously returned by newstr()
60 const char *copystr (const char *s) {
61 return s;
66 * freestr() - free a string returned by newstr() or copystr()
68 void freestr (const char *s) {
73 * donestr() - free string tables
75 void donestr (void) {
76 hashdone(strhash);
77 if (DEBUG_MEM) printf("%dK in strings\n", strtotal/1024);