fix: use O_CLOEXEC to prevent fds from leaking through other threads
[libjh.git] / string.c
1 // Copyright (2013) Jann Horn <jann@thejh.net>
2 // This code is licensed under the AGPLv3.
3
4 #include <string.h>
5
6 HEADER #define streq(a,b) (!strcmp((a),(b)))
7
8 PUBLIC_FN int count_char_occurences(char *s, char c) {
9   int n=0;
10   while (*s) {
11     if (*s==c) n++;
12     s++;
13   }
14   return n;
15 }
16
17 // memcpy plus terminating nullbyte
18 PUBLIC_FN void *memcpyn(void *d, const void *s, size_t n) {
19   memcpy(d, s, n);
20   char *d_ = d;
21   d_[n] = '\0';
22   return d;
23 }
24
25 // Wipe out whitespace characters at the end of str using nullbytes.
26 PUBLIC_FN void trim_end(char *str, char *whitespace) {
27   for (char *p = str+strlen(str)-1; p>=str; p--) {
28     if (!strchr(whitespace, *p)) break;
29     *p = '\0';
30     p--;
31   }
32 }
33
34 PUBLIC_FN int ends_with(char *str, char *sub) {
35   size_t str_len = strlen(str);
36   size_t sub_len = strlen(sub);
37   if (sub_len>str_len) return 0;
38   return streq(str+str_len-sub_len, sub);
39 }