From bbec1c7f81b8f59567fc8868aca61deb38acafeb Mon Sep 17 00:00:00 2001 From: Tsuda Kageyu Date: Sun, 19 May 2013 14:39:45 +0900 Subject: [PATCH] Changed String::number() to use a standard function --- ConfigureChecks.cmake | 14 ++++++++++++++ config.h.cmake | 4 ++++ taglib/toolkit/tstring.cpp | 36 ++++++++++++++++++------------------ 3 files changed, 36 insertions(+), 18 deletions(-) diff --git a/ConfigureChecks.cmake b/ConfigureChecks.cmake index 440a4414..46611a00 100644 --- a/ConfigureChecks.cmake +++ b/ConfigureChecks.cmake @@ -183,6 +183,20 @@ if(NOT HAVE_GCC_BYTESWAP_16 OR NOT HAVE_GCC_BYTESWAP_32 OR NOT HAVE_GCC_BYTESWAP endif() endif() +# Determine whether your compiler supports some safer version of sprintf. + +check_cxx_source_compiles(" + #include + int main() { char buf[20]; snprintf(buf, 20, \"%d\", 1); return 0; } +" HAVE_SNPRINTF) + +if(NOT HAVE_SNPRINTF) + check_cxx_source_compiles(" + #include + int main() { char buf[20]; sprintf_s(buf, \"%d\", 1); return 0; } + " HAVE_SPRINTF_S) +endif() + # Determine whether your compiler supports codecvt. check_cxx_source_compiles(" diff --git a/config.h.cmake b/config.h.cmake index 436ca440..15d2f997 100644 --- a/config.h.cmake +++ b/config.h.cmake @@ -24,6 +24,10 @@ #cmakedefine HAVE_WIN_ATOMIC 1 #cmakedefine HAVE_IA64_ATOMIC 1 +/* Defined if your compiler supports some safer version of sprintf */ +#cmakedefine HAVE_SNPRINTF 1 +#cmakedefine HAVE_SPRINTF_S 1 + /* Defined if you have libz */ #cmakedefine HAVE_ZLIB 1 diff --git a/taglib/toolkit/tstring.cpp b/taglib/toolkit/tstring.cpp index cf745f81..7b4d2040 100644 --- a/taglib/toolkit/tstring.cpp +++ b/taglib/toolkit/tstring.cpp @@ -33,7 +33,8 @@ #include "trefcounter.h" #include -#include +#include +#include #if defined(HAVE_MSC_BYTESWAP) # include @@ -597,31 +598,30 @@ bool String::isAscii() const String String::number(int n) // static { - if(n == 0) - return String("0"); + static const size_t BufferSize = 11; // Sufficient to store "-214748364". + static const char *Format = "%d"; - String charStack; + char buffer[BufferSize]; + int length; - bool negative = n < 0; +#if defined(HAVE_SNPRINTF) - if(negative) - n = n * -1; + length = snprintf(buffer, BufferSize, Format, n); - while(n > 0) { - int remainder = n % 10; - charStack += char(remainder + '0'); - n = (n - remainder) / 10; - } +#elif defined(HAVE_SPRINTF_S) - String s; + length = sprintf_s(buffer, Format, n); - if(negative) - s += '-'; +#else - for(int i = charStack.d->data.size() - 1; i >= 0; i--) - s += charStack.d->data[i]; + length = sprintf(buffer, Format, n); - return s; +#endif + + if(length > 0) + return String(buffer); + else + return String::null; } TagLib::wchar &String::operator[](int i)