Commit | Line | Data |
---|---|---|
f5436bfc MJ |
1 | /* |
2 | * Copyright (C) 2015 Michael Jeanson <mjeanson@efficios.com> | |
3 | * | |
4 | * Permission is hereby granted, free of charge, to any person obtaining a copy | |
5 | * of this software and associated documentation files (the "Software"), to deal | |
6 | * in the Software without restriction, including without limitation the rights | |
7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
8 | * copies of the Software, and to permit persons to whom the Software is | |
9 | * furnished to do so, subject to the following conditions: | |
10 | * | |
11 | * The above copyright notice and this permission notice shall be included in | |
12 | * all copies or substantial portions of the Software. | |
13 | * | |
14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
20 | * SOFTWARE. | |
21 | */ | |
22 | ||
23 | #ifndef _COMPAT_STRING_H | |
24 | #define _COMPAT_STRING_H | |
25 | ||
26 | #include <string.h> | |
27 | ||
28 | #ifdef HAVE_STRNLEN | |
29 | static inline | |
30 | size_t lttng_strnlen(const char *str, size_t max) | |
31 | { | |
32 | return strnlen(str, max); | |
33 | } | |
34 | #else | |
35 | static inline | |
36 | size_t lttng_strnlen(const char *str, size_t max) | |
37 | { | |
38 | size_t ret; | |
39 | const char *end; | |
40 | ||
41 | end = memchr(str, 0, max); | |
42 | ||
43 | if (end) { | |
44 | ret = (size_t) (end - str); | |
45 | } else { | |
46 | ret = max; | |
47 | } | |
48 | ||
49 | return ret; | |
50 | } | |
51 | #endif /* HAVE_STRNLEN */ | |
52 | ||
53 | #ifdef HAVE_STRNDUP | |
54 | static inline | |
55 | char *lttng_strndup(const char *s, size_t n) | |
56 | { | |
57 | return strndup(s, n); | |
58 | } | |
59 | #else | |
60 | static inline | |
61 | char *lttng_strndup(const char *s, size_t n) | |
62 | { | |
63 | char *ret; | |
64 | size_t navail; | |
65 | ||
66 | if (!s) { | |
67 | ret = NULL; | |
68 | goto end; | |
69 | } | |
70 | ||
71 | /* min() */ | |
72 | navail = strlen(s) + 1; | |
73 | if ((n + 1) < navail) { | |
74 | navail = n + 1; | |
75 | } | |
76 | ||
77 | ret = malloc(navail); | |
78 | if (!ret) { | |
79 | goto end; | |
80 | } | |
81 | ||
82 | memcpy(ret, s, navail); | |
83 | ret[navail - 1] = '\0'; | |
84 | end: | |
85 | return ret; | |
86 | } | |
87 | #endif /* HAVE_STRNDUP */ | |
88 | ||
89 | #endif /* _COMPAT_STRING_H */ |