symbol.c 2.28 KB
Newer Older
1 2 3 4 5 6 7 8
/*
 * Symbol management for the Gnumeric spreadsheet
 *
 * (C) 1998 the Free Software Foundation
 *
 * Author:
 *   Miguel de Icaza (miguel@kernel.org)
 */
9
#include <config.h>
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
#include <glib.h>
#include <string.h>
#include "symbol.h"

static GHashTable *symbol_hash_table;

Symbol *
symbol_lookup (char *str)
{
	Symbol *sym;

	g_return_val_if_fail (str != NULL, NULL);
	sym = (Symbol *) g_hash_table_lookup (symbol_hash_table, str);
	return sym;
}

Symbol *
symbol_lookup_substr (char *buffer, int len)
{
	char *str;
	Symbol *sym;
	
	g_return_val_if_fail (buffer != NULL, NULL);
	str = g_new (char, len + 1);
	strncpy (str, buffer, len);
	str [len] = 0;

	sym = symbol_lookup (str);
	g_free (str);
	
	return sym;
}

43 44 45 46 47 48 49
/*
 * symbol_install
 *
 * @str: the string name
 * @SymbolType: in which hash table we perform the lookup
 * @data: information attached to the symbol
 */
50 51 52 53 54 55 56 57 58 59 60 61 62
Symbol *
symbol_install (char *str, SymbolType type, void *data)
{
	Symbol *sym;

	g_return_val_if_fail (str != NULL, NULL);

	sym = g_new (Symbol, 1);
	sym->ref_count = 1;
	sym->type = type;
	sym->data = data;
	sym->str  = g_strdup (str);
	
63
	g_hash_table_insert (symbol_hash_table, sym->str, sym);
64 65 66 67
	
	return sym;
}

68 69 70 71 72 73
/*
 * symbol_ref:
 * @Sym: The symbol to reference
 *
 * Increments the reference count for the symbol
 */
74 75 76 77 78 79 80 81
void
symbol_ref (Symbol *sym)
{
	g_return_if_fail (sym != NULL);

	sym->ref_count++;
}

82 83 84 85 86 87 88 89
/*
 * symbol_ref_string:
 * @str:  string to be converted to a symbol
 *
 * This looks up the string on the symbol hash table,
 * if it is found, it is references, otherwise a new
 * symbol is created
 */
90 91 92 93 94 95 96 97 98 99 100 101 102
Symbol *
symbol_ref_string (char *str)
{
	Symbol *sym;

	sym = symbol_lookup (str);
	if (sym){
		symbol_ref (sym);
		return sym;
	}
	return symbol_install (str, SYMBOL_STRING, 0);
}

103 104 105 106 107 108 109
/*
 * symbol_unref:
 * @Sym:  The symbol to remove the reference from
 *
 * Unreferences a symbol.  If the count reaches zero, the symbol
 * is deallocated
 */
110 111 112 113
void
symbol_unref (Symbol *sym)
{
	g_return_if_fail (sym != NULL);
114
	g_return_if_fail (sym->ref_count > 0);
115 116 117 118 119 120 121
	
	if (--(sym->ref_count) == 0){
		g_free (sym->str);
		g_free (sym);
	}
}

Arturo Espinosa's avatar
Arturo Espinosa committed
122 123 124 125 126 127
gint
g_strcase_equal (gconstpointer v1, gconstpointer v2)
{
	return strcasecmp ((const gchar*) v1, (const gchar*) v2) == 0;
}

128 129 130
void
symbol_init (void)
{
Arturo Espinosa's avatar
Arturo Espinosa committed
131
	symbol_hash_table = g_hash_table_new (g_str_hash, g_strcase_equal);
132
}