1 /**
2  * @file util.h
3  *
4  * @brief Various wrappers around some utility functions.
5  * @author David Suárez
6  * @author Chris Lightfoot
7  * @date Sun, 21 Oct 2018 18:41:11 +0200
8  *
9  * Copyright (c) 2018-2019 David Suárez.
10  * Email: david.sephirot@gmail.com
11  *
12  * Copyright (c) 2003 Chris Lightfoot.
13  * Email: chris@ex-parrot.com; WWW: http://www.ex-parrot.com/~chris/
14  *
15  */
16 
17 #ifndef __UTIL_H__
18 #define __UTIL_H__
19 
20 #ifdef HAVE_CONFIG_H
21     #include <config.h>
22 #endif
23 
24 #include <stddef.h>
25 
26 /**
27  * @brief Malloc, and abort if fails.
28  *
29  * @param n size of memory to malloc
30  * @return pointer to the allocated mem
31  */
32 void *xmalloc(size_t n);
33 
34 /**
35  * @brief Calloc, and abort if fails.
36  *
37  * @param n number of elements to alloc
38  * @param m size of elements
39  * @return pointer to the allocated mem
40  */
41 void *xcalloc(size_t n, size_t m);
42 
43 /**
44  * @brief Realloc, and abort if fails.
45  *
46  * @param w pointer to the memory
47  * @param n size of memory to recalloc
48  * @return pointer to the reallocated mem
49  */
50 void *xrealloc(void *w, size_t n);
51 
52 /**
53  * @brief Free, ignoring a passed NULL value.
54  *
55  * @param v the memory to free
56  */
57 void xfree(void *v);
58 
59 /**
60  * @brief Strdup, and abort if fails.
61  *
62  * @param n original string
63  * @return duplicated string
64  */
65 char *xstrdup(const char *s);
66 
67 /**
68  * @brief Locate needle, of length n_len, in haystack, of length h_len, returning NULL.
69  *
70  * @param haystack string to search in
71  * @param size of haystack
72  * @param needle string to search for
73  * @param nlen size of needle
74  * @return a pointer to the found string or NULL if nothing found
75  */
76 
77 unsigned char *memstr(const unsigned char *haystack, const size_t hlen, const unsigned char *needle, const size_t nlen);
78 
79 /**
80  * @brief Sleep for x nanoseconds
81  *
82  * @param nanosecs nanosecs to sleep
83  */
84 void xnanosleep(long nanosecs);
85 
86 /**
87  * @brief Composes a file path from a base path and a filename.
88  *
89  * @param base the base path
90  * @param filename the filename
91  * @return the joined file path
92  */
93 char* compose_path(const char* base, const char* filename);
94 
95 /**
96  * @brief Extract the filename from a pathname.
97  *
98  * @param pathname the pathname
99  * @return a pointer to the beginning of filename in pathname; NULL if not found
100  */
101 const char* xbasename(const char* pathname);
102 
103 /**
104  * @brief Make P point to a new struct S, initialised as if in static storage (like = {0}).
105  */
106 #define alloc_struct(S, p)  p = xmalloc(sizeof *p); memset(p, 0, sizeof *p);
107 
108 #endif /* __UTIL_H__ */
109