From 0efb3c61a9575eede8984f362dfa6cd0b7562f4a Mon Sep 17 00:00:00 2001 From: Phil Jones Date: Tue, 6 Dec 2022 11:51:41 +0000 Subject: Add config file unit tests and fix some bugs. --- src/color.c | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) (limited to 'src/color.c') diff --git a/src/color.c b/src/color.c index 3fd9516..4b6b356 100644 --- a/src/color.c +++ b/src/color.c @@ -1,3 +1,4 @@ +#include #include #include #include "color.h" @@ -10,15 +11,22 @@ struct color hex_to_color(const char *hex) } uint32_t val = 0; + int64_t tmp; size_t len = strlen(hex); + errno = 0; if (len == 3) { char str[] = { hex[0], hex[0], hex[1], hex[1], hex[2], hex[2], '\0'}; - val = strtol(str, NULL, 16); + char *endptr; + tmp = strtol(str, &endptr, 16); + if (errno || *endptr != '\0' || tmp < 0) { + return (struct color) { -1, -1, -1, -1 }; + } + val = tmp; val <<= 8; val |= 0xFFu; } else if (len == 4) { @@ -28,13 +36,28 @@ struct color hex_to_color(const char *hex) hex[2], hex[2], hex[3], hex[3], '\0'}; - val = strtol(str, NULL, 16); + char *endptr; + tmp = strtol(str, &endptr, 16); + if (errno || *endptr != '\0' || tmp < 0) { + return (struct color) { -1, -1, -1, -1 }; + } + val = tmp; } else if (len == 6) { - val = strtol(hex, NULL, 16); + char *endptr; + tmp = strtol(hex, &endptr, 16); + if (errno || *endptr != '\0' || tmp < 0) { + return (struct color) { -1, -1, -1, -1 }; + } + val = tmp; val <<= 8; val |= 0xFFu; } else if (len == 8) { - val = strtol(hex, NULL, 16); + char *endptr; + tmp = strtol(hex, &endptr, 16); + if (errno || *endptr != '\0' || tmp < 0) { + return (struct color) { -1, -1, -1, -1 }; + } + val = tmp; } else { return (struct color) { -1, -1, -1, -1 }; } -- cgit v1.2.3