Skip to content

Commit

Permalink
add helper function to convert std::string to folly::IOBuf
Browse files Browse the repository at this point in the history
Reviewed By: ot

Differential Revision: D63949628

fbshipit-source-id: ae3897246405d8605f803da69d9ec54ebcc5c17e
  • Loading branch information
TJ Yin authored and facebook-github-bot committed Oct 11, 2024
1 parent 8c449c4 commit d0d7838
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
10 changes: 10 additions & 0 deletions folly/io/IOBuf.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1328,6 +1328,16 @@ IOBuf::Iterator IOBuf::cend() const {
return Iterator(nullptr, nullptr);
}

std::unique_ptr<IOBuf> IOBuf::fromString(std::unique_ptr<std::string> ptr) {
auto ret = takeOwnership(
ptr->data(),
ptr->size(),
[](void*, void* userData) { delete static_cast<std::string*>(userData); },
static_cast<void*>(ptr.get()));
std::ignore = ptr.release();
return ret;
}

folly::fbvector<struct iovec> IOBuf::getIov() const {
folly::fbvector<struct iovec> iov;
iov.reserve(countChainElements());
Expand Down
9 changes: 9 additions & 0 deletions folly/io/IOBuf.h
Original file line number Diff line number Diff line change
Expand Up @@ -1810,6 +1810,15 @@ class IOBuf {
*/
std::string toString() const { return to<std::string>(); }

/**
* Create an IOBuf from a std::string. Avoids copying the contents of the
* string, at the cost of an extra allocation.
*/
static std::unique_ptr<IOBuf> fromString(std::unique_ptr<std::string>);
static std::unique_ptr<IOBuf> fromString(std::string s) {
return fromString(std::make_unique<std::string>(std::move(s)));
}

/**
* Get an iovector suitable for e.g. writev()
*
Expand Down
7 changes: 7 additions & 0 deletions folly/io/test/IOBufTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1903,3 +1903,10 @@ TEST(IOBuf, MaybeSplitTail) {
auto buf3 = buf2->maybeSplitTail();
append(buf3, "!!!1");
}

TEST(IOBuf, FromString) {
EXPECT_EQ(folly::IOBuf::fromString("")->toString(), "");
EXPECT_EQ(folly::IOBuf::fromString("test")->toString(), "test");
auto longStr = std::string(1000, '0');
EXPECT_EQ(folly::IOBuf::fromString(longStr)->toString(), longStr);
}

0 comments on commit d0d7838

Please sign in to comment.