diff options
author | Willem Jan Palenstijn | 2009-07-25 10:25:57 +0000 |
---|---|---|
committer | Willem Jan Palenstijn | 2009-07-25 10:25:57 +0000 |
commit | 744112ceb0731da474604f47d27f413828db7009 (patch) | |
tree | 5321863dd510d46086f2963eddbd96eeb5ca38a5 | |
parent | 4463e1c084a4822a2c5c130532964ea3372bdef7 (diff) | |
download | scummvm-rg350-744112ceb0731da474604f47d27f413828db7009.tar.gz scummvm-rg350-744112ceb0731da474604f47d27f413828db7009.tar.bz2 scummvm-rg350-744112ceb0731da474604f47d27f413828db7009.zip |
Add Common::String::printf to format a string
svn-id: r42743
-rw-r--r-- | common/str.cpp | 30 | ||||
-rw-r--r-- | common/str.h | 5 | ||||
-rw-r--r-- | test/common/str.h | 8 |
3 files changed, 43 insertions, 0 deletions
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 <stdarg.h> + #if !defined(__SYMBIAN32__) #include <new> #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" ); + } }; |