1 // SPDX-License-Identifier: MIT
2 // Copyright (C) 2018 Luc Van Oostenryck
3
4 #include "utils.h"
5 #include "allocate.h"
6 #include <string.h>
7 #include <stdarg.h>
8 #include <stdio.h>
9
10
hexval(unsigned int c)11 unsigned int hexval(unsigned int c)
12 {
13 int retval = 256;
14 switch (c) {
15 case '0'...'9':
16 retval = c - '0';
17 break;
18 case 'a'...'f':
19 retval = c - 'a' + 10;
20 break;
21 case 'A'...'F':
22 retval = c - 'A' + 10;
23 break;
24 }
25 return retval;
26 }
27
xmemdup(const void * src,size_t len)28 void *xmemdup(const void *src, size_t len)
29 {
30 return memcpy(__alloc_bytes(len), src, len);
31 }
32
xstrdup(const char * src)33 char *xstrdup(const char *src)
34 {
35 return xmemdup(src, strlen(src) + 1);
36 }
37
xvasprintf(const char * fmt,va_list ap)38 char *xvasprintf(const char *fmt, va_list ap)
39 {
40 va_list ap2;
41 char *str;
42 int n;
43
44 va_copy(ap2, ap);
45 n = vsnprintf(NULL, 0, fmt, ap2) + 1;
46 va_end(ap2);
47
48 str = __alloc_bytes(n);
49 vsnprintf(str, n, fmt, ap);
50
51 return str;
52 }
53
xasprintf(const char * fmt,...)54 char *xasprintf(const char *fmt, ...)
55 {
56 va_list ap;
57 char *str;
58
59 va_start(ap, fmt);
60 str = xvasprintf(fmt, ap);
61 va_end(ap);
62
63 return str;
64 }
65