Root/
| 1 | /* |
| 2 | * util.h - Utility functions |
| 3 | * |
| 4 | * Copyright 2012 by Werner Almesberger |
| 5 | * |
| 6 | * This program is free software; you can redistribute it and/or modify |
| 7 | * it under the terms of the GNU General Public License as published by |
| 8 | * the Free Software Foundation; either version 2 of the License, or |
| 9 | * (at your option) any later version. |
| 10 | */ |
| 11 | |
| 12 | |
| 13 | #include <string.h> |
| 14 | #include <glib.h> |
| 15 | |
| 16 | #include "util.h" |
| 17 | |
| 18 | |
| 19 | static GTree *tree = NULL; |
| 20 | |
| 21 | |
| 22 | static gint comp(gconstpointer a, gconstpointer b) |
| 23 | { |
| 24 | return strcmp(a, b); |
| 25 | } |
| 26 | |
| 27 | |
| 28 | const char *unique(const char *s) |
| 29 | { |
| 30 | char *u; |
| 31 | |
| 32 | if (!tree) |
| 33 | tree = g_tree_new(comp); |
| 34 | u = g_tree_lookup(tree, s); |
| 35 | if (!u) { |
| 36 | u = strdup(s); |
| 37 | g_tree_insert(tree, u, u); |
| 38 | } |
| 39 | return u; |
| 40 | } |
| 41 | |
| 42 | |
| 43 | const char *unique_n(const char *s, int n) |
| 44 | { |
| 45 | char *tmp, *u; |
| 46 | |
| 47 | if (!tree) |
| 48 | tree = g_tree_new(comp); |
| 49 | tmp = stralloc_n(s, n); |
| 50 | u = g_tree_lookup(tree, tmp); |
| 51 | if (u) { |
| 52 | free(tmp); |
| 53 | return u; |
| 54 | } else { |
| 55 | g_tree_insert(tree, tmp, tmp); |
| 56 | return tmp; |
| 57 | } |
| 58 | } |
| 59 |
Branches:
master
