util: add split_pair() for splitting foo=bar strings

This commit is contained in:
Lennart Poettering 2013-07-18 20:22:29 +02:00
parent 2f5df74a5e
commit d4ac85c6f6
3 changed files with 56 additions and 0 deletions

View file

@ -5946,3 +5946,34 @@ void parse_user_at_host(char *arg, char **user, char **host) {
*user = arg;
}
}
int split_pair(const char *s, const char *sep, char **l, char **r) {
char *x, *a, *b;
assert(s);
assert(sep);
assert(l);
assert(r);
if (isempty(sep))
return -EINVAL;
x = strstr(s, sep);
if (!x)
return -EINVAL;
a = strndup(s, x - s);
if (!a)
return -ENOMEM;
b = strdup(x + strlen(sep));
if (!b) {
free(a);
return -ENOMEM;
}
*l = a;
*r = b;
return 0;
}

View file

@ -735,3 +735,5 @@ static inline void _reset_locale_(struct _locale_struct_ *s) {
bool id128_is_valid(const char *s) _pure_;
void parse_user_at_host(char *arg, char **user, char **host);
int split_pair(const char *s, const char *sep, char **l, char **r);

View file

@ -521,6 +521,28 @@ static void test_parse_user_at_host(void) {
assert_se(streq(host, "mikescomputer"));
}
static void test_split_pair(void) {
_cleanup_free_ char *a = NULL, *b = NULL;
assert_se(split_pair("", "", &a, &b) == -EINVAL);
assert_se(split_pair("foo=bar", "", &a, &b) == -EINVAL);
assert_se(split_pair("", "=", &a, &b) == -EINVAL);
assert_se(split_pair("foo=bar", "=", &a, &b) >= 0);
assert_se(streq(a, "foo"));
assert_se(streq(b, "bar"));
free(a);
free(b);
assert_se(split_pair("==", "==", &a, &b) >= 0);
assert_se(streq(a, ""));
assert_se(streq(b, ""));
free(a);
free(b);
assert_se(split_pair("===", "==", &a, &b) >= 0);
assert_se(streq(a, ""));
assert_se(streq(b, "="));
}
int main(int argc, char *argv[]) {
test_streq_ptr();
test_first_word();
@ -555,6 +577,7 @@ int main(int argc, char *argv[]) {
test_strextend();
test_strrep();
test_parse_user_at_host();
test_split_pair();
return 0;
}