add meson support
[protos/libecoli.git] / src / ecoli_string.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright 2016, Olivier MATZ <zer0@droids-corp.org>
3  */
4
5 #include <stdarg.h>
6 #include <stddef.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <ctype.h>
10
11 #include <ecoli_assert.h>
12 #include <ecoli_malloc.h>
13 #include <ecoli_string.h>
14
15 /* count the number of identical chars at the beginning of 2 strings */
16 size_t ec_strcmp_count(const char *s1, const char *s2)
17 {
18         size_t i = 0;
19
20         while (s1[i] && s2[i] && s1[i] == s2[i])
21                 i++;
22
23         return i;
24 }
25
26 int ec_str_startswith(const char *s, const char *beginning)
27 {
28         size_t len;
29
30         len = ec_strcmp_count(s, beginning);
31         if (beginning[len] == '\0')
32                 return 1;
33
34         return 0;
35 }
36
37 int ec_vasprintf(char **buf, const char *fmt, va_list ap)
38 {
39         char dummy;
40         int buflen, ret;
41         va_list aq;
42
43         va_copy(aq, ap);
44         *buf = NULL;
45         ret = vsnprintf(&dummy, 1, fmt, aq);
46         va_end(aq);
47         if (ret < 0)
48                 return ret;
49
50         buflen = ret + 1;
51         *buf = ec_malloc(buflen);
52         if (*buf == NULL)
53                 return -1;
54
55         va_copy(aq, ap);
56         ret = vsnprintf(*buf, buflen, fmt, aq);
57         va_end(aq);
58
59         ec_assert_print(ret < buflen, "invalid return value for vsnprintf");
60         if (ret < 0) {
61                 free(*buf);
62                 *buf = NULL;
63                 return -1;
64         }
65
66         return ret;
67 }
68
69 int ec_asprintf(char **buf, const char *fmt, ...)
70 {
71         va_list ap;
72         int ret;
73
74         va_start(ap, fmt);
75         ret = ec_vasprintf(buf, fmt, ap);
76         va_end(ap);
77
78         return ret;
79 }
80
81 bool ec_str_is_space(const char *s)
82 {
83         while (*s) {
84                 if (!isspace(*s))
85                         return false;
86                 s++;
87         }
88         return true;
89 }