From 97f9f0b699316ba60009b395948a712ec0b671d2 Mon Sep 17 00:00:00 2001 From: Brian Ashworth Date: Fri, 27 Dec 2019 23:33:55 -0500 Subject: parse_color: return success + drop fallback color This is the first in a series of commits to refactor the color handling in sway. This changes parse_color to return whether it was success and no longer uses 0xFFFFFFFF as the fallback color. This also verifies that the string actually contains a valid hexadecimal number along with the length checks. In the process of altering the calls to parse_color, I also took the opportunity to heavily refactor swaybar's ipc_parse_colors function. This allowed for several lines of duplicated code to be removed. --- common/util.c | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) (limited to 'common/util.c') diff --git a/common/util.c b/common/util.c index c0324b2f..84ebab99 100644 --- a/common/util.c +++ b/common/util.c @@ -1,4 +1,5 @@ #define _POSIX_C_SOURCE 200809L +#include #include #include #include @@ -13,21 +14,21 @@ int wrap(int i, int max) { return ((i % max) + max) % max; } -uint32_t parse_color(const char *color) { +bool parse_color(const char *color, uint32_t *result) { if (color[0] == '#') { ++color; } - int len = strlen(color); - if (len != 6 && len != 8) { - sway_log(SWAY_DEBUG, "Invalid color %s, defaulting to color 0xFFFFFFFF", color); - return 0xFFFFFFFF; + if ((len != 6 && len != 8) || !isxdigit(color[0]) || !isxdigit(color[1])) { + return false; } - uint32_t res = (uint32_t)strtoul(color, NULL, 16); - if (strlen(color) == 6) { - res = (res << 8) | 0xFF; + char *ptr; + uint32_t parsed = strtoul(color, &ptr, 16); + if (*ptr != '\0') { + return false; } - return res; + *result = len == 6 ? ((parsed << 8) | 0xFF) : parsed; + return true; } bool parse_boolean(const char *boolean, bool current) { -- cgit v1.2.3-54-g00ecf