Merge pull request #204 from TsudaKageyu/number

Changed String::number() to use a standard function
This commit is contained in:
Tsuda Kageyu 2013-05-18 22:59:02 -07:00
commit 2303da48a2
3 changed files with 36 additions and 18 deletions

View File

@ -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 <cstdio>
int main() { char buf[20]; snprintf(buf, 20, \"%d\", 1); return 0; }
" HAVE_SNPRINTF)
if(NOT HAVE_SNPRINTF)
check_cxx_source_compiles("
#include <cstdio>
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("

View File

@ -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

View File

@ -33,7 +33,8 @@
#include "trefcounter.h"
#include <iostream>
#include <string.h>
#include <cstdio>
#include <cstring>
#if defined(HAVE_MSC_BYTESWAP)
# include <stdlib.h>
@ -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)