aboutsummaryrefslogtreecommitdiffhomepage
path: root/intern.c
blob: 59fa135623af422fd129f9cb29d7e2f548ed593c (plain)
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/** \file intern.c

    Library for pooling common strings

*/
#include "config.h"


#include <stdlib.h>
#include <stdio.h>
#include <wchar.h>
#include <unistd.h>

#include "fallback.h"
#include "util.h"

#include "wutil.h"
#include "common.h"
#include "intern.h"

/**
   Table of interned strings
*/
static hash_table_t *intern_table=0;

/**
   Table of static interned strings
*/
static hash_table_t *intern_static_table=0;

const wchar_t *intern( const wchar_t *in )
{
	const wchar_t *res=0;
	
	if( !in )
		return 0;
	
	if( !intern_table )
	{
		intern_table = malloc( sizeof( hash_table_t ) );
		if( !intern_table )
		{
			DIE_MEM();
		}
		hash_init( intern_table, &hash_wcs_func, &hash_wcs_cmp );
	}
	
	if( intern_static_table )
	{
		res = hash_get( intern_static_table, in );
	}
	
	if( !res )
	{
		res = hash_get( intern_table, in );
		
		if( !res )
		{
			res = wcsdup( in );
			if( !res )
			{
				DIE_MEM();
			}
			
			hash_put( intern_table, res, res );
		}
	}
	
	return res;
}

const wchar_t *intern_static( const wchar_t *in )
{
	const wchar_t *res=0;
	
	if( !in )
		return 0;
	
	if( !intern_static_table )
	{
		intern_static_table = malloc( sizeof( hash_table_t ) );
		if( !intern_static_table )
		{
			DIE_MEM();			
		}
		hash_init( intern_static_table, &hash_wcs_func, &hash_wcs_cmp );
	}
	
	res = hash_get( intern_static_table, in );
	
	if( !res )
	{
		res = in;
		hash_put( intern_static_table, res, res );
	}
	
	return res;
}

/**
   Free the specified key/value pair. Should only be called by intern_free_all at shutdown
*/
static void clear_value( void *key, void *data )
{
	debug( 3,  L"interned string: '%ls'", data );	
	free( (void *)data );
}

void intern_free_all()
{
	if( intern_table )
	{
		hash_foreach( intern_table, &clear_value );		
		hash_destroy( intern_table );		
		free( intern_table );
		intern_table=0;		
	}

	if( intern_static_table )
	{
		hash_destroy( intern_static_table );		
		free( intern_static_table );
		intern_static_table=0;		
	}
	
}