fixing itoa on unix

This commit is contained in:
Enno Rehling 2018-12-02 20:32:04 +01:00
parent c203ffce08
commit ae0415cf8d
3 changed files with 17 additions and 13 deletions

View file

@ -18,7 +18,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#ifdef _MSC_VER
#include <platform.h>
#define HAVE__ITOA
#undef HAVE__ITOA
#endif
#include "strings.h"
@ -35,27 +35,23 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <string.h>
#endif
const char* str_itoab(int val, int base)
const char* str_itoa_r(int val, char *buf)
{
static char buf[32] = { 0 };
#ifdef HAVE__ITOAB
return _itoa(val, buf, base);
#ifdef HAVE__ITOA
return _itoa(val, buf, 10);
#else
int i = 30;
for (; val && i; --i, val /= base) {
buf[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[val % base];
}
return &buf[i + 1];
snprintf(buf, 12, "%d", val);
return buf;
#endif
}
const char *str_itoa(int n)
{
static char buf[12];
#ifdef HAVE__ITOA
static char buf[32] = { 0 };
return _itoa(n, buf, 10);
#else
return str_itoab(n, 10);
return str_itoa_r(n, buf);
#endif
}

View file

@ -29,7 +29,6 @@ extern "C" {
void str_replace(char *buffer, size_t size, const char *tmpl, const char *var, const char *value);
int str_hash(const char *s);
const char *str_itoa(int i);
const char *str_itoab(int i, int base);
size_t str_slprintf(char * dst, size_t size, const char * format, ...);
size_t str_strlcpy(char *dst, const char *src, size_t len);
size_t str_strlcat(char *dst, const char *src, size_t len);

View file

@ -128,6 +128,14 @@ static void test_str_strlcpy(CuTest * tc)
errno = 0;
}
static void test_str_itoa(CuTest * tc)
{
CuAssertStrEquals(tc, "1234", str_itoa(1234));
CuAssertStrEquals(tc, "0", str_itoa(0));
CuAssertStrEquals(tc, "1234567890", str_itoa(1234567890));
CuAssertStrEquals(tc, "-1234567890", str_itoa(-1234567890));
}
static void test_sbstring(CuTest * tc)
{
char buffer[16];
@ -165,6 +173,7 @@ CuSuite *get_strings_suite(void)
SUITE_ADD_TEST(suite, test_str_slprintf);
SUITE_ADD_TEST(suite, test_str_strlcat);
SUITE_ADD_TEST(suite, test_str_strlcpy);
SUITE_ADD_TEST(suite, test_str_itoa);
SUITE_ADD_TEST(suite, test_sbstring);
return suite;
}