aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--common/str.cpp30
-rw-r--r--common/str.h5
-rw-r--r--test/common/str.h8
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" );
+ }
};