Commit | Line | Data |
---|---|---|
9a7f65a3 | 1 | /* |
0235b0db | 2 | * SPDX-License-Identifier: MIT |
9a7f65a3 | 3 | * |
0235b0db | 4 | * Copyright (C) 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com> |
9a7f65a3 JI |
5 | */ |
6 | ||
0235b0db MJ |
7 | #ifndef _BABELTRACE_COMPAT_STRING_H |
8 | #define _BABELTRACE_COMPAT_STRING_H | |
9 | ||
9a7f65a3 | 10 | #include <string.h> |
832a0779 | 11 | #include <stdlib.h> |
9a7f65a3 | 12 | |
832a0779 MJ |
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 | ||
9a7f65a3 | 74 | #endif /* _BABELTRACE_COMPAT_STRING_H */ |