Root/util.c

Source at commit 5fdea0e99a2e8543a59d508cf28e1f2ff3607f18 created 4 years 10 months ago.
By Werner Almesberger, gui_canvas.c (key_press_event): make / rotate through packages as well
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
25char *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
40char *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
55int 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
65int 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
81static struct unique {
82    char *s;
83    struct unique *next;
84} *uniques = NULL;
85
86
87/* @@@ consider using rb trees */
88
89const 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
103void 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

Archive Download this file

Branches:
master



interactive