77238181350e33d72297069cd7eab53d91564060
[protos/libecoli.git] / libecoli / 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
10 #include <ecoli_assert.h>
11 #include <ecoli_malloc.h>
12 #include <ecoli_string.h>
13
14 /* count the number of identical chars at the beginning of 2 strings */
15 size_t ec_strcmp_count(const char *s1, const char *s2)
16 {
17         size_t i = 0;
18
19         while (s1[i] && s2[i] && s1[i] == s2[i])
20                 i++;
21
22         return i;
23 }
24
25 int ec_str_startswith(const char *s, const char *beginning)
26 {
27         size_t len;
28
29         len = ec_strcmp_count(s, beginning);
30         if (beginning[len] == '\0')
31                 return 1;
32
33         return 0;
34 }
35
36 int ec_vasprintf(char **buf, const char *fmt, va_list ap)
37 {
38         char dummy;
39         int buflen, ret;
40         va_list aq;
41
42         va_copy(aq, ap);
43         *buf = NULL;
44         ret = vsnprintf(&dummy, 1, fmt, aq);
45         va_end(aq);
46         if (ret < 0)
47                 return ret;
48
49         buflen = ret + 1;
50         *buf = ec_malloc(buflen);
51         if (*buf == NULL)
52                 return -1;
53
54         va_copy(aq, ap);
55         ret = vsnprintf(*buf, buflen, fmt, aq);
56         va_end(aq);
57
58         ec_assert_print(ret < buflen, "invalid return value for vsnprintf");
59         if (ret < 0) {
60                 free(*buf);
61                 *buf = NULL;
62                 return -1;
63         }
64
65         return ret;
66 }
67
68 int ec_asprintf(char **buf, const char *fmt, ...)
69 {
70         va_list ap;
71         int ret;
72
73         va_start(ap, fmt);
74         ret = ec_vasprintf(buf, fmt, ap);
75         va_end(ap);
76
77         return ret;
78 }