a1503b2928f3d6bf28bebe1ed41091c05aced4bd
[babeltrace.git] / src / compat / string.h
1 /*
2 * SPDX-License-Identifier: MIT
3 *
4 * Copyright (C) 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
5 */
6
7 #ifndef _BABELTRACE_COMPAT_STRING_H
8 #define _BABELTRACE_COMPAT_STRING_H
9
10 #include <string.h>
11 #include <stdlib.h>
12
13 #ifdef HAVE_STRNLEN
14 static inline
15 size_t bt_strnlen(const char *str, size_t max)
16 {
17 return strnlen(str, max);
18 }
19 #else
20 static inline
21 size_t bt_strnlen(const char *str, size_t max)
22 {
23 size_t ret;
24 const char *end;
25
26 end = memchr(str, 0, max);
27
28 if (end) {
29 ret = (size_t) (end - str);
30 } else {
31 ret = max;
32 }
33
34 return ret;
35 }
36 #endif /* HAVE_STRNLEN */
37
38 #ifdef HAVE_STRNDUP
39 static inline
40 char *bt_strndup(const char *s, size_t n)
41 {
42 return strndup(s, n);
43 }
44 #else
45 static inline
46 char *bt_strndup(const char *s, size_t n)
47 {
48 char *ret;
49 size_t navail;
50
51 if (!s) {
52 ret = NULL;
53 goto end;
54 }
55
56 /* min() */
57 navail = strlen(s) + 1;
58 if ((n + 1) < navail) {
59 navail = n + 1;
60 }
61
62 ret = malloc(navail);
63 if (!ret) {
64 goto end;
65 }
66
67 memcpy(ret, s, navail);
68 ret[navail - 1] = '\0';
69 end:
70 return ret;
71 }
72 #endif /* HAVE_STRNDUP */
73
74 #endif /* _BABELTRACE_COMPAT_STRING_H */
This page took 0.031085 seconds and 4 git commands to generate.