Fix: common: poll: compat_poll_wait never finishes
[lttng-tools.git] / src / common / compat / string.h
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
12#include <string.h>
ec5b87f3 13#include <stdlib.h>
f5436bfc
MJ
14
15#ifdef HAVE_STRNLEN
16static inline
17size_t lttng_strnlen(const char *str, size_t max)
18{
19 return strnlen(str, max);
20}
21#else
22static inline
23size_t lttng_strnlen(const char *str, size_t max)
24{
25 size_t ret;
26 const char *end;
27
28 end = memchr(str, 0, max);
29
30 if (end) {
31 ret = (size_t) (end - str);
32 } else {
33 ret = max;
34 }
35
36 return ret;
37}
38#endif /* HAVE_STRNLEN */
39
40#ifdef HAVE_STRNDUP
41static inline
42char *lttng_strndup(const char *s, size_t n)
43{
44 return strndup(s, n);
45}
46#else
47static inline
48char *lttng_strndup(const char *s, size_t n)
49{
50 char *ret;
51 size_t navail;
52
53 if (!s) {
54 ret = NULL;
55 goto end;
56 }
57
58 /* min() */
59 navail = strlen(s) + 1;
60 if ((n + 1) < navail) {
61 navail = n + 1;
62 }
63
64 ret = malloc(navail);
65 if (!ret) {
66 goto end;
67 }
68
69 memcpy(ret, s, navail);
70 ret[navail - 1] = '\0';
71end:
72 return ret;
73}
74#endif /* HAVE_STRNDUP */
75
afc5df03
JG
76#ifdef HAVE_FLS
77static inline int lttng_fls(int val)
78{
79 return fls(val);
80}
81#else
82static inline int lttng_fls(int val)
83{
84 int r = 32;
85 unsigned int x = (unsigned int) val;
86
87 if (!x)
88 return 0;
89 if (!(x & 0xFFFF0000U)) {
90 x <<= 16;
91 r -= 16;
92 }
93 if (!(x & 0xFF000000U)) {
94 x <<= 8;
95 r -= 8;
96 }
97 if (!(x & 0xF0000000U)) {
98 x <<= 4;
99 r -= 4;
100 }
101 if (!(x & 0xC0000000U)) {
102 x <<= 2;
103 r -= 2;
104 }
105 if (!(x & 0x80000000U)) {
afc5df03
JG
106 r -= 1;
107 }
108 return r;
109}
110#endif /* HAVE_FLS */
111
4b223a67
FD
112#if HAVE_MEMRCHR
113static inline
114void *lttng_memrchr(const void *s, int c, size_t n)
115{
116 return memrchr(s, c, n);
117}
118#else
119static inline
120void *lttng_memrchr(const void *s, int c, size_t n)
121{
122 int i;
123 const char *str = s;
124 for (i = n-1; i >= 0; i--) {
125 if (str[i] == (char)c) {
126 return (void *)(str+i);
127 }
128 }
129 return NULL;
130}
131#endif /* HAVE_MEMRCHR */
132
f5436bfc 133#endif /* _COMPAT_STRING_H */
This page took 0.040727 seconds and 4 git commands to generate.