--- nono/lib/mystring.cpp 2026/04/29 17:04:57 1.1.1.5 +++ nono/lib/mystring.cpp 2026/04/29 17:05:15 1.1.1.7 @@ -4,6 +4,10 @@ // Licensed under nono-license.txt // +// +// 文字列操作 +// + #include "mystring.h" #include @@ -82,6 +86,16 @@ string_tolower(const std::string& src) return dst; } +// 文字列 src 中の ASCII 小文字を大文字にした新しい文字列を返す。 +std::string +string_toupper(const std::string& src) +{ + std::string dst(src); + std::transform(dst.begin(), dst.end(), dst.begin(), + [](unsigned char c){ return std::toupper(c); }); + return dst; +} + // 文字列 lhs の先頭が rhs と大文字小文字の区別なしで一致すれば true を返す。 // ASCII 専用。 // C++20 の starts_with に似せておく。 @@ -141,25 +155,79 @@ string_split(const char *str, int len, c return list; } -#if 0 +// val を3桁ずつカンマ区切りした文字列にして返す。最大は 26桁。 +// ex) 123 -> "138" +// 12345 -> "12,345" +std::string +format_number(uint64 val) +{ + // 1 2 3 4 5 6 + // UINT64_MAX = 18,446,744,073,709,551,615 + char part[6][8]; + char buf[32]; + int n; + + n = 0; + memset(&part, 0, sizeof(part)); + while (val >= 1000) { + uint32 r = val % 1000; + val /= 1000; + + snprintf(part[n], sizeof(part[n]), ",%03u", r); + n++; + } + // この時点で + // part[0] = ",615"; + // part[1] = ",551"; + // : + // part[5] = ",446"; + + // 先頭(val は 1000未満) + snprintf(buf, sizeof(buf), "%u", (uint32)val); + + // part を連結 + while (--n >= 0) { + strlcat(buf, part[n], sizeof(buf)); + } + return std::string(buf); +} + +// value を width 桁の16進数文字列にして返す。"%0{width}x" みたいな感じ。 +// strhex(0x12345678, 4) -> "5678" +// strhex(0x00000001, 3) -> "001" +std::string +strhex(uint32 value, int width) +{ + std::string s; + + for (width -= 1; width >= 0; width--) { + uint32 d = (value >> (width * 4)) & 0x0f; + if (__predict_true(d < 10)) { + s += '0' + d; + } else { + s += 'a' + d - 10; + } + } + return s; +} + + +#if defined(SELFTEST) #include -#include +#include "stopwatch.h" +std::string s; int main() { - std::string s0 = string_format("%d_%d", 0, 1); - if (s0 != "0_1") { - printf("error\n"); - return 1; - } - timeval start, end, result; - gettimeofday(&start, NULL); - for (int i = 0; i < 100000; i++) { - std::string s = string_format("%d_%d", i, i); - } - gettimeofday(&end, NULL); - timersub(&end, &start, &result); - long long t = (result.tv_sec) * 1000000 + result.tv_usec; - printf("%d.%03d\n", (int)t / 1000, (int)t % 1000); + Stopwatch sw; + sw.Start(); + for (uint64 i = 0; i < 10000000; i += 3) { + s = format_number(i); + if (s.empty()) + return 0; + } + sw.Stop(); + uint64 t = sw.Elapsed(); + printf("%ld.%03ld msec\n", t / 1000 / 1000, (t / 1000) % 1000); return 0; } #endif