1 /* SPDX-License-Identifier: BSD-3-Clause
2 * Copyright 2016, Olivier MATZ <zer0@droids-corp.org>
14 #include <ecoli_assert.h>
15 #include <ecoli_malloc.h>
16 #include <ecoli_string.h>
18 /* count the number of identical chars at the beginning of 2 strings */
19 size_t ec_strcmp_count(const char *s1, const char *s2)
23 while (s1[i] && s2[i] && s1[i] == s2[i])
29 int ec_str_startswith(const char *s, const char *beginning)
33 len = ec_strcmp_count(s, beginning);
34 if (beginning[len] == '\0')
40 int ec_vasprintf(char **buf, const char *fmt, va_list ap)
48 ret = vsnprintf(&dummy, 1, fmt, aq);
54 *buf = ec_malloc(buflen);
59 ret = vsnprintf(*buf, buflen, fmt, aq);
62 ec_assert_print(ret < buflen, "invalid return value for vsnprintf");
72 int ec_asprintf(char **buf, const char *fmt, ...)
78 ret = ec_vasprintf(buf, fmt, ap);
84 bool ec_str_is_space(const char *s)
94 int ec_str_parse_llint(const char *str, unsigned int base, int64_t min,
95 int64_t max, int64_t *val)
98 int save_errno = errno;
101 *val = strtoll(str, &endptr, base);
103 if ((errno == ERANGE && (*val == LLONG_MAX || *val == LLONG_MIN)) ||
104 (errno != 0 && *val == 0))
126 int ec_str_parse_ullint(const char *str, unsigned int base, uint64_t min,
127 uint64_t max, uint64_t *val)
130 int save_errno = errno;
132 /* since a negative input is silently converted to a positive
133 * one by strtoull(), first check that it is positive */
134 if (strchr(str, '-'))
138 *val = strtoull(str, &endptr, base);
140 if ((errno == ERANGE && *val == ULLONG_MAX) ||
141 (errno != 0 && *val == 0))