diff --git a/uart.hpp b/uart.hpp index 91326ab..a3cefe7 100644 --- a/uart.hpp +++ b/uart.hpp @@ -22,11 +22,6 @@ static constexpr size_t cntDigits() T num = limit; size_t cnt = 0; - if (num < 0) { - num = -num; - ++cnt; - } - do { num /= Base; ++cnt; @@ -38,8 +33,23 @@ static constexpr size_t cntDigits() template static constexpr size_t maxNumDigits() { - T minDigits = cntDigits::min(), Base>(); - T maxDigits = cntDigits::max(), Base>(); + constexpr T minVal = util::NumericLimits::min(); + constexpr T maxVal = util::NumericLimits::max(); + + T minDigits = cntDigits() + ((minVal < 0) ? 1 : 0); + T maxDigits = cntDigits() + ((maxVal < 0) ? 1 : 0); + + return (minDigits < maxDigits) ? maxDigits : minDigits; +} + +template +static constexpr size_t maxPadding() +{ + constexpr T minVal = util::NumericLimits::min(); + constexpr T maxVal = util::NumericLimits::max(); + + T minDigits = cntDigits(); + T maxDigits = cntDigits(); return (minDigits < maxDigits) ? maxDigits : minDigits; } @@ -111,14 +121,17 @@ class Uart { txByte(ch); } - template + template static void txNumber(const T &val) { static_assert(util::is_integral_v, "Only supported on integral types"); static_assert(Base >= 2, "Numbers with bases less than 2 make no sense"); static_assert(Base <= 16, "Numbers with bases higher than 16 are not supported"); + static_assert(Padding <= detail::maxPadding(), "Cannot pad more than maximum length of number"); + constexpr char alphaChar = (LowerCase) ? 'a' : 'A'; constexpr size_t numDigits = detail::maxNumDigits(); + data_t buffer[numDigits]; data_t *bufEnd = buffer + numDigits - 1; @@ -131,10 +144,20 @@ class Uart { do { data_t lastDigit = digits % Base; - *bufEnd-- = (lastDigit < 10) ? ('0' + lastDigit) : ('a' + lastDigit - 10); + *bufEnd-- = (lastDigit < 10) ? ('0' + lastDigit) : (alphaChar + lastDigit - 10); digits /= Base; } while (digits > 0); + if (Padding > 0) { + size_t strLen = buffer + numDigits - (bufEnd + 1); + + if (Padding > strLen) { + for (size_t i = Padding; i > strLen && bufEnd >= buffer; --i) { + *bufEnd-- = PadChar; + } + } + } + for (data_t *buf = bufEnd + 1; buf < buffer + numDigits; ++buf) txByte(*buf); }