Root/
Source at commit ad2c07f49c326140a0839e6453fb68bb48745781 created 9 years 2 months ago. By Werner Almesberger, dump.c (order_vecs): don't trip over vectors with deferred resolution | |
---|---|
1 | /* |
2 | * util.c - Common utility functions |
3 | * |
4 | * Written 2009 by Werner Almesberger |
5 | * Copyright 2009 by Werner Almesberger |
6 | * |
7 | * This program is free software; you can redistribute it and/or modify |
8 | * it under the terms of the GNU General Public License as published by |
9 | * the Free Software Foundation; either version 2 of the License, or |
10 | * (at your option) any later version. |
11 | */ |
12 | |
13 | |
14 | #include <stdarg.h> |
15 | #include <stdio.h> |
16 | #include <string.h> |
17 | |
18 | #include "util.h" |
19 | |
20 | |
21 | |
22 | /* ----- printf buffer allocation ------------------------------------------ */ |
23 | |
24 | |
25 | char *stralloc_vprintf(const char *fmt, va_list ap) |
26 | { |
27 | va_list aq; |
28 | char *buf; |
29 | int n; |
30 | |
31 | va_copy(aq, ap); |
32 | n = vsnprintf(NULL, 0, fmt, aq); |
33 | va_end(aq); |
34 | buf = alloc_size(n+1); |
35 | vsnprintf(buf, n+1, fmt, ap); |
36 | return buf; |
37 | } |
38 | |
39 | |
40 | char *stralloc_printf(const char *fmt, ...) |
41 | { |
42 | va_list ap; |
43 | char *s; |
44 | |
45 | va_start(ap, fmt); |
46 | s = stralloc_vprintf(fmt, ap); |
47 | va_end(ap); |
48 | return s; |
49 | } |
50 | |
51 | |
52 | /* ----- identifier syntax check ------------------------------------------- */ |
53 | |
54 | |
55 | int is_id_char(char c, int first) |
56 | { |
57 | if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_') |
58 | return 1; |
59 | if (first) |
60 | return 0; |
61 | return c >= '0' && c <= '9'; |
62 | } |
63 | |
64 | |
65 | int is_id(const char *s) |
66 | { |
67 | const char *p; |
68 | |
69 | if (!*s) |
70 | return 0; |
71 | for (p = s; *p; p++) |
72 | if (!is_id_char(*p, s == p)) |
73 | return 0; |
74 | return 1; |
75 | } |
76 | |
77 | |
78 | /* ----- unique identifiers ------------------------------------------------ */ |
79 | |
80 | |
81 | static struct unique { |
82 | char *s; |
83 | struct unique *next; |
84 | } *uniques = NULL; |
85 | |
86 | |
87 | /* @@@ consider using rb trees */ |
88 | |
89 | const char *unique(const char *s) |
90 | { |
91 | struct unique **walk; |
92 | |
93 | for (walk = &uniques; *walk; walk = &(*walk)->next) |
94 | if (!strcmp(s, (*walk)->s)) |
95 | return (*walk)->s; |
96 | *walk = alloc_type(struct unique); |
97 | (*walk)->s = stralloc(s); |
98 | (*walk)->next = NULL; |
99 | return (*walk)->s; |
100 | } |
101 | |
102 | |
103 | void unique_cleanup(void) |
104 | { |
105 | struct unique *next; |
106 | |
107 | while (uniques) { |
108 | next = uniques->next; |
109 | free(uniques->s); |
110 | free(uniques); |
111 | uniques = next; |
112 | } |
113 | } |
114 | |
115 |
Branches:
master