diff --git a/include/grpc/support/slice.h b/include/grpc/support/slice.h index ec6c117afe6..a4fb2d08074 100644 --- a/include/grpc/support/slice.h +++ b/include/grpc/support/slice.h @@ -172,6 +172,10 @@ gpr_slice gpr_empty_slice(void); int gpr_slice_cmp(gpr_slice a, gpr_slice b); int gpr_slice_str_cmp(gpr_slice a, const char *b); +/* Returns a null terminated C string from a slice. It is the responsibility of + the caller to call gpr_free on the result. */ +char *gpr_slice_to_cstring(gpr_slice s); + #ifdef __cplusplus } #endif diff --git a/src/core/support/slice.c b/src/core/support/slice.c index a2d62fc1e53..e4196a48c64 100644 --- a/src/core/support/slice.c +++ b/src/core/support/slice.c @@ -325,3 +325,10 @@ int gpr_slice_str_cmp(gpr_slice a, const char *b) { if (d != 0) return d; return memcmp(GPR_SLICE_START_PTR(a), b, b_length); } + +char *gpr_slice_to_cstring(gpr_slice slice) { + char *result = gpr_malloc(GPR_SLICE_LENGTH(slice) + 1); + memcpy(result, GPR_SLICE_START_PTR(slice), GPR_SLICE_LENGTH(slice)); + result[GPR_SLICE_LENGTH(slice)] = '\0'; + return result; +} diff --git a/test/core/support/slice_test.c b/test/core/support/slice_test.c index 63dedea50fe..3f6522f8bf1 100644 --- a/test/core/support/slice_test.c +++ b/test/core/support/slice_test.c @@ -35,6 +35,7 @@ #include +#include #include #include "test/core/util/test_config.h" @@ -211,6 +212,33 @@ static void test_slice_from_copied_string_works(void) { gpr_slice_unref(slice); } +static void test_slice_to_cstring_works(void) { + static const char *text = "HELLO WORLD!"; + static const char *long_text = + "It was a bright cold day in April, and the clocks were striking " + "thirteen. Winston Smith, his chin nuzzled into his breast in an effort " + "to escape the vile wind, slipped quickly through the glass doors of " + "Victory Mansions, though not quickly enough to prevent a swirl of " + "gritty dust from entering along with him."; + gpr_slice slice; + char *text2; + char *long_text2; + + LOG_TEST_NAME("test_slice_to_cstring_works"); + + slice = gpr_slice_from_copied_string(text); + text2 = gpr_slice_to_cstring(slice); + GPR_ASSERT(strcmp(text, text2) == 0); + gpr_free(text2); + gpr_slice_unref(slice); + + slice = gpr_slice_from_copied_string(long_text); + long_text2 = gpr_slice_to_cstring(slice); + GPR_ASSERT(strcmp(long_text, long_text2) == 0); + gpr_free(long_text2); + gpr_slice_unref(slice); +} + int main(int argc, char **argv) { unsigned length; grpc_test_init(argc, argv); @@ -223,5 +251,6 @@ int main(int argc, char **argv) { test_slice_split_tail_works(length); } test_slice_from_copied_string_works(); + test_slice_to_cstring_works(); return 0; }