File: newstr.c

package info (click to toggle)
ftjam 2.5.2-1.1
  • links: PTS
  • area: main
  • in suites: bullseye, buster, jessie, jessie-kfreebsd, lenny, sid, squeeze, stretch, wheezy
  • size: 1,216 kB
  • ctags: 1,237
  • sloc: ansic: 7,226; sh: 2,751; yacc: 443; makefile: 121
file content (98 lines) | stat: -rwxr-xr-x 2,000 bytes parent folder | download | duplicates (2)
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
94
95
96
97
98
/*
 * Copyright 1993, 1995 Christopher Seiwald.
 *
 * This file is part of Jam - see jam.c for Copyright information.
 */

/*
 * newstr.c - string manipulation routines
 *
 * To minimize string copying, string creation, copying, and freeing
 * is done through newstr.
 *
 * External functions:
 *
 *    newstr() - return a malloc'ed copy of a string
 *    copystr() - return a copy of a string previously returned by newstr()
 *    freestr() - free a string returned by newstr() or copystr()
 *    donestr() - free string tables
 *
 * Once a string is passed to newstr(), the returned string is readonly.
 *
 * This implementation builds a hash table of all strings, so that multiple 
 * calls of newstr() on the same string allocate memory for the string once.
 * Strings are never actually freed.
 *
 * 11/04/02 (seiwald) - const-ing for string literals
 */

# include "jam.h"
# include "newstr.h"
# include "hash.h"

typedef const char *STRING;

static struct hash *strhash = 0;
static int strtotal = 0;

/*
 * newstr() - return a malloc'ed copy of a string
 */

const char *
newstr( const char *string )
{
	STRING str, *s = &str;

	if( !strhash )
	    strhash = hashinit( sizeof( STRING ), "strings" );

	*s = string;

	if( hashenter( strhash, (HASHDATA **)&s ) )
	{
	    int l = strlen( string );
	    char *m = (char *)malloc( l + 1 );

	    if (DEBUG_MEM)
		    printf("newstr: allocating %d bytes\n", l + 1 );

	    strtotal += l + 1;
	    memcpy( m, string, l + 1 );
	    *s = m;
	}

	return *s;
}

/*
 * copystr() - return a copy of a string previously returned by newstr()
 */

const char *
copystr( const char *s )
{
	return s;
}

/*
 * freestr() - free a string returned by newstr() or copystr()
 */

void
freestr( const char *s )
{
}

/*
 * donestr() - free string tables
 */

void
donestr()
{
	hashdone( strhash );

	if( DEBUG_MEM )
	    printf( "%dK in strings\n", strtotal / 1024 );
}