]> git.ozlabs.org Git - ponghero.git/blob - stdrusty.h
Add wiimote.c simple test.
[ponghero.git] / stdrusty.h
1 #ifndef _STDRUSTY_H
2 #define _STDRUSTY_H
3 #include <stdbool.h>
4 #include <string.h>
5 #include <stdint.h>
6 #include <stddef.h>
7
8 /* Is A == B ? */
9 #define streq(a,b) (strcmp((a),(b)) == 0)
10
11 /* Does A start with B ? */
12 #define strstarts(a,b) (strncmp((a),(b),strlen(b)) == 0)
13
14 /* Does A end in B ? */
15 static inline bool strends(const char *a, const char *b)
16 {
17         if (strlen(a) < strlen(b))
18                 return false;
19
20         return streq(a + strlen(a) - strlen(b), b);
21 }
22
23 #define ___stringify(x) #x
24 #define __stringify(x)          ___stringify(x)
25
26 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
27
28 /* Upper bound to sprintf this simple type?  Each 3 bits < 1 digit. */
29 #define CHAR_SIZE(type) (((sizeof(type)*CHAR_BIT + 2) / 3) + 1)
30
31 typedef uint32_t u32;
32 typedef uint16_t u16;
33 typedef uint8_t u8;
34
35 /* Convenient wrappers for malloc and realloc.  Use them. */
36 #define new(type) ((type *)malloc_nofail(sizeof(type)))
37 #define new_array(type, num) realloc_array((type *)0, (num))
38 #define realloc_array(ptr, num) ((__typeof__(ptr))_realloc_array((ptr), sizeof((*ptr)), (num)))
39
40 void *malloc_nofail(size_t size);
41 void *realloc_nofail(void *ptr, size_t size);
42 void *_realloc_array(void *ptr, size_t size, size_t num);
43
44 void barf(const char *fmt, ...) __attribute__((noreturn, format(printf,1,2)));
45 void barf_perror(const char *fmt, ...)
46         __attribute__((noreturn, format(printf,1,2)));
47
48 /* This version adds one byte (for nul term) */
49 void *grab_file(const char *filename, unsigned long *size);
50 void release_file(void *data, unsigned long size);
51
52 /* For writing daemons, based on Stevens. */
53 void daemonize(void);
54
55 /* Signal handling: returns fd to listen on. */
56 int signal_to_fd(int signal);
57 void close_signal(int fd);
58
59 /* from the Linux Kernel:
60  * min()/max() macros that also do
61  * strict type-checking.. See the
62  * "unnecessary" pointer comparison.
63  */
64 #define min(x,y) ({ \
65         typeof(x) _x = (x);     \
66         typeof(y) _y = (y);     \
67         (void) (&_x == &_y);            \
68         _x < _y ? _x : _y; })
69
70 #define max(x,y) ({ \
71         typeof(x) _x = (x);     \
72         typeof(y) _y = (y);     \
73         (void) (&_x == &_y);            \
74         _x > _y ? _x : _y; })
75
76 /* Delete (by memmove) elements of an array */
77 #define delete_arr(p, len, off, num) \
78         _delete_arr((p), (len), (off), (num), sizeof(*p))
79 void _delete_arr(void *p, unsigned len, unsigned off, unsigned num, size_t s);
80
81 /* Write/read this much data. */
82 bool write_all(int fd, const void *data, unsigned long size);
83 bool read_all(int fd, void *data, unsigned long size);
84
85 #endif /* _STDRUSTY_H */