Tests: Fix: Use '.logfile' instead of '.log' for test app output
[lttng-tools.git] / src / common / compat / string.hpp
1 /*
2 * Copyright (C) 2015 Michael Jeanson <mjeanson@efficios.com>
3 * Copyright (C) 2015 Jérémie Galarneau <jeremie.galarneau@efficios.com>
4 *
5 * SPDX-License-Identifier: MIT
6 *
7 */
8
9 #ifndef _COMPAT_STRING_H
10 #define _COMPAT_STRING_H
11
12 #include <stdlib.h>
13 #include <string.h>
14
15 #ifdef HAVE_STRNLEN
16 static inline size_t lttng_strnlen(const char *str, size_t max)
17 {
18 return strnlen(str, max);
19 }
20 #else
21 static inline size_t lttng_strnlen(const char *str, size_t max)
22 {
23 size_t ret;
24 const char *end;
25
26 end = (const char *) 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 char *lttng_strndup(const char *s, size_t n)
40 {
41 return strndup(s, n);
42 }
43 #else
44 static inline char *lttng_strndup(const char *s, size_t n)
45 {
46 char *ret;
47 size_t navail;
48
49 if (!s) {
50 ret = NULL;
51 goto end;
52 }
53
54 /* min() */
55 navail = strlen(s) + 1;
56 if ((n + 1) < navail) {
57 navail = n + 1;
58 }
59
60 ret = malloc<char>(navail);
61 if (!ret) {
62 goto end;
63 }
64
65 memcpy(ret, s, navail);
66 ret[navail - 1] = '\0';
67 end:
68 return ret;
69 }
70 #endif /* HAVE_STRNDUP */
71
72 #ifdef HAVE_FLS
73 static inline int lttng_fls(int val)
74 {
75 return fls(val);
76 }
77 #else
78 static inline int lttng_fls(int val)
79 {
80 int r = 32;
81 unsigned int x = (unsigned int) val;
82
83 if (!x)
84 return 0;
85 if (!(x & 0xFFFF0000U)) {
86 x <<= 16;
87 r -= 16;
88 }
89 if (!(x & 0xFF000000U)) {
90 x <<= 8;
91 r -= 8;
92 }
93 if (!(x & 0xF0000000U)) {
94 x <<= 4;
95 r -= 4;
96 }
97 if (!(x & 0xC0000000U)) {
98 x <<= 2;
99 r -= 2;
100 }
101 if (!(x & 0x80000000U)) {
102 r -= 1;
103 }
104 return r;
105 }
106 #endif /* HAVE_FLS */
107
108 #ifdef HAVE_MEMRCHR
109 static inline void *lttng_memrchr(const void *s, int c, size_t n)
110 {
111 return (void *) memrchr(s, c, n);
112 }
113 #else
114 static inline void *lttng_memrchr(const void *s, int c, size_t n)
115 {
116 int i;
117 const char *str = (const char *) s;
118 for (i = n - 1; i >= 0; i--) {
119 if (str[i] == (char) c) {
120 return (void *) (str + i);
121 }
122 }
123 return NULL;
124 }
125 #endif /* HAVE_MEMRCHR */
126
127 #endif /* _COMPAT_STRING_H */
This page took 0.04562 seconds and 4 git commands to generate.