These combine strndup() + strspn()/strcspn() into one.
There are a bunch of strndupa() calls that could use similar treatment
(or should be converted to strdup[c]spn(), but this commit doesn't
bother with that.
int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
_cleanup_free_ char *status = NULL;
char *t, *f;
- size_t len;
int r;
assert(terminator);
t--;
}
- len = strcspn(t, terminator);
-
- f = strndup(t, len);
+ f = strdupcspn(t, terminator);
if (!f)
return -ENOMEM;
}
if (FLAGS_SET(flags, GET_HOSTNAME_SHORT))
- buf = strndup(s, strcspn(s, "."));
+ buf = strdupcspn(s, ".");
else
buf = strdup(s);
if (!buf)
return n;
}
+
+char *strdupspn(const char *a, const char *accept) {
+ if (isempty(a) || isempty(accept))
+ return strdup("");
+
+ return strndup(a, strspn(a, accept));
+}
+
+char *strdupcspn(const char *a, const char *reject) {
+ if (isempty(a))
+ return strdup("");
+ if (isempty(reject))
+ return strdup(a);
+
+ return strndup(a, strcspn(a, reject));
+}
char *string_replace_char(char *str, char old_char, char new_char);
size_t strspn_from_end(const char *str, const char *accept);
+
+char *strdupspn(const char *a, const char *accept);
+char *strdupcspn(const char *a, const char *reject);
assert(rule[0]);
_cleanup_free_ char *rulename = NULL;
- const char *e;
int r;
- e = strchrnul(rule + 1, rule[0]);
- rulename = strndup(rule + 1, e - rule - 1);
+ rulename = strdupcspn(rule + 1, CHAR_TO_STR(rule[0]));
if (!rulename)
return log_oom();
/* If that didn't work, strip off the
* other layouts from the entry, too */
- x = strndup(a[1], strcspn(a[1], ","));
+ x = strdupcspn(a[1], ",");
+ if (!x)
+ return -ENOMEM;
if (startswith_comma(c->x11_layout, x))
matching = 1;
}
static int extract_pretty(const char *path, const char *suffix, char **ret) {
_cleanup_free_ char *name = NULL;
const char *p;
- size_t n;
assert(path);
assert(ret);
p = last_path_component(path);
- n = strcspn(p, "/");
- name = strndup(p, n);
+ name = strdupcspn(p, "/");
if (!name)
return -ENOMEM;
weblink += strspn(weblink, " \t");
/* Cut out till next whitespace/newline */
- url = strndup(weblink, strcspn(weblink, WHITESPACE));
+ url = strdupcspn(weblink, WHITESPACE);
if (!url)
return log_oom();