enh(stream): replace magic numbers in u64toaFastLut with macros

Replace magic numbers in the u64toaFastLut function with macros for
better readability and maintainability. Add unit test to ensure the
correctness of the refactor.
This commit is contained in:
Jinqing Kuang 2025-02-18 17:13:35 +08:00
parent 48758608b4
commit 87040f1822
2 changed files with 53 additions and 13 deletions

View File

@ -1502,31 +1502,46 @@ bool taosAssertRelease(bool condition) {
}
#endif
#define NUM_BASE 100
#define DIGIT_LENGTH 2
#define MAX_DIGITS 24
char* u64toaFastLut(uint64_t val, char* buf) {
// Look-up table for 2-digit numbers
static const char* lut =
"0001020304050607080910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455"
"5657585960616263646566676869707172737475767778798081828384858687888990919293949596979899";
char temp[24];
char* p = temp;
char temp[MAX_DIGITS];
char* p = temp + tListLen(temp);
while (val >= 100) {
strncpy(p, lut + (val % 100) * 2, 2);
val /= 100;
p += 2;
// Process the digits greater than or equal to 100
while (val >= NUM_BASE) {
// Get the last 2 digits from the look-up table and add to the buffer
p -= DIGIT_LENGTH;
strncpy(p, lut + (val % NUM_BASE) * DIGIT_LENGTH, DIGIT_LENGTH);
val /= NUM_BASE;
}
// Process the remaining 1 or 2 digits
if (val >= 10) {
strncpy(p, lut + val * 2, 2);
p += 2;
// If the number is 10 or more, get the 2 digits from the look-up table
p -= DIGIT_LENGTH;
strncpy(p, lut + val * DIGIT_LENGTH, DIGIT_LENGTH);
} else if (val > 0 || p == temp) {
*(p++) = val + '0';
// If the number is less than 10, add the single digit to the buffer
p -= 1;
*p = val + '0';
}
while (p != temp) {
*buf++ = *--p;
int64_t len = temp + tListLen(temp) - p;
if (len > 0) {
memcpy(buf, p, len);
} else {
buf[0] = '0';
len = 1;
}
buf[len] = '\0';
*buf = '\0';
return buf;
return buf + len;
}

View File

@ -139,3 +139,28 @@ TEST(log, misc) {
taosCloseLog();
}
TEST(log, test_u64toa) {
char buf[64] = {0};
char *p = buf;
p = u64toaFastLut(0, buf);
EXPECT_EQ(p, buf + 1);
EXPECT_EQ(strcmp(buf, "0"), 0);
p = u64toaFastLut(1, buf);
EXPECT_EQ(p, buf + 1);
EXPECT_EQ(strcmp(buf, "1"), 0);
p = u64toaFastLut(12, buf);
EXPECT_EQ(p, buf + 2);
EXPECT_EQ(strcmp(buf, "12"), 0);
p = u64toaFastLut(12345, buf);
EXPECT_EQ(p, buf + 5);
EXPECT_EQ(strcmp(buf, "12345"), 0);
p = u64toaFastLut(1234567890, buf);
EXPECT_EQ(p, buf + 10);
EXPECT_EQ(strcmp(buf, "1234567890"), 0);
}