From 744112ceb0731da474604f47d27f413828db7009 Mon Sep 17 00:00:00 2001 From: Willem Jan Palenstijn Date: Sat, 25 Jul 2009 10:25:57 +0000 Subject: Add Common::String::printf to format a string svn-id: r42743 --- common/str.cpp | 30 ++++++++++++++++++++++++++++++ common/str.h | 5 +++++ test/common/str.h | 8 ++++++++ 3 files changed, 43 insertions(+) diff --git a/common/str.cpp b/common/str.cpp index 0d24f2edac..deef8bb22d 100644 --- a/common/str.cpp +++ b/common/str.cpp @@ -28,6 +28,8 @@ #include "common/memorypool.h" +#include + #if !defined(__SYMBIAN32__) #include #endif @@ -435,6 +437,34 @@ uint String::hash() const { return hashit(c_str()); } +// static +String String::printf(const char *fmt, ...) +{ + String output; + assert(output.isStorageIntern()); + + va_list va; + va_start(va, fmt); + int len = vsnprintf(output._str, _builtinCapacity, fmt, va); + va_end(va); + + if (len < (int)_builtinCapacity) { + // vsnprintf succeeded + output._size = len; + } else { + // vsnprintf didn't have enough space, so grow buffer + output.ensureCapacity(len, false); + va_start(va, fmt); + int len2 = vsnprintf(output._str, len+1, fmt, va); + va_end(va); + assert(len == len2); + output._size = len2; + } + + return output; +} + + #pragma mark - bool String::operator ==(const String &x) const { diff --git a/common/str.h b/common/str.h index b7dbd6535a..2fc88e9c91 100644 --- a/common/str.h +++ b/common/str.h @@ -218,6 +218,11 @@ public: uint hash() const; + /** + * Printf-like function. Returns a formatted String. + */ + static Common::String printf(const char *fmt, ...) GCC_PRINTF(1,2); + public: typedef char * iterator; typedef const char * const_iterator; diff --git a/test/common/str.h b/test/common/str.h index bf0db98b09..f65b078bdc 100644 --- a/test/common/str.h +++ b/test/common/str.h @@ -285,4 +285,12 @@ class StringTestSuite : public CxxTest::TestSuite TS_ASSERT(!Common::matchString("monkey.s99", "monkey.s*1")); TS_ASSERT(Common::matchString("monkey.s101", "monkey.s*1")); } + + void test_string_printf() { + TS_ASSERT( Common::String::printf("") == "" ); + TS_ASSERT( Common::String::printf("%s", "test") == "test" ); + TS_ASSERT( Common::String::printf("%s.s%.02d", "monkey", 1) == "monkey.s01" ); + TS_ASSERT( Common::String::printf("%s%X", "test", 1234) == "test4D2" ); + TS_ASSERT( Common::String::printf("Some %s to make this string longer than the default built-in %s %d", "text", "capacity", 123456) == "Some text to make this string longer than the default built-in capacity 123456" ); + } }; -- cgit v1.2.3