Root/eeshow/misc/util.h

Source at commit fe6d3a9e8504da158b00ed44ceeae54f6b96dfc4 created 7 years 4 months ago.
By Werner Almesberger, eeshow/misc/util.h (strbegins): !strncmp(s, prefix, strlen(prefix))
1/*
2 * misc/util.h - Common utility functions
3 *
4 * Written 2016 by Werner Almesberger
5 * Copyright 2016 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#ifndef MISC_UTIL_H
15#define MISC_UTIL_H
16
17#include <stdbool.h>
18#include <stdlib.h>
19#include <stdio.h>
20#include <string.h>
21
22
23#define alloc_size(s) \
24    ({ void *alloc_size_tmp = malloc(s); \
25    if (!alloc_size_tmp) { \
26        perror("malloc"); \
27        exit(1); \
28    } \
29    alloc_size_tmp; })
30
31#define alloc_type(t) ((t *) alloc_size(sizeof(t)))
32#define alloc_type_n(t, n) ((t *) alloc_size(sizeof(t) * (n)))
33
34
35#define realloc_size(p, s) \
36    ({ void *alloc_size_tmp = realloc((p), (s)); \
37    if (!alloc_size_tmp) { \
38        perror("realloc"); \
39        exit(1); \
40    } \
41    alloc_size_tmp; })
42
43#define realloc_type_n(p, t, n) ((t *) realloc_size((p), sizeof(t) * (n)))
44
45
46#define stralloc(s) \
47    ({ char *stralloc_tmp = strdup(s); \
48    if (!stralloc_tmp) { \
49        perror("strdup"); \
50        exit(1); \
51    } \
52    stralloc_tmp; })
53
54
55#define ARRAY_ELEMENTS(a) (sizeof(a) / sizeof(a[0]))
56#define ARRAY_END(a) ((a) + ARRAY_ELEMENTS(a))
57
58
59#define swap(a, b) \
60    ({ typeof(a) _tmp = (a); a = (b); b = _tmp; })
61
62#define sign1(x) ((x) < 0 ? -1 : 1)
63
64#define unsupported(s) \
65    fprintf(stderr, __FILE__ ":%d: unsupported: " s "\n", __LINE__)
66
67
68static inline bool strbegins(const char *s, const char *prefix)
69{
70    return !strncmp(s, prefix, strlen(prefix));
71}
72
73#endif /* !MISC_UTIL_H */
74

Archive Download this file

Branches:
master



interactive