From 693fe2a1f5f785391eaab68bad1e22df77b98b66 Mon Sep 17 00:00:00 2001 From: Michael Jumper Date: Fri, 1 Apr 2011 00:53:53 -0700 Subject: [PATCH] Support for negative numbers in guac_write_int --- libguac/include/guacio.h | 2 +- libguac/src/guacio.c | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/libguac/include/guacio.h b/libguac/include/guacio.h index e82061ed..ff3a1639 100644 --- a/libguac/include/guacio.h +++ b/libguac/include/guacio.h @@ -123,7 +123,7 @@ GUACIO* guac_open(int fd); * @param i The unsigned int to write. * @return Zero on success, or non-zero if an error occurs while writing. */ -ssize_t guac_write_int(GUACIO* io, unsigned long i); +ssize_t guac_write_int(GUACIO* io, long i); /** * Writes the given string to the given GUACIO object. The data diff --git a/libguac/src/guacio.c b/libguac/src/guacio.c index e984c4fc..7c04054c 100644 --- a/libguac/src/guacio.c +++ b/libguac/src/guacio.c @@ -98,21 +98,31 @@ ssize_t __guac_write(GUACIO* io, const char* buf, int count) { return retval; } -ssize_t guac_write_int(GUACIO* io, unsigned long i) { +ssize_t guac_write_int(GUACIO* io, long i) { char buffer[128]; char* ptr = &(buffer[127]); + int nonneg; + + /* Obtain non-negative value */ + if (i < 0) nonneg = -i; + else nonneg = i; + + /* Generate numeric string */ *ptr = 0; do { ptr--; - *ptr = '0' + (i % 10); + *ptr = '0' + (nonneg % 10); - i /= 10; + nonneg /= 10; - } while (i > 0 && ptr >= buffer); + } while (nonneg > 0 && ptr >= buffer); + + /* Prepend with dash if negative */ + if (i < 0 && ptr >= buffer) *(--ptr) = '-'; return guac_write_string(io, ptr);