Skip to content

Commit

Permalink
[cstdstring] add format functions for working with wstring/wchar_t
Browse files Browse the repository at this point in the history
  • Loading branch information
night199uk authored and Jonathan Marshall committed Nov 13, 2013
1 parent 9e61643 commit bce122c
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
53 changes: 53 additions & 0 deletions xbmc/utils/StringUtils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,59 @@ string StringUtils::FormatV(const char *fmt, va_list args)
return "";
}

wstring StringUtils::Format(const wchar_t *fmt, ...)
{
va_list args;
va_start(args, fmt);
wstring str = FormatV(fmt, args);
va_end(args);

return str;
}

wstring StringUtils::FormatV(const wchar_t *fmt, va_list args)
{
if (fmt == NULL)
return L"";

int size = FORMAT_BLOCK_SIZE;
va_list argCopy;

wchar_t *cstr = reinterpret_cast<wchar_t*>(malloc(sizeof(wchar_t) * size));
if (cstr == NULL)
return L"";

while (1)
{
va_copy(argCopy, args);

int nActual = vswprintf(cstr, size, fmt, argCopy);
va_end(argCopy);

if (nActual > -1 && nActual < size) // We got a valid result
{
wstring str(cstr, nActual);
free(cstr);
return str;
}
if (nActual > -1) // Exactly what we will need (glibc 2.1)
size = nActual + 1;
else // Let's try to double the size (glibc 2.0)
size *= 2;

wchar_t *new_cstr = reinterpret_cast<wchar_t*>(realloc(cstr, sizeof(wchar_t) * size));
if (new_cstr == NULL)
{
free(cstr);
return L"";
}

cstr = new_cstr;
}

return L"";
}

void StringUtils::ToUpper(string &str)
{
transform(str.begin(), str.end(), str.begin(), ::toupper);
Expand Down
2 changes: 2 additions & 0 deletions xbmc/utils/StringUtils.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ class StringUtils
*/
static std::string Format(const char *fmt, ...);
static std::string FormatV(const char *fmt, va_list args);
static std::wstring Format(const wchar_t *fmt, ...);
static std::wstring FormatV(const wchar_t *fmt, va_list args);
static void ToUpper(std::string &str);
static void ToLower(std::string &str);
static bool EqualsNoCase(const std::string &str1, const std::string &str2);
Expand Down

0 comments on commit bce122c

Please sign in to comment.