File: util.c

package info (click to toggle)
fped 0.0%2Br5986-1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 900 kB
  • sloc: ansic: 12,009; yacc: 1,088; sh: 688; lex: 197; makefile: 132
file content (114 lines) | stat: -rw-r--r-- 1,946 bytes parent folder | download
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
/*
 * util.c - Common utility functions
 *
 * Written 2009 by Werner Almesberger
 * Copyright 2009 by Werner Almesberger
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */


#include <stdarg.h>
#include <stdio.h>
#include <string.h>

#include "util.h"



/* ----- printf buffer allocation ------------------------------------------ */


char *stralloc_vprintf(const char *fmt, va_list ap)
{
	va_list aq;
	char *buf;
	int n;

	va_copy(aq, ap);
	n = vsnprintf(NULL, 0, fmt, aq);
	va_end(aq);
	buf = alloc_size(n+1);
	vsnprintf(buf, n+1, fmt, ap);
	return buf;
}


char *stralloc_printf(const char *fmt, ...)
{
	va_list ap;
	char *s;

	va_start(ap, fmt);
	s = stralloc_vprintf(fmt, ap);
	va_end(ap);
	return s;
}


/* ----- identifier syntax check ------------------------------------------- */


int is_id_char(char c, int first) 
{
	if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_')
		return 1;
	if (first)
		return 0;
	return c >= '0' && c <= '9';
}


int is_id(const char *s)
{
	const char *p;

	if (!*s)
		return 0;
	for (p = s; *p; p++)
		if (!is_id_char(*p, s == p))
			return 0;
	return 1;
}


/* ----- unique identifiers ------------------------------------------------ */


static struct unique {
	char *s;
	struct unique *next;
} *uniques = NULL;


/* @@@ consider using rb trees */

const char *unique(const char *s)
{
	struct unique **walk;

	for (walk = &uniques; *walk; walk = &(*walk)->next)
		if (!strcmp(s, (*walk)->s))
			return (*walk)->s;
	*walk = alloc_type(struct unique);
	(*walk)->s = stralloc(s);
	(*walk)->next = NULL;
	return (*walk)->s;
}


void unique_cleanup(void)
{
	struct unique *next;

	while (uniques) {
		next = uniques->next;
		free(uniques->s);
		free(uniques);
		uniques = next;
	}
}