From 30295b0577ee0d1e7b140ac94de1ac79a2d7f0c3 Mon Sep 17 00:00:00 2001 From: Daniel Brall <729926+Bradan@users.noreply.github.com> Date: Mon, 25 Mar 2024 20:13:08 +0100 Subject: [PATCH] Fixed and improved HtmlColor::ToNumericalString (#792) * Fixed and improved HtmlColor::ToNumericalString which decremented bufLen twice and returned wrong results * Strictly expect least 8 characters --------- Co-authored-by: Daniel Brall --- src/internal/colors/HtmlColor.cpp | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/internal/colors/HtmlColor.cpp b/src/internal/colors/HtmlColor.cpp index 9e9af5f..1840e73 100644 --- a/src/internal/colors/HtmlColor.cpp +++ b/src/internal/colors/HtmlColor.cpp @@ -36,28 +36,28 @@ static inline char hexdigit(uint8_t v) } +/** + * Generates a Html encoded hex color string (#aabbcc) with null termination. + * + * @param buf the buffer to write the string to + * @param bufSize the maximum buffer size (must be at least 8 characters) + * @return The amount of chars written to buf including the null terminator. + */ size_t HtmlColor::ToNumericalString(char* buf, size_t bufSize) const { - size_t bufLen = bufSize - 1; - - if (bufLen-- > 0) + if (bufSize >= 8) { - if (bufLen > 0) - { - buf[0] = '#'; - } + buf[0] = '#'; uint32_t color = Color; - for (uint8_t indexDigit = 6; indexDigit > 0; indexDigit--) + for (size_t indexDigit = 6; indexDigit > 0; --indexDigit) // note pre-decrement { - if (bufLen > indexDigit) - { - buf[indexDigit] = hexdigit(color & 0x0000000f); - } + buf[indexDigit] = hexdigit(color & 0x0000000f); color >>= 4; } + buf[7] = '\0'; - buf[(bufLen < 7 ? bufLen : 7)] = 0; + return 8; } - return 7; + return 0; }