mirror of
https://github.com/libretro/scummvm.git
synced 2025-03-02 08:19:19 +00:00
Add Common::String::printf to format a string
svn-id: r42743
This commit is contained in:
parent
4463e1c084
commit
744112ceb0
@ -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 {
|
||||
|
@ -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;
|
||||
|
@ -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" );
|
||||
}
|
||||
};
|
||||
|
Loading…
x
Reference in New Issue
Block a user