From e5b0df28eb4179c1971ec143a13146a50a895e58 Mon Sep 17 00:00:00 2001 From: Steven Moreland Date: Mon, 29 Mar 2021 17:28:48 +0000 Subject: hidl_string: empty string opt always applies Before, it only applied for the default constructor. However, there are many cases where we can avoid the extra allocation. The most important is when we allocate a hidl_memory object. Here, the empty string literal is passed to hidl_string, but we don't actually need an allocation. Bug: 179720143 Test: N/A Change-Id: I307305b88e8b8c54cb2e2759b60b7015a3ac82b9 --- base/HidlSupport.cpp | 8 ++++++++ test_main.cpp | 14 ++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/base/HidlSupport.cpp b/base/HidlSupport.cpp index af805b9..78faa2f 100644 --- a/base/HidlSupport.cpp +++ b/base/HidlSupport.cpp @@ -217,6 +217,14 @@ void hidl_string::copyFrom(const char *data, size_t size) { if (size >= UINT32_MAX) { LOG(FATAL) << "string size can't exceed 2^32 bytes: " << size; } + + if (size == 0) { + mBuffer = kEmptyString; + mSize = 0; + mOwnsBuffer = false; + return; + } + char *buf = (char *)malloc(size + 1); memcpy(buf, data, size); buf[size] = '\0'; diff --git a/test_main.cpp b/test_main.cpp index ea4dfd1..5c6c78e 100644 --- a/test_main.cpp +++ b/test_main.cpp @@ -175,6 +175,20 @@ TEST_F(LibHidlTest, StringTest) { EXPECT_FALSE(hs2 <= hs1); } +// empty string optimization should apply for any constructor +TEST_F(LibHidlTest, HidlStringEmptyLiteralAllocation) { + using android::hardware::hidl_string; + + hidl_string empty1; + hidl_string empty2(""); + hidl_string empty3("foo", 0); + hidl_string empty4((std::string())); + + EXPECT_EQ(empty1.c_str(), empty2.c_str()); + EXPECT_EQ(empty1.c_str(), empty3.c_str()); + EXPECT_EQ(empty1.c_str(), empty4.c_str()); +} + TEST_F(LibHidlTest, MemoryTest) { using android::hardware::hidl_memory; -- cgit v1.2.3