1f013da621bf1db55d117d0e45a792280a9d3089
[folly.git] / folly / io / test / IOBufCursorTest.cpp
1 /*
2  * Copyright 2013-present Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <folly/io/IOBuf.h>
17
18 #include <folly/Format.h>
19 #include <folly/Range.h>
20 #include <folly/io/Cursor.h>
21 #include <folly/portability/GTest.h>
22 #include <numeric>
23 #include <vector>
24
25 using folly::ByteRange;
26 using folly::format;
27 using folly::IOBuf;
28 using folly::StringPiece;
29 using std::unique_ptr;
30 using namespace folly::io;
31
32 TEST(IOBuf, RWCursor) {
33   unique_ptr<IOBuf> iobuf1(IOBuf::create(20));
34   iobuf1->append(20);
35   unique_ptr<IOBuf> iobuf2(IOBuf::create(20));
36   iobuf2->append(20);
37
38   iobuf2.get();
39   iobuf1->prependChain(std::move(iobuf2));
40
41   EXPECT_TRUE(iobuf1->isChained());
42
43   RWPrivateCursor wcursor(iobuf1.get());
44   Cursor rcursor(iobuf1.get());
45   wcursor.writeLE((uint64_t)1);
46   wcursor.writeLE((uint64_t)1);
47   wcursor.writeLE((uint64_t)1);
48   wcursor.write((uint8_t)1);
49
50   EXPECT_EQ(1u, rcursor.readLE<uint64_t>());
51   rcursor.skip(8);
52   EXPECT_EQ(1u, rcursor.readLE<uint32_t>());
53   rcursor.skip(0);
54   EXPECT_EQ(0u, rcursor.read<uint8_t>());
55   EXPECT_EQ(0u, rcursor.read<uint8_t>());
56   EXPECT_EQ(0u, rcursor.read<uint8_t>());
57   EXPECT_EQ(0u, rcursor.read<uint8_t>());
58   EXPECT_EQ(1u, rcursor.read<uint8_t>());
59 }
60
61 TEST(IOBuf, skip) {
62   unique_ptr<IOBuf> iobuf1(IOBuf::create(20));
63   iobuf1->append(20);
64   RWPrivateCursor wcursor(iobuf1.get());
65   wcursor.write((uint8_t)1);
66   wcursor.write((uint8_t)2);
67   Cursor cursor(iobuf1.get());
68   cursor.skip(1);
69   EXPECT_EQ(2, cursor.read<uint8_t>());
70 }
71
72 TEST(IOBuf, reset) {
73   unique_ptr<IOBuf> iobuf1(IOBuf::create(20));
74   iobuf1->append(20);
75   RWPrivateCursor wcursor(iobuf1.get());
76   wcursor.write((uint8_t)1);
77   wcursor.write((uint8_t)2);
78   wcursor.reset(iobuf1.get());
79   EXPECT_EQ(1, wcursor.read<uint8_t>());
80 }
81
82 TEST(IOBuf, copy_assign_convert) {
83   unique_ptr<IOBuf> iobuf1(IOBuf::create(20));
84   iobuf1->append(20);
85   RWPrivateCursor wcursor(iobuf1.get());
86   RWPrivateCursor cursor2(wcursor);
87   RWPrivateCursor cursor3(iobuf1.get());
88
89   wcursor.write((uint8_t)1);
90   cursor3 = wcursor;
91   wcursor.write((uint8_t)2);
92   Cursor cursor4(wcursor);
93   RWPrivateCursor cursor5(wcursor);
94   wcursor.write((uint8_t)3);
95
96   EXPECT_EQ(1, cursor2.read<uint8_t>());
97   EXPECT_EQ(2, cursor3.read<uint8_t>());
98   EXPECT_EQ(3, cursor4.read<uint8_t>());
99 }
100
101 TEST(IOBuf, arithmetic) {
102   IOBuf iobuf1(IOBuf::CREATE, 20);
103   iobuf1.append(20);
104   RWPrivateCursor wcursor(&iobuf1);
105   wcursor += 1;
106   wcursor.write((uint8_t)1);
107   Cursor cursor(&iobuf1);
108   cursor += 1;
109   EXPECT_EQ(1, cursor.read<uint8_t>());
110
111   Cursor start(&iobuf1);
112   Cursor cursor2 = start + 9;
113   EXPECT_EQ(7, cursor2 - cursor);
114   EXPECT_NE(cursor, cursor2);
115   cursor += 8;
116   cursor2 = cursor2 + 1;
117   EXPECT_EQ(cursor, cursor2);
118 }
119
120 TEST(IOBuf, endian) {
121   unique_ptr<IOBuf> iobuf1(IOBuf::create(20));
122   iobuf1->append(20);
123   RWPrivateCursor wcursor(iobuf1.get());
124   Cursor rcursor(iobuf1.get());
125   uint16_t v = 1;
126   int16_t vu = -1;
127   wcursor.writeBE(v);
128   wcursor.writeBE(vu);
129   // Try a couple combinations to ensure they were generated correctly
130   wcursor.writeBE(vu);
131   wcursor.writeLE(vu);
132   wcursor.writeLE(vu);
133   wcursor.writeLE(v);
134   EXPECT_EQ(v, rcursor.readBE<uint16_t>());
135 }
136
137 TEST(IOBuf, Cursor) {
138   unique_ptr<IOBuf> iobuf1(IOBuf::create(1));
139   iobuf1->append(1);
140   RWPrivateCursor c(iobuf1.get());
141   c.write((uint8_t)40); // OK
142   try {
143     c.write((uint8_t)10); // Bad write, checked should except.
144     ADD_FAILURE();
145   } catch (...) {
146   }
147 }
148
149 TEST(IOBuf, UnshareCursor) {
150   uint8_t buf = 0;
151   unique_ptr<IOBuf> iobuf1(IOBuf::wrapBuffer(&buf, 1));
152   unique_ptr<IOBuf> iobuf2(IOBuf::wrapBuffer(&buf, 1));
153   RWUnshareCursor c1(iobuf1.get());
154   RWUnshareCursor c2(iobuf2.get());
155
156   c1.write((uint8_t)10); // This should duplicate the two buffers.
157   uint8_t t = c2.read<uint8_t>();
158   EXPECT_EQ(0, t);
159
160   iobuf1 = IOBuf::wrapBuffer(&buf, 1);
161   iobuf2 = IOBuf::wrapBuffer(&buf, 1);
162   RWPrivateCursor c3(iobuf1.get());
163   RWPrivateCursor c4(iobuf2.get());
164
165   c3.write((uint8_t)10); // This should _not_ duplicate the two buffers.
166   t = c4.read<uint8_t>();
167   EXPECT_EQ(10, t);
168 }
169
170 namespace {
171 void append(std::unique_ptr<IOBuf>& buf, folly::StringPiece data) {
172   EXPECT_LE(data.size(), buf->tailroom());
173   memcpy(buf->writableData(), data.data(), data.size());
174   buf->append(data.size());
175 }
176
177 void append(Appender& appender, StringPiece data) {
178   appender.push(ByteRange(data));
179 }
180
181 std::string toString(const IOBuf& buf) {
182   std::string str;
183   Cursor cursor(&buf);
184   ByteRange b;
185   while (!(b = cursor.peekBytes()).empty()) {
186     str.append(reinterpret_cast<const char*>(b.data()), b.size());
187     cursor.skip(b.size());
188   }
189   return str;
190 }
191
192 } // namespace
193
194 TEST(IOBuf, PullAndPeek) {
195   std::unique_ptr<IOBuf> iobuf1(IOBuf::create(10));
196   append(iobuf1, "he");
197   std::unique_ptr<IOBuf> iobuf2(IOBuf::create(10));
198   append(iobuf2, "llo ");
199   std::unique_ptr<IOBuf> iobuf3(IOBuf::create(10));
200   append(iobuf3, "world");
201   iobuf1->prependChain(std::move(iobuf2));
202   iobuf1->prependChain(std::move(iobuf3));
203   EXPECT_EQ(3, iobuf1->countChainElements());
204   EXPECT_EQ(11, iobuf1->computeChainDataLength());
205
206   char buf[12];
207   memset(buf, 0, sizeof(buf));
208   Cursor(iobuf1.get()).pull(buf, 11);
209   EXPECT_EQ("hello world", std::string(buf));
210
211   memset(buf, 0, sizeof(buf));
212   EXPECT_EQ(11, Cursor(iobuf1.get()).pullAtMost(buf, 20));
213   EXPECT_EQ("hello world", std::string(buf));
214
215   EXPECT_THROW({Cursor(iobuf1.get()).pull(buf, 20);},
216                std::out_of_range);
217
218   {
219     RWPrivateCursor cursor(iobuf1.get());
220     auto b = cursor.peekBytes();
221     EXPECT_EQ("he", StringPiece(b));
222     cursor.skip(b.size());
223     b = cursor.peekBytes();
224     EXPECT_EQ("llo ", StringPiece(b));
225     cursor.skip(b.size());
226     b = cursor.peekBytes();
227     EXPECT_EQ("world", StringPiece(b));
228     cursor.skip(b.size());
229     EXPECT_EQ(3, iobuf1->countChainElements());
230     EXPECT_EQ(11, iobuf1->computeChainDataLength());
231   }
232
233   {
234     RWPrivateCursor cursor(iobuf1.get());
235     cursor.gather(11);
236     auto b = cursor.peekBytes();
237     EXPECT_EQ("hello world", StringPiece(b));
238     EXPECT_EQ(1, iobuf1->countChainElements());
239     EXPECT_EQ(11, iobuf1->computeChainDataLength());
240   }
241 }
242
243 TEST(IOBuf, pushCursorData) {
244   unique_ptr<IOBuf> iobuf1(IOBuf::create(20));
245   iobuf1->append(15);
246   iobuf1->trimStart(5);
247   unique_ptr<IOBuf> iobuf2(IOBuf::create(10));
248   unique_ptr<IOBuf> iobuf3(IOBuf::create(10));
249   iobuf3->append(10);
250
251   iobuf1->prependChain(std::move(iobuf2));
252   iobuf1->prependChain(std::move(iobuf3));
253   EXPECT_TRUE(iobuf1->isChained());
254
255   //write 20 bytes to the buffer chain
256   RWPrivateCursor wcursor(iobuf1.get());
257   EXPECT_FALSE(wcursor.isAtEnd());
258   wcursor.writeBE<uint64_t>(1);
259   wcursor.writeBE<uint64_t>(10);
260   wcursor.writeBE<uint32_t>(20);
261   EXPECT_TRUE(wcursor.isAtEnd());
262
263   // create a read buffer for the buffer chain
264   Cursor rcursor(iobuf1.get());
265   EXPECT_EQ(1, rcursor.readBE<uint64_t>());
266   EXPECT_EQ(10, rcursor.readBE<uint64_t>());
267   EXPECT_EQ(20, rcursor.readBE<uint32_t>());
268   EXPECT_EQ(0, rcursor.totalLength());
269   rcursor.reset(iobuf1.get());
270   EXPECT_EQ(20, rcursor.totalLength());
271
272   // create another write buffer
273   unique_ptr<IOBuf> iobuf4(IOBuf::create(30));
274   iobuf4->append(30);
275   RWPrivateCursor wcursor2(iobuf4.get());
276   // write buffer chain data into it, now wcursor2 should only
277   // have 10 bytes writable space
278   wcursor2.push(rcursor, 20);
279   EXPECT_EQ(wcursor2.totalLength(), 10);
280   // write again with not enough space in rcursor
281   EXPECT_THROW(wcursor2.push(rcursor, 20), std::out_of_range);
282
283   // create a read cursor to check iobuf3 data back
284   Cursor rcursor2(iobuf4.get());
285   EXPECT_EQ(1, rcursor2.readBE<uint64_t>());
286   EXPECT_EQ(10, rcursor2.readBE<uint64_t>());
287   EXPECT_EQ(20, rcursor2.readBE<uint32_t>());
288 }
289
290 TEST(IOBuf, Gather) {
291   std::unique_ptr<IOBuf> iobuf1(IOBuf::create(10));
292   append(iobuf1, "he");
293   std::unique_ptr<IOBuf> iobuf2(IOBuf::create(10));
294   append(iobuf2, "llo ");
295   std::unique_ptr<IOBuf> iobuf3(IOBuf::create(10));
296   append(iobuf3, "world");
297   iobuf1->prependChain(std::move(iobuf2));
298   iobuf1->prependChain(std::move(iobuf3));
299   EXPECT_EQ(3, iobuf1->countChainElements());
300   EXPECT_EQ(11, iobuf1->computeChainDataLength());
301
302   // Attempting to gather() more data than available in the chain should fail.
303   // Try from the very beginning of the chain.
304   RWPrivateCursor cursor(iobuf1.get());
305   EXPECT_THROW(cursor.gather(15), std::overflow_error);
306   // Now try from the middle of the chain
307   cursor += 3;
308   EXPECT_THROW(cursor.gather(10), std::overflow_error);
309
310   // Calling gatherAtMost() should succeed, however, and just gather
311   // as much as it can
312   cursor.gatherAtMost(10);
313   EXPECT_EQ(8, cursor.length());
314   EXPECT_EQ(8, cursor.totalLength());
315   EXPECT_FALSE(cursor.isAtEnd());
316   EXPECT_EQ("lo world",
317             folly::StringPiece(reinterpret_cast<const char*>(cursor.data()),
318                                cursor.length()));
319   EXPECT_EQ(2, iobuf1->countChainElements());
320   EXPECT_EQ(11, iobuf1->computeChainDataLength());
321
322   // Now try gather again on the chain head
323   cursor = RWPrivateCursor(iobuf1.get());
324   cursor.gather(5);
325   // Since gather() doesn't split buffers, everything should be collapsed into
326   // a single buffer now.
327   EXPECT_EQ(1, iobuf1->countChainElements());
328   EXPECT_EQ(11, iobuf1->computeChainDataLength());
329   EXPECT_EQ(11, cursor.length());
330   EXPECT_EQ(11, cursor.totalLength());
331 }
332
333 TEST(IOBuf, cloneAndInsert) {
334   std::unique_ptr<IOBuf> iobuf1(IOBuf::create(10));
335   append(iobuf1, "he");
336   std::unique_ptr<IOBuf> iobuf2(IOBuf::create(10));
337   append(iobuf2, "llo ");
338   std::unique_ptr<IOBuf> iobuf3(IOBuf::create(10));
339   append(iobuf3, "world");
340   iobuf1->prependChain(std::move(iobuf2));
341   iobuf1->prependChain(std::move(iobuf3));
342   EXPECT_EQ(3, iobuf1->countChainElements());
343   EXPECT_EQ(11, iobuf1->computeChainDataLength());
344
345   std::unique_ptr<IOBuf> cloned;
346
347   Cursor(iobuf1.get()).clone(cloned, 3);
348   EXPECT_EQ(2, cloned->countChainElements());
349   EXPECT_EQ(3, cloned->computeChainDataLength());
350
351
352   EXPECT_EQ(11, Cursor(iobuf1.get()).cloneAtMost(cloned, 20));
353   EXPECT_EQ(3, cloned->countChainElements());
354   EXPECT_EQ(11, cloned->computeChainDataLength());
355
356
357   EXPECT_THROW({Cursor(iobuf1.get()).clone(cloned, 20);},
358                std::out_of_range);
359
360   {
361     // Check that inserting in the middle of an iobuf splits
362     RWPrivateCursor cursor(iobuf1.get());
363     Cursor(iobuf1.get()).clone(cloned, 3);
364     EXPECT_EQ(2, cloned->countChainElements());
365     EXPECT_EQ(3, cloned->computeChainDataLength());
366
367     cursor.skip(1);
368
369     cursor.insert(std::move(cloned));
370     cursor.insert(folly::IOBuf::create(0));
371     EXPECT_EQ(4, cursor.getCurrentPosition());
372     EXPECT_EQ(7, iobuf1->countChainElements());
373     EXPECT_EQ(14, iobuf1->computeChainDataLength());
374     // Check that nextBuf got set correctly to the buffer with 1 byte left
375     EXPECT_EQ(1, cursor.peekBytes().size());
376     cursor.read<uint8_t>();
377   }
378
379   {
380     // Check that inserting at the end doesn't create empty buf
381     RWPrivateCursor cursor(iobuf1.get());
382     Cursor(iobuf1.get()).clone(cloned, 1);
383     EXPECT_EQ(1, cloned->countChainElements());
384     EXPECT_EQ(1, cloned->computeChainDataLength());
385
386     cursor.skip(1);
387
388     cursor.insert(std::move(cloned));
389     EXPECT_EQ(2, cursor.getCurrentPosition());
390     EXPECT_EQ(8, iobuf1->countChainElements());
391     EXPECT_EQ(15, iobuf1->computeChainDataLength());
392     // Check that nextBuf got set correctly
393     cursor.read<uint8_t>();
394   }
395   {
396     // Check that inserting at the beginning of a chunk (except first one)
397     // doesn't create empty buf
398     RWPrivateCursor cursor(iobuf1.get());
399     Cursor(iobuf1.get()).clone(cloned, 1);
400     EXPECT_EQ(1, cloned->countChainElements());
401     EXPECT_EQ(1, cloned->computeChainDataLength());
402
403     cursor.skip(1);
404
405     cursor.insert(std::move(cloned));
406     EXPECT_EQ(2, cursor.getCurrentPosition());
407     EXPECT_EQ(14, cursor.totalLength());
408     EXPECT_EQ(9, iobuf1->countChainElements());
409     EXPECT_EQ(16, iobuf1->computeChainDataLength());
410     // Check that nextBuf got set correctly
411     cursor.read<uint8_t>();
412   }
413   {
414     // Check that inserting at the beginning of a chain DOES keep an empty
415     // buffer.
416     RWPrivateCursor cursor(iobuf1.get());
417     Cursor(iobuf1.get()).clone(cloned, 1);
418     EXPECT_EQ(1, cloned->countChainElements());
419     EXPECT_EQ(1, cloned->computeChainDataLength());
420
421     cursor.insert(std::move(cloned));
422     EXPECT_EQ(1, cursor.getCurrentPosition());
423     EXPECT_EQ(16, cursor.totalLength());
424     EXPECT_EQ(11, iobuf1->countChainElements());
425     EXPECT_EQ(17, iobuf1->computeChainDataLength());
426     // Check that nextBuf got set correctly
427     cursor.read<uint8_t>();
428   }
429 }
430
431 TEST(IOBuf, cloneWithEmptyBufAtStart) {
432   folly::IOBufEqual eq;
433   auto empty = IOBuf::create(0);
434   auto hel = IOBuf::create(3);
435   append(hel, "hel");
436   auto lo = IOBuf::create(2);
437   append(lo, "lo");
438
439   auto iobuf = empty->clone();
440   iobuf->prependChain(hel->clone());
441   iobuf->prependChain(lo->clone());
442   iobuf->prependChain(empty->clone());
443   iobuf->prependChain(hel->clone());
444   iobuf->prependChain(lo->clone());
445   iobuf->prependChain(empty->clone());
446   iobuf->prependChain(lo->clone());
447   iobuf->prependChain(hel->clone());
448   iobuf->prependChain(lo->clone());
449   iobuf->prependChain(lo->clone());
450
451   Cursor cursor(iobuf.get());
452   std::unique_ptr<IOBuf> cloned;
453   char data[3];
454   cursor.pull(&data, 3);
455   cursor.clone(cloned, 2);
456   EXPECT_EQ(1, cloned->countChainElements());
457   EXPECT_EQ(2, cloned->length());
458   EXPECT_TRUE(eq(lo, cloned));
459
460   cursor.pull(&data, 3);
461   EXPECT_EQ("hel", std::string(data, sizeof(data)));
462
463   cursor.skip(2);
464   cursor.clone(cloned, 2);
465   EXPECT_TRUE(eq(lo, cloned));
466
467   std::string hello = cursor.readFixedString(5);
468   cursor.clone(cloned, 2);
469   EXPECT_TRUE(eq(lo, cloned));
470 }
471
472 TEST(IOBuf, Appender) {
473   std::unique_ptr<IOBuf> head(IOBuf::create(10));
474   append(head, "hello");
475
476   Appender app(head.get(), 10);
477   auto cap = head->capacity();
478   auto len1 = app.length();
479   EXPECT_EQ(cap - 5, len1);
480   app.ensure(len1);  // won't grow
481   EXPECT_EQ(len1, app.length());
482   app.ensure(len1 + 1);  // will grow
483   EXPECT_LE(len1 + 1, app.length());
484
485   append(app, " world");
486   EXPECT_EQ("hello world", toString(*head));
487 }
488
489 TEST(IOBuf, Printf) {
490   IOBuf head(IOBuf::CREATE, 24);
491   Appender app(&head, 32);
492
493   app.printf("%s", "test");
494   EXPECT_EQ(head.length(), 4);
495   EXPECT_EQ(0, memcmp(head.data(), "test\0", 5));
496
497   app.printf("%d%s %s%s %#x", 32, "this string is",
498              "longer than our original allocation size,",
499              "and will therefore require a new allocation", 0x12345678);
500   // The tailroom should start with a nul byte now.
501   EXPECT_GE(head.prev()->tailroom(), 1u);
502   EXPECT_EQ(0, *head.prev()->tail());
503
504   EXPECT_EQ("test32this string is longer than our original "
505             "allocation size,and will therefore require a "
506             "new allocation 0x12345678",
507             head.moveToFbString().toStdString());
508 }
509
510 TEST(IOBuf, Format) {
511   IOBuf head(IOBuf::CREATE, 24);
512   Appender app(&head, 32);
513
514   format("{}", "test")(app);
515   EXPECT_EQ(head.length(), 4);
516   EXPECT_EQ(0, memcmp(head.data(), "test", 4));
517
518   auto fmt = format("{}{} {}{} {:#x}",
519                     32, "this string is",
520                     "longer than our original allocation size,",
521                     "and will therefore require a new allocation",
522                     0x12345678);
523   fmt(app);
524   EXPECT_EQ("test32this string is longer than our original "
525             "allocation size,and will therefore require a "
526             "new allocation 0x12345678",
527             head.moveToFbString().toStdString());
528 }
529
530 TEST(IOBuf, QueueAppender) {
531   folly::IOBufQueue queue;
532
533   // Allocate 100 bytes at once, but don't grow past 1024
534   QueueAppender app(&queue, 100);
535   size_t n = 1024 / sizeof(uint32_t);
536   for (uint32_t i = 0; i < n; ++i) {
537     app.writeBE(i);
538   }
539
540   // There must be a goodMallocSize between 100 and 1024...
541   EXPECT_LT(1u, queue.front()->countChainElements());
542   const IOBuf* buf = queue.front();
543   do {
544     EXPECT_LE(100u, buf->capacity());
545     buf = buf->next();
546   } while (buf != queue.front());
547
548   Cursor cursor(queue.front());
549   for (uint32_t i = 0; i < n; ++i) {
550     EXPECT_EQ(i, cursor.readBE<uint32_t>());
551   }
552
553   EXPECT_THROW({cursor.readBE<uint32_t>();}, std::out_of_range);
554 }
555
556 TEST(IOBuf, QueueAppenderPushAtMostFillBuffer) {
557   folly::IOBufQueue queue;
558   // There should be a goodMallocSize between 125 and 1000
559   QueueAppender appender{&queue, 125};
560   std::vector<uint8_t> data;
561   data.resize(1000);
562   std::iota(data.begin(), data.end(), uint8_t(0));
563   // Add 100 byte
564   appender.pushAtMost(data.data(), 100);
565   // Add 900 bytes
566   appender.pushAtMost(data.data() + 100, data.size() - 100);
567   const auto buf = queue.front();
568   // Should fill the current buffer before adding another
569   EXPECT_LE(2, buf->countChainElements());
570   EXPECT_EQ(0, buf->tailroom());
571   EXPECT_LE(125, buf->length());
572   EXPECT_EQ(1000, buf->computeChainDataLength());
573   const StringPiece sp{(const char*)data.data(), data.size()};
574   EXPECT_EQ(sp, toString(*buf));
575 }
576
577 TEST(IOBuf, QueueAppenderInsertOwn) {
578   auto buf = IOBuf::create(10);
579   folly::IOBufQueue queue;
580   QueueAppender appender{&queue, 128};
581   appender.insert(std::move(buf));
582
583   std::vector<uint8_t> data;
584   data.resize(256);
585   std::iota(data.begin(), data.end(), 0);
586   appender.pushAtMost(folly::range(data));
587   // Buffer is owned, so we should write to it
588   EXPECT_LE(2, queue.front()->countChainElements());
589   EXPECT_EQ(0, queue.front()->tailroom());
590   const StringPiece sp{(const char*)data.data(), data.size()};
591   EXPECT_EQ(sp, toString(*queue.front()));
592 }
593
594 TEST(IOBuf, QueueAppenderInsertClone) {
595   IOBuf buf{IOBuf::CREATE, 100};
596   folly::IOBufQueue queue;
597   QueueAppender appender{&queue, 100};
598   // Buffer is shared, so we create a new buffer to write to
599   appender.insert(buf);
600   uint8_t x = 42;
601   appender.pushAtMost(&x, 1);
602   EXPECT_EQ(2, queue.front()->countChainElements());
603   EXPECT_EQ(0, queue.front()->length());
604   EXPECT_LT(0, queue.front()->tailroom());
605   EXPECT_EQ(1, queue.front()->next()->length());
606   EXPECT_EQ(x, queue.front()->next()->data()[0]);
607 }
608
609 TEST(IOBuf, CursorOperators) {
610   // Test operators on a single-item chain
611   {
612     std::unique_ptr<IOBuf> chain1(IOBuf::create(20));
613     chain1->append(10);
614
615     Cursor curs1(chain1.get());
616     EXPECT_EQ(0, curs1 - chain1.get());
617     EXPECT_FALSE(curs1.isAtEnd());
618     curs1.skip(3);
619     EXPECT_EQ(3, curs1 - chain1.get());
620     EXPECT_FALSE(curs1.isAtEnd());
621     curs1.skip(7);
622     EXPECT_EQ(10, curs1 - chain1.get());
623     EXPECT_TRUE(curs1.isAtEnd());
624
625     Cursor curs2(chain1.get());
626     EXPECT_EQ(0, curs2 - chain1.get());
627     EXPECT_EQ(10, curs1 - curs2);
628     EXPECT_THROW(curs2 - curs1, std::out_of_range);
629   }
630
631   // Test cross-chain operations
632   {
633     std::unique_ptr<IOBuf> chain1(IOBuf::create(20));
634     chain1->append(10);
635     std::unique_ptr<IOBuf> chain2 = chain1->clone();
636
637     Cursor curs1(chain1.get());
638     Cursor curs2(chain2.get());
639     EXPECT_THROW(curs1 - curs2, std::out_of_range);
640     EXPECT_THROW(curs1 - chain2.get(), std::out_of_range);
641   }
642
643   // Test operations on multi-item chains
644   {
645     std::unique_ptr<IOBuf> chain(IOBuf::create(20));
646     chain->append(10);
647     chain->appendChain(chain->clone());
648     EXPECT_EQ(20, chain->computeChainDataLength());
649
650     Cursor curs1(chain.get());
651     curs1.skip(5);
652     Cursor curs2(chain.get());
653     curs2.skip(3);
654     EXPECT_EQ(2, curs1 - curs2);
655     EXPECT_EQ(5, curs1 - chain.get());
656     EXPECT_THROW(curs2 - curs1, std::out_of_range);
657
658     curs1.skip(7);
659     EXPECT_EQ(9, curs1 - curs2);
660     EXPECT_EQ(12, curs1 - chain.get());
661     EXPECT_THROW(curs2 - curs1, std::out_of_range);
662
663     curs2.skip(7);
664     EXPECT_EQ(2, curs1 - curs2);
665     EXPECT_THROW(curs2 - curs1, std::out_of_range);
666   }
667
668   // Test isAtEnd() with empty buffers at the end of a chain
669   {
670     auto iobuf1 = IOBuf::create(20);
671     iobuf1->append(15);
672     iobuf1->trimStart(5);
673
674     Cursor c(iobuf1.get());
675     EXPECT_FALSE(c.isAtEnd());
676     c.skip(10);
677     EXPECT_TRUE(c.isAtEnd());
678
679     iobuf1->prependChain(IOBuf::create(10));
680     iobuf1->prependChain(IOBuf::create(10));
681     EXPECT_TRUE(c.isAtEnd());
682     iobuf1->prev()->append(5);
683     EXPECT_FALSE(c.isAtEnd());
684     c.skip(5);
685     EXPECT_TRUE(c.isAtEnd());
686   }
687
688   // Test canAdvance with a chain of items
689   {
690     auto chain = IOBuf::create(10);
691     chain->append(10);
692     chain->appendChain(chain->clone());
693     EXPECT_EQ(2, chain->countChainElements());
694     EXPECT_EQ(20, chain->computeChainDataLength());
695
696     Cursor c(chain.get());
697     for (size_t i = 0; i <= 20; ++i) {
698       EXPECT_TRUE(c.canAdvance(i));
699     }
700     EXPECT_FALSE(c.canAdvance(21));
701     c.skip(10);
702     EXPECT_TRUE(c.canAdvance(10));
703     EXPECT_FALSE(c.canAdvance(11));
704   }
705 }
706
707 TEST(IOBuf, StringOperations) {
708   // Test a single buffer with two null-terminated strings and an extra uint8_t
709   // at the end
710   {
711     std::unique_ptr<IOBuf> chain(IOBuf::create(16));
712     Appender app(chain.get(), 0);
713     app.push(reinterpret_cast<const uint8_t*>("hello\0world\0\x01"), 13);
714
715     Cursor curs(chain.get());
716     EXPECT_STREQ("hello", curs.readTerminatedString().c_str());
717     EXPECT_STREQ("world", curs.readTerminatedString().c_str());
718     EXPECT_EQ(1, curs.read<uint8_t>());
719   }
720
721   // Test multiple buffers where the first is empty and the string starts in
722   // the second buffer.
723   {
724     std::unique_ptr<IOBuf> chain(IOBuf::create(8));
725     chain->prependChain(IOBuf::create(12));
726     Appender app(chain.get(), 0);
727     app.push(reinterpret_cast<const uint8_t*>("hello world\0"), 12);
728
729     Cursor curs(chain.get());
730     EXPECT_STREQ("hello world", curs.readTerminatedString().c_str());
731   }
732
733   // Test multiple buffers with a single null-terminated string spanning them
734   {
735     std::unique_ptr<IOBuf> chain(IOBuf::create(8));
736     chain->prependChain(IOBuf::create(8));
737     chain->append(8);
738     chain->next()->append(4);
739     RWPrivateCursor rwc(chain.get());
740     rwc.push(reinterpret_cast<const uint8_t*>("hello world\0"), 12);
741
742     Cursor curs(chain.get());
743     EXPECT_STREQ("hello world", curs.readTerminatedString().c_str());
744   }
745
746   // Test a reading a null-terminated string that's longer than the maximum
747   // allowable length
748   {
749     std::unique_ptr<IOBuf> chain(IOBuf::create(16));
750     Appender app(chain.get(), 0);
751     app.push(reinterpret_cast<const uint8_t*>("hello world\0"), 12);
752
753     Cursor curs(chain.get());
754     EXPECT_THROW(curs.readTerminatedString('\0', 5), std::length_error);
755   }
756
757   // Test reading a null-terminated string from a chain with an empty buffer at
758   // the front
759   {
760     std::unique_ptr<IOBuf> buf(IOBuf::create(8));
761     Appender app(buf.get(), 0);
762     app.push(reinterpret_cast<const uint8_t*>("hello\0"), 6);
763     std::unique_ptr<IOBuf> chain(IOBuf::create(8));
764     chain->prependChain(std::move(buf));
765
766     Cursor curs(chain.get());
767     EXPECT_STREQ("hello", curs.readTerminatedString().c_str());
768   }
769
770   // Test reading a null-terminated string from a chain that doesn't contain the
771   // terminator
772   {
773     std::unique_ptr<IOBuf> buf(IOBuf::create(8));
774     Appender app(buf.get(), 0);
775     app.push(reinterpret_cast<const uint8_t*>("hello"), 5);
776     std::unique_ptr<IOBuf> chain(IOBuf::create(8));
777     chain->prependChain(std::move(buf));
778
779     Cursor curs(chain.get());
780     EXPECT_THROW(curs.readTerminatedString(),
781                  std::out_of_range);
782   }
783
784   // Test reading a null-terminated string past the maximum length
785   {
786     std::unique_ptr<IOBuf> buf(IOBuf::create(8));
787     Appender app(buf.get(), 0);
788     app.push(reinterpret_cast<const uint8_t*>("hello\0"), 6);
789     std::unique_ptr<IOBuf> chain(IOBuf::create(8));
790     chain->prependChain(std::move(buf));
791
792     Cursor curs(chain.get());
793     EXPECT_THROW(curs.readTerminatedString('\0', 3),
794                  std::length_error);
795   }
796
797   // Test reading a two fixed-length strings from a single buffer with an extra
798   // uint8_t at the end
799   {
800     std::unique_ptr<IOBuf> chain(IOBuf::create(16));
801     Appender app(chain.get(), 0);
802     app.push(reinterpret_cast<const uint8_t*>("helloworld\x01"), 11);
803
804     Cursor curs(chain.get());
805     EXPECT_STREQ("hello", curs.readFixedString(5).c_str());
806     EXPECT_STREQ("world", curs.readFixedString(5).c_str());
807     EXPECT_EQ(1, curs.read<uint8_t>());
808   }
809
810   // Test multiple buffers where the first is empty and a fixed-length string
811   // starts in the second buffer.
812   {
813     std::unique_ptr<IOBuf> chain(IOBuf::create(8));
814     chain->prependChain(IOBuf::create(16));
815     Appender app(chain.get(), 0);
816     app.push(reinterpret_cast<const uint8_t*>("hello world"), 11);
817
818     Cursor curs(chain.get());
819     EXPECT_STREQ("hello world", curs.readFixedString(11).c_str());
820   }
821
822   // Test multiple buffers with a single fixed-length string spanning them
823   {
824     std::unique_ptr<IOBuf> chain(IOBuf::create(8));
825     chain->prependChain(IOBuf::create(8));
826     chain->append(7);
827     chain->next()->append(4);
828     RWPrivateCursor rwc(chain.get());
829     rwc.push(reinterpret_cast<const uint8_t*>("hello world"), 11);
830
831     Cursor curs(chain.get());
832     EXPECT_STREQ("hello world", curs.readFixedString(11).c_str());
833   }
834
835   // Test reading a fixed-length string from a chain with an empty buffer at
836   // the front
837   {
838     std::unique_ptr<IOBuf> buf(IOBuf::create(8));
839     Appender app(buf.get(), 0);
840     app.push(reinterpret_cast<const uint8_t*>("hello"), 5);
841     std::unique_ptr<IOBuf> chain(IOBuf::create(8));
842     chain->prependChain(std::move(buf));
843
844     Cursor curs(chain.get());
845     EXPECT_STREQ("hello", curs.readFixedString(5).c_str());
846   }
847 }
848
849 TEST(IOBuf, ReadWhileTrue) {
850   auto isAlpha = [](uint8_t ch) {
851     return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
852   };
853   auto isDigit = [](uint8_t ch) { return (ch >= '0' && ch <= '9'); };
854
855   // Test reading alternating alphabetic and numeric strings
856   {
857     std::unique_ptr<IOBuf> chain(IOBuf::create(32));
858     Appender app(chain.get(), 0);
859     app.push(StringPiece("hello123world456"));
860
861     Cursor curs(chain.get());
862     EXPECT_STREQ("hello", curs.readWhile(isAlpha).c_str());
863     EXPECT_STREQ("123", curs.readWhile(isDigit).c_str());
864     EXPECT_STREQ("world", curs.readWhile(isAlpha).c_str());
865     EXPECT_STREQ("456", curs.readWhile(isDigit).c_str());
866     EXPECT_TRUE(curs.isAtEnd());
867   }
868
869   // The same, but also use skipWhile()
870   {
871     std::unique_ptr<IOBuf> chain(IOBuf::create(16));
872     Appender app(chain.get(), 0);
873     app.push(StringPiece("hello123world456"));
874
875     Cursor curs(chain.get());
876     EXPECT_STREQ("hello", curs.readWhile(isAlpha).c_str());
877     curs.skipWhile(isDigit);
878     curs.skipWhile(isAlpha);
879     EXPECT_STREQ("456", curs.readWhile(isDigit).c_str());
880     EXPECT_TRUE(curs.isAtEnd());
881   }
882
883   // Test readWhile() using data split across multiple buffers,
884   // including some empty buffers in the middle of the chain.
885   {
886     std::unique_ptr<IOBuf> chain;
887
888     // First element in the chain has "he"
889     auto buf = IOBuf::create(40);
890     Appender app(buf.get(), 0);
891     app.push(StringPiece("he"));
892     chain = std::move(buf);
893
894     // The second element has "ll", after 10 bytes of headroom
895     buf = IOBuf::create(40);
896     buf->advance(10);
897     app = Appender{buf.get(), 0};
898     app.push(StringPiece("ll"));
899     chain->prependChain(std::move(buf));
900
901     // The third element is empty
902     buf = IOBuf::create(40);
903     buf->advance(15);
904     chain->prependChain(std::move(buf));
905
906     // The fourth element has "o12"
907     buf = IOBuf::create(40);
908     buf->advance(37);
909     app = Appender{buf.get(), 0};
910     app.push(StringPiece("o12"));
911     chain->prependChain(std::move(buf));
912
913     // The fifth element has "3"
914     buf = IOBuf::create(40);
915     app = Appender{buf.get(), 0};
916     app.push(StringPiece("3"));
917     chain->prependChain(std::move(buf));
918
919     // The sixth element is empty
920     buf = IOBuf::create(40);
921     chain->prependChain(std::move(buf));
922
923     // The seventh element has "world456"
924     buf = IOBuf::create(40);
925     app = Appender{buf.get(), 0};
926     app.push(StringPiece("world456"));
927     chain->prependChain(std::move(buf));
928
929     // The eighth element is empty
930     buf = IOBuf::create(40);
931     chain->prependChain(std::move(buf));
932
933     Cursor curs(chain.get());
934     EXPECT_STREQ("hello", curs.readWhile(isAlpha).c_str());
935     EXPECT_STREQ("123", curs.readWhile(isDigit).c_str());
936     EXPECT_STREQ("world", curs.readWhile(isAlpha).c_str());
937     EXPECT_STREQ("456", curs.readWhile(isDigit).c_str());
938     EXPECT_TRUE(curs.isAtEnd());
939   }
940 }
941
942 TEST(IOBuf, TestAdvanceToEndSingle) {
943   std::unique_ptr<IOBuf> chain(IOBuf::create(10));
944   chain->append(10);
945
946   Cursor curs(chain.get());
947   curs.advanceToEnd();
948   EXPECT_TRUE(curs.isAtEnd());
949   EXPECT_EQ(curs - chain.get(), 10);
950 }
951
952 TEST(IOBuf, TestAdvanceToEndMulti) {
953   std::unique_ptr<IOBuf> chain(IOBuf::create(10));
954   chain->append(10);
955
956   std::unique_ptr<IOBuf> buf(IOBuf::create(5));
957   buf->append(5);
958   chain->prependChain(std::move(buf));
959
960   buf = IOBuf::create(20);
961   buf->append(20);
962   chain->prependChain(std::move(buf));
963
964   Cursor curs(chain.get());
965   curs.advanceToEnd();
966   EXPECT_TRUE(curs.isAtEnd());
967   EXPECT_EQ(curs - chain.get(), 35);
968
969   curs.reset(chain.get());
970   curs.skip(12);
971   curs.advanceToEnd();
972   EXPECT_TRUE(curs.isAtEnd());
973 }
974
975 TEST(IOBuf, TestRetreatSingle) {
976   std::unique_ptr<IOBuf> chain(IOBuf::create(20));
977   chain->append(20);
978
979   Cursor curs(chain.get());
980   EXPECT_EQ(curs.retreatAtMost(0), 0);
981   EXPECT_EQ(curs.totalLength(), 20);
982   EXPECT_EQ(curs.retreatAtMost(5), 0);
983   EXPECT_EQ(curs.totalLength(), 20);
984   EXPECT_EQ(curs.retreatAtMost(25), 0);
985   EXPECT_EQ(curs.totalLength(), 20);
986
987   curs.retreat(0);
988   EXPECT_THROW(curs.retreat(5), std::out_of_range);
989   curs.reset(chain.get());
990   EXPECT_THROW(curs.retreat(25), std::out_of_range);
991   curs.reset(chain.get());
992
993   curs.advanceToEnd();
994   curs.retreat(5);
995   EXPECT_EQ(curs.totalLength(), 5);
996   curs.retreat(10);
997   EXPECT_EQ(curs.totalLength(), 15);
998   EXPECT_THROW(curs.retreat(10), std::out_of_range);
999
1000   curs.reset(chain.get());
1001   curs.advanceToEnd();
1002   EXPECT_EQ(curs.retreatAtMost(5), 5);
1003   EXPECT_EQ(curs.totalLength(), 5);
1004   EXPECT_EQ(curs.retreatAtMost(10), 10);
1005   EXPECT_EQ(curs.totalLength(), 15);
1006   EXPECT_EQ(curs.retreatAtMost(10), 5);
1007   EXPECT_EQ(curs.totalLength(), 20);
1008 }
1009
1010 TEST(IOBuf, TestRetreatMulti) {
1011   std::unique_ptr<IOBuf> chain(IOBuf::create(10));
1012   chain->append(10);
1013
1014   std::unique_ptr<IOBuf> buf(IOBuf::create(5));
1015   buf->append(5);
1016   chain->prependChain(std::move(buf));
1017
1018   buf = IOBuf::create(20);
1019   buf->append(20);
1020   chain->prependChain(std::move(buf));
1021
1022   Cursor curs(chain.get());
1023   EXPECT_EQ(curs.retreatAtMost(10), 0);
1024   EXPECT_THROW(curs.retreat(10), std::out_of_range);
1025   curs.reset(chain.get());
1026
1027   curs.advanceToEnd();
1028   curs.retreat(20);
1029   EXPECT_EQ(curs.totalLength(), 20);
1030   EXPECT_EQ(curs.length(), 20);
1031   curs.retreat(1);
1032   EXPECT_EQ(curs.totalLength(), 21);
1033   EXPECT_EQ(curs.length(), 1);
1034   EXPECT_EQ(curs.retreatAtMost(50), 14);
1035   EXPECT_EQ(curs.totalLength(), 35);
1036
1037   curs.advanceToEnd();
1038   curs.retreat(30);
1039   EXPECT_EQ(curs.totalLength(), 30);
1040 }
1041
1042 TEST(IOBuf, TestRetreatOperators) {
1043   std::unique_ptr<IOBuf> chain(IOBuf::create(20));
1044   chain->append(20);
1045
1046   Cursor curs(chain.get());
1047   curs.advanceToEnd();
1048   curs -= 5;
1049   EXPECT_EQ(curs.totalLength(), 5);
1050
1051   curs.advanceToEnd();
1052   auto retreated = curs - 5;
1053   EXPECT_EQ(retreated.totalLength(), 5);
1054   EXPECT_EQ(curs.totalLength(), 0);
1055 }
1056
1057 TEST(IOBuf, tryRead) {
1058   unique_ptr<IOBuf> iobuf1(IOBuf::create(6));
1059   iobuf1->append(6);
1060   unique_ptr<IOBuf> iobuf2(IOBuf::create(24));
1061   iobuf2->append(24);
1062
1063   iobuf1->prependChain(std::move(iobuf2));
1064
1065   EXPECT_TRUE(iobuf1->isChained());
1066
1067   RWPrivateCursor wcursor(iobuf1.get());
1068   Cursor rcursor(iobuf1.get());
1069   wcursor.writeLE((uint32_t)1);
1070   wcursor.writeLE((uint64_t)1);
1071   wcursor.writeLE((uint64_t)1);
1072   wcursor.writeLE((uint64_t)1);
1073   wcursor.writeLE((uint16_t)1);
1074   EXPECT_EQ(0, wcursor.totalLength());
1075
1076   EXPECT_EQ(1u, rcursor.readLE<uint32_t>());
1077
1078   EXPECT_EQ(1u, rcursor.readLE<uint32_t>());
1079   EXPECT_EQ(0u, rcursor.readLE<uint32_t>());
1080
1081   EXPECT_EQ(1u, rcursor.readLE<uint32_t>());
1082   rcursor.skip(4);
1083
1084   uint32_t val;
1085   EXPECT_TRUE(rcursor.tryRead(val));
1086   EXPECT_EQ(1, val);
1087   EXPECT_TRUE(rcursor.tryRead(val));
1088
1089   EXPECT_EQ(0, val);
1090   EXPECT_FALSE(rcursor.tryRead(val));
1091 }
1092
1093 TEST(IOBuf, tryReadLE) {
1094   IOBuf buf{IOBuf::CREATE, 4};
1095   buf.append(4);
1096
1097   RWPrivateCursor wcursor(&buf);
1098   Cursor rcursor(&buf);
1099
1100   const uint32_t expected = 0x01020304;
1101   wcursor.writeLE(expected);
1102   uint32_t actual;
1103   EXPECT_TRUE(rcursor.tryReadLE(actual));
1104   EXPECT_EQ(expected, actual);
1105 }
1106
1107 TEST(IOBuf, tryReadBE) {
1108   IOBuf buf{IOBuf::CREATE, 4};
1109   buf.append(4);
1110
1111   RWPrivateCursor wcursor(&buf);
1112   Cursor rcursor(&buf);
1113
1114   const uint32_t expected = 0x01020304;
1115   wcursor.writeBE(expected);
1116   uint32_t actual;
1117   EXPECT_TRUE(rcursor.tryReadBE(actual));
1118   EXPECT_EQ(expected, actual);
1119 }
1120
1121 TEST(IOBuf, tryReadConsumesAllInputOnFailure) {
1122   IOBuf buf{IOBuf::CREATE, 2};
1123   buf.append(2);
1124
1125   Cursor rcursor(&buf);
1126   uint32_t val;
1127   EXPECT_FALSE(rcursor.tryRead(val));
1128   EXPECT_EQ(0, rcursor.totalLength());
1129 }
1130
1131 TEST(IOBuf, readConsumesAllInputOnFailure) {
1132   IOBuf buf{IOBuf::CREATE, 2};
1133   buf.append(2);
1134
1135   Cursor rcursor(&buf);
1136   EXPECT_THROW(rcursor.read<uint32_t>(), std::out_of_range);
1137   EXPECT_EQ(0, rcursor.totalLength());
1138 }
1139
1140 TEST(IOBuf, pushEmptyByteRange) {
1141   // Test pushing an empty ByteRange.  This mainly tests that we do not
1142   // trigger UBSAN warnings by calling memcpy() with an null source pointer,
1143   // which is undefined behavior even if the length is 0.
1144   IOBuf buf{IOBuf::CREATE, 2};
1145   ByteRange emptyBytes;
1146
1147   // Test calling Cursor::push()
1148   RWPrivateCursor wcursor(&buf);
1149   wcursor.push(emptyBytes);
1150   EXPECT_EQ(0, buf.computeChainDataLength());
1151
1152   // Test calling Appender::push()
1153   Appender app(&buf, 16);
1154   app.push(emptyBytes);
1155   EXPECT_EQ(0, buf.computeChainDataLength());
1156 }
1157
1158 TEST(IOBuf, positionTracking) {
1159   unique_ptr<IOBuf> iobuf1(IOBuf::create(6));
1160   iobuf1->append(6);
1161   unique_ptr<IOBuf> iobuf2(IOBuf::create(24));
1162   iobuf2->append(24);
1163   iobuf1->prependChain(std::move(iobuf2));
1164
1165   Cursor cursor(iobuf1.get());
1166
1167   EXPECT_EQ(0, cursor.getCurrentPosition());
1168   EXPECT_EQ(6, cursor.length());
1169
1170   cursor.skip(3);
1171   EXPECT_EQ(3, cursor.getCurrentPosition());
1172   EXPECT_EQ(3, cursor.length());
1173
1174   // Test that we properly handle advancing to the next chunk.
1175   cursor.skip(4);
1176   EXPECT_EQ(7, cursor.getCurrentPosition());
1177   EXPECT_EQ(23, cursor.length());
1178
1179   // Test that we properly handle doing to the previous chunk.
1180   cursor.retreat(2);
1181   EXPECT_EQ(5, cursor.getCurrentPosition());
1182   EXPECT_EQ(1, cursor.length());
1183
1184   // Test that we properly handle advanceToEnd
1185   cursor.advanceToEnd();
1186   EXPECT_EQ(30, cursor.getCurrentPosition());
1187   EXPECT_EQ(0, cursor.totalLength());
1188
1189   // Reset to 0.
1190   cursor.reset(iobuf1.get());
1191   EXPECT_EQ(0, cursor.getCurrentPosition());
1192   EXPECT_EQ(30, cursor.totalLength());
1193 }