string-util: add new strdupcspn()/strdupspn()
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.
This commit is contained in:
+1
-4
@@ -862,7 +862,6 @@ int executable_is_script(const char *path, char **interpreter) {
|
||||
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);
|
||||
@@ -914,9 +913,7 @@ int get_proc_field(const char *filename, const char *pattern, const char *termin
|
||||
t--;
|
||||
}
|
||||
|
||||
len = strcspn(t, terminator);
|
||||
|
||||
f = strndup(t, len);
|
||||
f = strdupcspn(t, terminator);
|
||||
if (!f)
|
||||
return -ENOMEM;
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ int gethostname_full(GetHostnameFlags flags, char **ret) {
|
||||
}
|
||||
|
||||
if (FLAGS_SET(flags, GET_HOSTNAME_SHORT))
|
||||
buf = strndup(s, strcspn(s, "."));
|
||||
buf = strdupcspn(s, ".");
|
||||
else
|
||||
buf = strdup(s);
|
||||
if (!buf)
|
||||
|
||||
@@ -1201,3 +1201,19 @@ size_t strspn_from_end(const char *str, const char *accept) {
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -240,3 +240,6 @@ bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok);
|
||||
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);
|
||||
|
||||
Reference in New Issue
Block a user