diff --git a/include/grpc/support/string.h b/include/grpc/support/string.h index 68e7452a7fa..2ce19036f2e 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 7960547735b..7e84437fac7 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; +}