Tests: Fix: Use '.logfile' instead of '.log' for test app output
[lttng-tools.git] / src / common / compat / string.hpp
CommitLineData
f5436bfc
MJ
1/*
2 * Copyright (C) 2015 Michael Jeanson <mjeanson@efficios.com>
ab5be9fa 3 * Copyright (C) 2015 Jérémie Galarneau <jeremie.galarneau@efficios.com>
f5436bfc 4 *
ab5be9fa 5 * SPDX-License-Identifier: MIT
f5436bfc 6 *
f5436bfc
MJ
7 */
8
9#ifndef _COMPAT_STRING_H
10#define _COMPAT_STRING_H
11
ec5b87f3 12#include <stdlib.h>
28f23191 13#include <string.h>
f5436bfc
MJ
14
15#ifdef HAVE_STRNLEN
28f23191 16static inline size_t lttng_strnlen(const char *str, size_t max)
f5436bfc
MJ
17{
18 return strnlen(str, max);
19}
20#else
28f23191 21static inline size_t lttng_strnlen(const char *str, size_t max)
f5436bfc
MJ
22{
23 size_t ret;
24 const char *end;
25
e59345cc 26 end = (const char *) memchr(str, 0, max);
f5436bfc
MJ
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
28f23191 39static inline char *lttng_strndup(const char *s, size_t n)
f5436bfc
MJ
40{
41 return strndup(s, n);
42}
43#else
28f23191 44static inline char *lttng_strndup(const char *s, size_t n)
f5436bfc
MJ
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
64803277 60 ret = malloc<char>(navail);
f5436bfc
MJ
61 if (!ret) {
62 goto end;
63 }
64
65 memcpy(ret, s, navail);
66 ret[navail - 1] = '\0';
67end:
68 return ret;
69}
70#endif /* HAVE_STRNDUP */
71
afc5df03
JG
72#ifdef HAVE_FLS
73static inline int lttng_fls(int val)
74{
75 return fls(val);
76}
77#else
78static 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)) {
afc5df03
JG
102 r -= 1;
103 }
104 return r;
105}
106#endif /* HAVE_FLS */
107
ce7fc42f 108#ifdef HAVE_MEMRCHR
28f23191 109static inline void *lttng_memrchr(const void *s, int c, size_t n)
4b223a67 110{
48a40005 111 return (void *) memrchr(s, c, n);
4b223a67
FD
112}
113#else
28f23191 114static inline void *lttng_memrchr(const void *s, int c, size_t n)
4b223a67
FD
115{
116 int i;
e59345cc 117 const char *str = (const char *) s;
28f23191
JG
118 for (i = n - 1; i >= 0; i--) {
119 if (str[i] == (char) c) {
120 return (void *) (str + i);
4b223a67
FD
121 }
122 }
123 return NULL;
124}
125#endif /* HAVE_MEMRCHR */
126
f5436bfc 127#endif /* _COMPAT_STRING_H */
This page took 0.093298 seconds and 5 git commands to generate.