Imported Upstream version 1.22.0
[platform/upstream/grpc.git] / test / core / slice / slice_test.cc
index 1e53a19..4f824cb 100644 (file)
@@ -27,6 +27,7 @@
 #include <grpc/support/alloc.h>
 #include <grpc/support/log.h>
 
+#include "src/core/lib/gprpp/memory.h"
 #include "src/core/lib/slice/slice_internal.h"
 #include "src/core/lib/transport/static_metadata.h"
 #include "test/core/util/test_config.h"
@@ -51,13 +52,6 @@ static void test_slice_malloc_returns_something_sensible(void) {
     }
     /* Returned slice length must be what was requested. */
     GPR_ASSERT(GRPC_SLICE_LENGTH(slice) == length);
-    /* If the slice has a refcount, it must be destroyable. */
-    if (slice.refcount) {
-      GPR_ASSERT(slice.refcount->vtable != nullptr);
-      GPR_ASSERT(slice.refcount->vtable->ref != nullptr);
-      GPR_ASSERT(slice.refcount->vtable->unref != nullptr);
-      GPR_ASSERT(slice.refcount->vtable->hash != nullptr);
-    }
     /* We must be able to write to every byte of the data */
     for (i = 0; i < length; i++) {
       GRPC_SLICE_START_PTR(slice)[i] = static_cast<uint8_t>(i);
@@ -292,6 +286,44 @@ static void test_static_slice_copy_interning(void) {
   grpc_shutdown();
 }
 
+static void test_moved_string_slice(void) {
+  LOG_TEST_NAME("test_moved_string_slice");
+
+  grpc_init();
+
+  // Small string should be inlined.
+  constexpr char kSmallStr[] = "hello12345";
+  char* small_ptr = strdup(kSmallStr);
+  grpc_slice small =
+      grpc_slice_from_moved_string(grpc_core::UniquePtr<char>(small_ptr));
+  GPR_ASSERT(GRPC_SLICE_LENGTH(small) == strlen(kSmallStr));
+  GPR_ASSERT(GRPC_SLICE_START_PTR(small) !=
+             reinterpret_cast<uint8_t*>(small_ptr));
+  grpc_slice_unref(small);
+
+  // Large string should be move the reference.
+  constexpr char kSLargeStr[] = "hello123456789123456789123456789";
+  char* large_ptr = strdup(kSLargeStr);
+  grpc_slice large =
+      grpc_slice_from_moved_string(grpc_core::UniquePtr<char>(large_ptr));
+  GPR_ASSERT(GRPC_SLICE_LENGTH(large) == strlen(kSLargeStr));
+  GPR_ASSERT(GRPC_SLICE_START_PTR(large) ==
+             reinterpret_cast<uint8_t*>(large_ptr));
+  grpc_slice_unref(large);
+
+  // Moved buffer must respect the provided length not the actual length of the
+  // string.
+  large_ptr = strdup(kSLargeStr);
+  small = grpc_slice_from_moved_buffer(grpc_core::UniquePtr<char>(large_ptr),
+                                       strlen(kSmallStr));
+  GPR_ASSERT(GRPC_SLICE_LENGTH(small) == strlen(kSmallStr));
+  GPR_ASSERT(GRPC_SLICE_START_PTR(small) !=
+             reinterpret_cast<uint8_t*>(large_ptr));
+  grpc_slice_unref(small);
+
+  grpc_shutdown();
+}
+
 int main(int argc, char** argv) {
   unsigned length;
   grpc::testing::TestEnvironment env(argc, argv);
@@ -309,6 +341,7 @@ int main(int argc, char** argv) {
   test_slice_interning();
   test_static_slice_interning();
   test_static_slice_copy_interning();
+  test_moved_string_slice();
   grpc_shutdown();
   return 0;
 }