diff options
author | 2015-01-23 11:12:46 -0800 | |
---|---|---|
committer | 2015-01-23 11:12:46 -0800 | |
commit | c0fc6a1f1fe54f0b83a7089bf65cff39d91e611f (patch) | |
tree | 052477124a995529a407c2dc115948df938f5a68 | |
parent | 55f17830fbb25ab321b20444ca298709b177de00 (diff) |
Add gpr_ltoa
-rw-r--r-- | include/grpc/support/string.h | 7 | ||||
-rw-r--r-- | src/core/support/string.c | 30 |
2 files changed, 37 insertions, 0 deletions
diff --git a/include/grpc/support/string.h b/include/grpc/support/string.h index 68e7452a7f..2ce19036f2 100644 --- a/include/grpc/support/string.h +++ b/include/grpc/support/string.h @@ -60,6 +60,13 @@ char *gpr_hexdump(const char *buf, size_t len, gpr_uint32 flags); int gpr_parse_bytes_to_uint32(const char *data, size_t length, gpr_uint32 *result); +/* Convert a long to a string in base 10; returns the length of the + output string (or 0 on failure) */ +int gpr_ltoa(long value, char *output); + +/* Reverse a run of bytes */ +void gpr_reverse_bytes(char *str, int len); + /* printf to a newly-allocated string. The set of supported formats may vary between platforms. diff --git a/src/core/support/string.c b/src/core/support/string.c index 7960547735..7e84437fac 100644 --- a/src/core/support/string.c +++ b/src/core/support/string.c @@ -122,3 +122,33 @@ int gpr_parse_bytes_to_uint32(const char *buf, size_t len, gpr_uint32 *result) { *result = out; return 1; } + +void gpr_reverse_bytes(char *str, int len) { + char *p1, *p2; + for (p1 = str, p2 = str + len - 1; p2 > p1; ++p1, --p2) { + char temp = *p1; + *p1 = *p2; + *p2 = temp; + } +} + +int gpr_ltoa(long value, char *string) { + int i = 0; + int neg = value < 0; + + if (value == 0) { + string[0] = '0'; + string[1] = 0; + return 1; + } + + if (neg) value = -value; + while (value) { + string[i++] = '0' + value % 10; + value /= 10; + } + if (neg) string[i++] = '-'; + gpr_reverse_bytes(string, i); + string[i] = 0; + return i; +} |