dte test coverage


Directory: ./
File: src/util/xmalloc.h
Date: 2025-07-02 15:21:29
Exec Total Coverage
Lines: 23 23 100.0%
Functions: 9 9 100.0%
Branches: 0 0 -%

Line Branch Exec Source
1 #ifndef UTIL_XMALLOC_H
2 #define UTIL_XMALLOC_H
3
4 #include <stddef.h>
5 #include <string.h>
6 #include "arith.h"
7 #include "macros.h"
8 #include "xstring.h"
9
10 #define XMEMDUP(ptr) xmemdup(ptr, sizeof(*ptr))
11 #define xrenew(mem, n) xreallocarray(mem, (n), sizeof(*mem))
12
13 void *xmalloc(size_t size) XMALLOC ALLOC_SIZE(1);
14 void *xcalloc(size_t nmemb, size_t size) XMALLOC ALLOC_SIZE(1, 2);
15 void *xrealloc(void *ptr, size_t size) RETURNS_NONNULL WARN_UNUSED_RESULT ALLOC_SIZE(2);
16 char *xstrdup(const char *str) XSTRDUP;
17 char *xasprintf(const char *format, ...) PRINTF(1) XMALLOC;
18
19 XMALLOC ALLOC_SIZE(1)
20 3696 static inline void *xcalloc1(size_t size)
21 {
22 3696 return xcalloc(1, size);
23 }
24
25 XMALLOC ALLOC_SIZE(1, 2)
26 2013 static inline void *xmallocarray(size_t nmemb, size_t size)
27 {
28 2013 return xmalloc(xmul(nmemb, size));
29 }
30
31 RETURNS_NONNULL WARN_UNUSED_RESULT ALLOC_SIZE(2, 3)
32 13844 static inline void *xreallocarray(void *ptr, size_t nmemb, size_t size)
33 {
34 13844 return xrealloc(ptr, xmul(nmemb, size));
35 }
36
37 NONNULL_ARGS_AND_RETURN ALLOC_SIZE(2)
38 4176 static inline void *xmemdup(const void *ptr, size_t size)
39 {
40 4176 return memcpy(xmalloc(size), ptr, size);
41 }
42
43 NONNULL_ARGS_AND_RETURN
44 1812 static inline void *xmemjoin(const void *p1, size_t n1, const void *p2, size_t n2)
45 {
46 1812 char *joined = xmalloc(xadd(n1, n2));
47 1812 xmempcpy2(joined, p1, n1, p2, n2);
48 1812 return joined;
49 }
50
51 NONNULL_ARGS_AND_RETURN
52 1 static inline void *xmemjoin3 (
53 const void *p1, size_t n1,
54 const void *p2, size_t n2,
55 const void *p3, size_t n3
56 ) {
57 1 char *joined = xmalloc(xadd3(n1, n2, n3));
58 1 xmempcpy3(joined, p1, n1, p2, n2, p3, n3);
59 1 return joined;
60 }
61
62 XSTRDUP
63 1416 static inline char *xstrjoin(const char *s1, const char *s2)
64 {
65 1416 return xmemjoin(s1, strlen(s1), s2, strlen(s2) + 1);
66 }
67
68 // Return a null-terminated copy of the first `size` bytes of `str`
69 XSTRDUP
70 338 static inline char *xstrcut(const char *str, size_t size)
71 {
72 338 return xmemjoin(str, size, "", 1);
73 }
74
75 // Return a null-terminated copy of the substring between `pos` and `end`
76 XSTRDUP
77 88 static inline char *xstrslice(const char *str, size_t pos, size_t end)
78 {
79 88 BUG_ON(pos > end);
80 88 return xstrcut(str + pos, end - pos);
81 }
82
83 #endif
84