Skip to content

Commit

Permalink
Move color parse message out of hex parser
Browse files Browse the repository at this point in the history
Simplifies parsing code, gives a better message and reduces responsibility of
last parser to report errors.

Signed-off-by: Tin Švagelj <tin.svagelj@live.com>
  • Loading branch information
Caellian committed May 25, 2024
1 parent 6f98039 commit 6a39ebf
Showing 1 changed file with 4 additions and 7 deletions.
11 changes: 4 additions & 7 deletions src/colours.cc
Original file line number Diff line number Diff line change
Expand Up @@ -83,17 +83,13 @@ std::optional<Colour> parse_hex_color(const std::string &color) {
}
return -1;
};
const auto none = [&]() {
NORM_ERR("can't parse hex color '%s' (%d)", name, len);
return std::nullopt;
};

uint8_t argb[4] = {0xff, 0, 0, 0};
if (len == 3 || len == 4) {
bool skip_alpha = (len == 3);
for (size_t i = 0; i < len; i++) {
int nib = hex_nibble_value(name[i]);
if (nib < 0) { return none(); }
if (nib < 0) return std::nullopt;
// Duplicate the nibble, so "#abc" -> 0xaa, 0xbb, 0xcc
int val = (nib << 4) + nib;

Expand All @@ -104,13 +100,13 @@ std::optional<Colour> parse_hex_color(const std::string &color) {
for (size_t i = 0; i + 1 < len; i += 2) {
int nib1 = hex_nibble_value(name[i]);
int nib2 = hex_nibble_value(name[i + 1]);
if (nib1 < 0 || nib2 < 0) { return none(); }
if (nib1 < 0 || nib2 < 0) return std::nullopt;
int val = (nib1 << 4) + nib2;

argb[skip_alpha + i / 2] = val;
}
} else {
return none();
return std::nullopt;
}

return Colour(argb[1], argb[2], argb[3], argb[0]);
Expand All @@ -128,6 +124,7 @@ Colour parse_color(const std::string &color) {

#undef TRY_PARSER

NORM_ERR("can't parse color '%s'", color.c_str());
return ERROR_COLOUR;
}

Expand Down

0 comments on commit 6a39ebf

Please sign in to comment.