Add convenience functions to serialize to / deserialize from string
authorKeith Adams <kma@fb.com>
Mon, 29 Dec 2014 18:46:01 +0000 (10:46 -0800)
committerAjit Banerjee <ajitb@fb.com>
Wed, 7 Jan 2015 20:24:35 +0000 (12:24 -0800)
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
folly/io/IOBufQueue.h
folly/io/test/IOBufQueueTest.cpp

index 23e721fa7f99d0f77745d5ff58481936e610955e..a72229b2a4aacf692925d33469c2edf35a809fab 100644 (file)
@@ -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<const char*>(range.data()), range.size());
+  }
+}
+
 } // folly
index cbc11376a993e731533c7c13e969963141079dbc..73046f52c85fac465a1363764d93eba83edcc0f4 100644 (file)
@@ -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&&);
index 9e7c5a44fe2ad6641938e3ccb79b8fc648693178..b76ea97a465c8d14b0eb269fa433a50015a9b781 100644 (file)
@@ -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);