time-util: Introduce parse_sec_def_infinity

This works like parse_sec() but defaults to USEC_INFINITY when passed an
empty string or only whitespace.

Also introduce config_parse_sec_def_infinity, which can be used to parse
config options using this function.

This is useful for time options that use "infinity" for default and that
can be reset by unsetting them.

Introduce a test case to ensure it works as expected.
This commit is contained in:
Filipe Brandenburger 2019-01-23 19:48:54 -08:00
parent 93e4163e91
commit 7b61ce3c44
5 changed files with 33 additions and 0 deletions

View File

@ -1031,6 +1031,15 @@ int parse_sec_fix_0(const char *t, usec_t *ret) {
return r;
}
int parse_sec_def_infinity(const char *t, usec_t *ret) {
t += strspn(t, WHITESPACE);
if (isempty(t)) {
*ret = USEC_INFINITY;
return 0;
}
return parse_sec(t, ret);
}
static const char* extract_nsec_multiplier(const char *p, nsec_t *multiplier) {
static const struct {
const char *suffix;

View File

@ -112,6 +112,7 @@ int parse_timestamp(const char *t, usec_t *usec);
int parse_sec(const char *t, usec_t *usec);
int parse_sec_fix_0(const char *t, usec_t *usec);
int parse_sec_def_infinity(const char *t, usec_t *usec);
int parse_time(const char *t, usec_t *usec, usec_t default_unit);
int parse_nsec(const char *t, nsec_t *nsec);

View File

@ -506,6 +506,7 @@ DEFINE_PARSER(unsigned, unsigned, safe_atou);
DEFINE_PARSER(double, double, safe_atod);
DEFINE_PARSER(nsec, nsec_t, parse_nsec);
DEFINE_PARSER(sec, usec_t, parse_sec);
DEFINE_PARSER(sec_def_infinity, usec_t, parse_sec_def_infinity);
DEFINE_PARSER(mode, mode_t, parse_mode);
int config_parse_iec_size(const char* unit,

View File

@ -127,6 +127,7 @@ CONFIG_PARSER_PROTOTYPE(config_parse_string);
CONFIG_PARSER_PROTOTYPE(config_parse_path);
CONFIG_PARSER_PROTOTYPE(config_parse_strv);
CONFIG_PARSER_PROTOTYPE(config_parse_sec);
CONFIG_PARSER_PROTOTYPE(config_parse_sec_def_infinity);
CONFIG_PARSER_PROTOTYPE(config_parse_nsec);
CONFIG_PARSER_PROTOTYPE(config_parse_mode);
CONFIG_PARSER_PROTOTYPE(config_parse_warn_compat);

View File

@ -85,6 +85,26 @@ static void test_parse_sec_fix_0(void) {
assert_se(u == USEC_INFINITY);
}
static void test_parse_sec_def_infinity(void) {
usec_t u;
log_info("/* %s */", __func__);
assert_se(parse_sec_def_infinity("5s", &u) >= 0);
assert_se(u == 5 * USEC_PER_SEC);
assert_se(parse_sec_def_infinity("", &u) >= 0);
assert_se(u == USEC_INFINITY);
assert_se(parse_sec_def_infinity(" ", &u) >= 0);
assert_se(u == USEC_INFINITY);
assert_se(parse_sec_def_infinity("0s", &u) >= 0);
assert_se(u == 0);
assert_se(parse_sec_def_infinity("0", &u) >= 0);
assert_se(u == 0);
assert_se(parse_sec_def_infinity(" 0", &u) >= 0);
assert_se(u == 0);
assert_se(parse_sec_def_infinity("-5s", &u) < 0);
}
static void test_parse_time(void) {
usec_t u;
@ -472,6 +492,7 @@ int main(int argc, char *argv[]) {
test_parse_sec();
test_parse_sec_fix_0();
test_parse_sec_def_infinity();
test_parse_time();
test_parse_nsec();
test_format_timespan(1);