From 1ed040e7ee591753381c065ed8b48cbe6cd20e76 Mon Sep 17 00:00:00 2001 From: Keith Adams Date: Mon, 29 Dec 2014 10:46:01 -0800 Subject: [PATCH] Add convenience functions to serialize to / deserialize from string Summary: kma asked Test Plan: tests added Reviewed By: andrei.bajenov@fb.com Subscribers: alandau, bmatheny, mshneer, folly-diffs@ FB internal diff: D1756731 Signature: t1:1756731:1419442987:afdccce166ef1f1e609d8894ea587915f6fea8e7 --- folly/io/IOBufQueue.cpp | 13 +++++++++++++ folly/io/IOBufQueue.h | 5 +++++ folly/io/test/IOBufQueueTest.cpp | 9 +++++++++ 3 files changed, 27 insertions(+) diff --git a/folly/io/IOBufQueue.cpp b/folly/io/IOBufQueue.cpp index 23e721fa..a72229b2 100644 --- a/folly/io/IOBufQueue.cpp +++ b/folly/io/IOBufQueue.cpp @@ -273,4 +273,17 @@ void IOBufQueue::clear() { chainLength_ = 0; } +void IOBufQueue::appendToString(std::string& out) const { + if (!head_) { + return; + } + auto len = + options_.cacheChainLength ? chainLength_ : head_->computeChainDataLength(); + out.reserve(out.size() + len); + + for (auto range : *head_) { + out.append(reinterpret_cast(range.data()), range.size()); + } +} + } // folly diff --git a/folly/io/IOBufQueue.h b/folly/io/IOBufQueue.h index cbc11376..73046f52 100644 --- a/folly/io/IOBufQueue.h +++ b/folly/io/IOBufQueue.h @@ -261,6 +261,11 @@ class IOBufQueue { */ void clear(); + /** + * Append the queue to a std::string. Non-destructive. + */ + void appendToString(std::string& out) const; + /** Movable */ IOBufQueue(IOBufQueue&&) noexcept; IOBufQueue& operator=(IOBufQueue&&); diff --git a/folly/io/test/IOBufQueueTest.cpp b/folly/io/test/IOBufQueueTest.cpp index 9e7c5a44..b76ea97a 100644 --- a/folly/io/test/IOBufQueueTest.cpp +++ b/folly/io/test/IOBufQueueTest.cpp @@ -378,6 +378,15 @@ TEST(IOBufQueue, PopFirst) { EXPECT_EQ(0, queue.chainLength()); } +TEST(IOBufQueue, AppendToString) { + IOBufQueue queue; + queue.append("hello ", 6); + queue.append("world", 5); + std::string s; + queue.appendToString(s); + EXPECT_EQ("hello world", s); +} + int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); gflags::ParseCommandLineFlags(&argc, &argv, true); -- 2.34.1