isl_input.c: read_defined_var_list: avoid double free on error
[isl.git] / isl_name.c
blob8e902db99f42433fa4ea8c36f127b55dee52a9bd
1 /*
2 * Copyright 2008-2009 Katholieke Universiteit Leuven
4 * Use of this software is governed by the GNU LGPLv2.1 license
6 * Written by Sven Verdoolaege, K.U.Leuven, Departement
7 * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
8 */
10 #include <string.h>
11 #include "isl_name.h"
13 struct isl_name *isl_name_alloc(struct isl_ctx *ctx, const char *s)
15 const char *copy = strdup(s);
16 struct isl_name *name;
18 if (!copy)
19 return NULL;
20 name = isl_alloc_type(ctx, struct isl_name);
21 if (!name)
22 goto error;
24 name->ref = 1;
25 name->name = copy;
27 return name;
28 error:
29 free((char *)copy);
30 return NULL;
33 static int isl_name_has_name(const void *entry, const void *val)
35 struct isl_name *name = (struct isl_name *)entry;
36 const char *s = (const char *)val;
38 return !strcmp(name->name, s);
41 struct isl_name *isl_name_get(struct isl_ctx *ctx, const char *name)
43 struct isl_hash_table_entry *entry;
44 uint32_t name_hash;
46 name_hash = isl_hash_string(isl_hash_init(), name);
47 entry = isl_hash_table_find(ctx, &ctx->name_hash, name_hash,
48 isl_name_has_name, name, 1);
49 if (!entry)
50 return NULL;
51 if (entry->data)
52 return isl_name_copy(ctx, entry->data);
53 entry->data = isl_name_alloc(ctx, name);
54 if (!entry->data)
55 ctx->name_hash.n--;
56 return entry->data;
59 struct isl_name *isl_name_copy(struct isl_ctx *ctx, struct isl_name *name)
61 if (!name)
62 return NULL;
64 name->ref++;
65 return name;
68 static int isl_name_eq(const void *entry, const void *name)
70 return entry == name;
73 void isl_name_free(struct isl_ctx *ctx, struct isl_name *name)
75 uint32_t name_hash;
76 struct isl_hash_table_entry *entry;
78 if (!name)
79 return;
81 if (--name->ref > 0)
82 return;
84 name_hash = isl_hash_string(isl_hash_init(), name->name);
85 entry = isl_hash_table_find(ctx, &ctx->name_hash, name_hash,
86 isl_name_eq, name, 0);
87 isl_assert(ctx, entry, return);
88 isl_hash_table_remove(ctx, &ctx->name_hash, entry);
90 free((char *)name->name);
91 free(name);