a615496c1d8e9a9abaedb5fde82d3a2cba23d374
[folly.git] / folly / io / test / IOBufTest.cpp
1 /*
2  * Copyright 2016 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
17 #include <folly/io/IOBuf.h>
18 #include <folly/io/TypedIOBuf.h>
19
20 #include <cstddef>
21
22 #include <boost/random.hpp>
23
24 #include <folly/Malloc.h>
25 #include <folly/Range.h>
26 #include <folly/portability/GTest.h>
27
28 using folly::fbstring;
29 using folly::fbvector;
30 using folly::IOBuf;
31 using folly::TypedIOBuf;
32 using folly::StringPiece;
33 using folly::ByteRange;
34 using std::unique_ptr;
35
36 void append(std::unique_ptr<IOBuf>& buf, StringPiece str) {
37   EXPECT_LE(str.size(), buf->tailroom());
38   memcpy(buf->writableData(), str.data(), str.size());
39   buf->append(str.size());
40 }
41
42 void prepend(std::unique_ptr<IOBuf>& buf, StringPiece str) {
43   EXPECT_LE(str.size(), buf->headroom());
44   memcpy(buf->writableData() - str.size(), str.data(), str.size());
45   buf->prepend(str.size());
46 }
47
48 TEST(IOBuf, Simple) {
49   unique_ptr<IOBuf> buf(IOBuf::create(100));
50   uint32_t cap = buf->capacity();
51   EXPECT_LE(100, cap);
52   EXPECT_EQ(0, buf->headroom());
53   EXPECT_EQ(0, buf->length());
54   EXPECT_EQ(cap, buf->tailroom());
55
56   append(buf, "world");
57   buf->advance(10);
58   EXPECT_EQ(10, buf->headroom());
59   EXPECT_EQ(5, buf->length());
60   EXPECT_EQ(cap - 15, buf->tailroom());
61
62   prepend(buf, "hello ");
63   EXPECT_EQ(4, buf->headroom());
64   EXPECT_EQ(11, buf->length());
65   EXPECT_EQ(cap - 15, buf->tailroom());
66
67   const char* p = reinterpret_cast<const char*>(buf->data());
68   EXPECT_EQ("hello world", std::string(p, buf->length()));
69
70   buf->clear();
71   EXPECT_EQ(0, buf->headroom());
72   EXPECT_EQ(0, buf->length());
73   EXPECT_EQ(cap, buf->tailroom());
74 }
75
76
77 void testAllocSize(uint32_t requestedCapacity) {
78   unique_ptr<IOBuf> iobuf(IOBuf::create(requestedCapacity));
79   EXPECT_GE(iobuf->capacity(), requestedCapacity);
80 }
81
82 TEST(IOBuf, AllocSizes) {
83   // Try with a small allocation size that should fit in the internal buffer
84   testAllocSize(28);
85
86   // Try with a large allocation size that will require an external buffer.
87   testAllocSize(9000);
88
89   // 220 bytes is currently the cutoff
90   // (It would be nice to use the IOBuf::kMaxInternalDataSize constant,
91   // but it's private and it doesn't seem worth making it public just for this
92   // test code.)
93   testAllocSize(220);
94   testAllocSize(219);
95   testAllocSize(221);
96 }
97
98 void deleteArrayBuffer(void *buf, void* arg) {
99   uint32_t* deleteCount = static_cast<uint32_t*>(arg);
100   ++(*deleteCount);
101   uint8_t* bufPtr = static_cast<uint8_t*>(buf);
102   delete[] bufPtr;
103 }
104
105 TEST(IOBuf, TakeOwnership) {
106   uint32_t size1 = 99;
107   uint8_t *buf1 = static_cast<uint8_t*>(malloc(size1));
108   unique_ptr<IOBuf> iobuf1(IOBuf::takeOwnership(buf1, size1));
109   EXPECT_EQ(buf1, iobuf1->data());
110   EXPECT_EQ(size1, iobuf1->length());
111   EXPECT_EQ(buf1, iobuf1->buffer());
112   EXPECT_EQ(size1, iobuf1->capacity());
113
114   uint32_t deleteCount = 0;
115   uint32_t size2 = 4321;
116   uint8_t *buf2 = new uint8_t[size2];
117   unique_ptr<IOBuf> iobuf2(IOBuf::takeOwnership(buf2, size2,
118                                                 deleteArrayBuffer,
119                                                 &deleteCount));
120   EXPECT_EQ(buf2, iobuf2->data());
121   EXPECT_EQ(size2, iobuf2->length());
122   EXPECT_EQ(buf2, iobuf2->buffer());
123   EXPECT_EQ(size2, iobuf2->capacity());
124   EXPECT_EQ(0, deleteCount);
125   iobuf2.reset();
126   EXPECT_EQ(1, deleteCount);
127
128   deleteCount = 0;
129   uint32_t size3 = 3456;
130   uint8_t *buf3 = new uint8_t[size3];
131   uint32_t length3 = 48;
132   unique_ptr<IOBuf> iobuf3(IOBuf::takeOwnership(buf3, size3, length3,
133                                                 deleteArrayBuffer,
134                                                 &deleteCount));
135   EXPECT_EQ(buf3, iobuf3->data());
136   EXPECT_EQ(length3, iobuf3->length());
137   EXPECT_EQ(buf3, iobuf3->buffer());
138   EXPECT_EQ(size3, iobuf3->capacity());
139   EXPECT_EQ(0, deleteCount);
140   iobuf3.reset();
141   EXPECT_EQ(1, deleteCount);
142
143   deleteCount = 0;
144   {
145     uint32_t size4 = 1234;
146     uint8_t *buf4 = new uint8_t[size4];
147     uint32_t length4 = 48;
148     IOBuf iobuf4(IOBuf::TAKE_OWNERSHIP, buf4, size4, length4,
149                  deleteArrayBuffer, &deleteCount);
150     EXPECT_EQ(buf4, iobuf4.data());
151     EXPECT_EQ(length4, iobuf4.length());
152     EXPECT_EQ(buf4, iobuf4.buffer());
153     EXPECT_EQ(size4, iobuf4.capacity());
154
155     IOBuf iobuf5 = std::move(iobuf4);
156     EXPECT_EQ(buf4, iobuf5.data());
157     EXPECT_EQ(length4, iobuf5.length());
158     EXPECT_EQ(buf4, iobuf5.buffer());
159     EXPECT_EQ(size4, iobuf5.capacity());
160     EXPECT_EQ(0, deleteCount);
161   }
162   EXPECT_EQ(1, deleteCount);
163 }
164
165 TEST(IOBuf, WrapBuffer) {
166   const uint32_t size1 = 1234;
167   uint8_t buf1[size1];
168   unique_ptr<IOBuf> iobuf1(IOBuf::wrapBuffer(buf1, size1));
169   EXPECT_EQ(buf1, iobuf1->data());
170   EXPECT_EQ(size1, iobuf1->length());
171   EXPECT_EQ(buf1, iobuf1->buffer());
172   EXPECT_EQ(size1, iobuf1->capacity());
173
174   uint32_t size2 = 0x1234;
175   unique_ptr<uint8_t[]> buf2(new uint8_t[size2]);
176   unique_ptr<IOBuf> iobuf2(IOBuf::wrapBuffer(buf2.get(), size2));
177   EXPECT_EQ(buf2.get(), iobuf2->data());
178   EXPECT_EQ(size2, iobuf2->length());
179   EXPECT_EQ(buf2.get(), iobuf2->buffer());
180   EXPECT_EQ(size2, iobuf2->capacity());
181
182   uint32_t size3 = 4321;
183   unique_ptr<uint8_t[]> buf3(new uint8_t[size3]);
184   IOBuf iobuf3(IOBuf::WRAP_BUFFER, buf3.get(), size3);
185   EXPECT_EQ(buf3.get(), iobuf3.data());
186   EXPECT_EQ(size3, iobuf3.length());
187   EXPECT_EQ(buf3.get(), iobuf3.buffer());
188   EXPECT_EQ(size3, iobuf3.capacity());
189
190   const uint32_t size4 = 2345;
191   unique_ptr<uint8_t[]> buf4(new uint8_t[size4]);
192   IOBuf iobuf4 = IOBuf::wrapBufferAsValue(buf4.get(), size4);
193   EXPECT_EQ(buf4.get(), iobuf4.data());
194   EXPECT_EQ(size4, iobuf4.length());
195   EXPECT_EQ(buf4.get(), iobuf4.buffer());
196   EXPECT_EQ(size4, iobuf4.capacity());
197 }
198
199 TEST(IOBuf, CreateCombined) {
200   // Create a combined IOBuf, then destroy it.
201   // The data buffer and IOBuf both become unused as part of the destruction
202   {
203     auto buf = IOBuf::createCombined(256);
204     EXPECT_FALSE(buf->isShared());
205   }
206
207   // Create a combined IOBuf, clone from it, and then destroy the original
208   // IOBuf.  The data buffer cannot be deleted until the clone is also
209   // destroyed.
210   {
211     auto bufA = IOBuf::createCombined(256);
212     EXPECT_FALSE(bufA->isShared());
213     auto bufB = bufA->clone();
214     EXPECT_TRUE(bufA->isShared());
215     EXPECT_TRUE(bufB->isShared());
216     bufA.reset();
217     EXPECT_FALSE(bufB->isShared());
218   }
219
220   // Create a combined IOBuf, then call reserve() to get a larger buffer.
221   // The IOBuf no longer points to the combined data buffer, but the
222   // overall memory segment cannot be deleted until the IOBuf is also
223   // destroyed.
224   {
225     auto buf = IOBuf::createCombined(256);
226     buf->reserve(0, buf->capacity() + 100);
227   }
228
229   // Create a combined IOBuf, clone from it, then call unshare() on the original
230   // buffer.  This creates a situation where bufB is pointing at the combined
231   // buffer associated with bufA, but bufA is now using a different buffer.
232   auto testSwap = [](bool resetAFirst) {
233     auto bufA = IOBuf::createCombined(256);
234     EXPECT_FALSE(bufA->isShared());
235     auto bufB = bufA->clone();
236     EXPECT_TRUE(bufA->isShared());
237     EXPECT_TRUE(bufB->isShared());
238     bufA->unshare();
239     EXPECT_FALSE(bufA->isShared());
240     EXPECT_FALSE(bufB->isShared());
241
242     if (resetAFirst) {
243       bufA.reset();
244       bufB.reset();
245     } else {
246       bufB.reset();
247       bufA.reset();
248     }
249   };
250   testSwap(true);
251   testSwap(false);
252 }
253
254 void fillBuf(uint8_t* buf, uint32_t length, boost::mt19937& gen) {
255   for (uint32_t n = 0; n < length; ++n) {
256     buf[n] = static_cast<uint8_t>(gen() & 0xff);
257   }
258 }
259
260 void fillBuf(IOBuf* buf, boost::mt19937& gen) {
261   buf->unshare();
262   fillBuf(buf->writableData(), buf->length(), gen);
263 }
264
265 void checkBuf(const uint8_t* buf, uint32_t length, boost::mt19937& gen) {
266   // Rather than using EXPECT_EQ() to check each character,
267   // count the number of differences and the first character that differs.
268   // This way on error we'll report just that information, rather than tons of
269   // failed checks for each byte in the buffer.
270   uint32_t numDifferences = 0;
271   uint32_t firstDiffIndex = 0;
272   uint8_t firstDiffExpected = 0;
273   for (uint32_t n = 0; n < length; ++n) {
274     uint8_t expected = static_cast<uint8_t>(gen() & 0xff);
275     if (buf[n] == expected) {
276       continue;
277     }
278
279     if (numDifferences == 0) {
280       firstDiffIndex = n;
281       firstDiffExpected = expected;
282     }
283     ++numDifferences;
284   }
285
286   EXPECT_EQ(0, numDifferences);
287   if (numDifferences > 0) {
288     // Cast to int so it will be printed numerically
289     // rather than as a char if the check fails
290     EXPECT_EQ(static_cast<int>(buf[firstDiffIndex]),
291               static_cast<int>(firstDiffExpected));
292   }
293 }
294
295 void checkBuf(IOBuf* buf, boost::mt19937& gen) {
296   checkBuf(buf->data(), buf->length(), gen);
297 }
298
299 void checkBuf(ByteRange buf, boost::mt19937& gen) {
300   checkBuf(buf.data(), buf.size(), gen);
301 }
302
303 void checkChain(IOBuf* buf, boost::mt19937& gen) {
304   IOBuf *current = buf;
305   do {
306     checkBuf(current->data(), current->length(), gen);
307     current = current->next();
308   } while (current != buf);
309 }
310
311 TEST(IOBuf, Chaining) {
312   uint32_t fillSeed = 0x12345678;
313   boost::mt19937 gen(fillSeed);
314
315   // An IOBuf with external storage
316   uint32_t headroom = 123;
317   unique_ptr<IOBuf> iob1(IOBuf::create(2048));
318   iob1->advance(headroom);
319   iob1->append(1500);
320   fillBuf(iob1.get(), gen);
321
322   // An IOBuf with internal storage
323   unique_ptr<IOBuf> iob2(IOBuf::create(20));
324   iob2->append(20);
325   fillBuf(iob2.get(), gen);
326
327   // An IOBuf around a buffer it doesn't own
328   uint8_t localbuf[1234];
329   fillBuf(localbuf, 1234, gen);
330   unique_ptr<IOBuf> iob3(IOBuf::wrapBuffer(localbuf, sizeof(localbuf)));
331
332   // An IOBuf taking ownership of a user-supplied buffer
333   uint32_t heapBufSize = 900;
334   uint8_t* heapBuf = static_cast<uint8_t*>(malloc(heapBufSize));
335   fillBuf(heapBuf, heapBufSize, gen);
336   unique_ptr<IOBuf> iob4(IOBuf::takeOwnership(heapBuf, heapBufSize));
337
338   // An IOBuf taking ownership of a user-supplied buffer with
339   // a custom free function
340   uint32_t arrayBufSize = 321;
341   uint8_t* arrayBuf = new uint8_t[arrayBufSize];
342   fillBuf(arrayBuf, arrayBufSize, gen);
343   uint32_t arrayBufFreeCount = 0;
344   unique_ptr<IOBuf> iob5(IOBuf::takeOwnership(arrayBuf, arrayBufSize,
345                                               deleteArrayBuffer,
346                                               &arrayBufFreeCount));
347
348   EXPECT_FALSE(iob1->isChained());
349   EXPECT_FALSE(iob2->isChained());
350   EXPECT_FALSE(iob3->isChained());
351   EXPECT_FALSE(iob4->isChained());
352   EXPECT_FALSE(iob5->isChained());
353
354   EXPECT_FALSE(iob1->isSharedOne());
355   EXPECT_FALSE(iob2->isSharedOne());
356   EXPECT_TRUE(iob3->isSharedOne()); // since we own the buffer
357   EXPECT_FALSE(iob4->isSharedOne());
358   EXPECT_FALSE(iob5->isSharedOne());
359
360   // Chain the buffers all together
361   // Since we are going to relinquish ownership of iob2-5 to the chain,
362   // store raw pointers to them so we can reference them later.
363   IOBuf* iob2ptr = iob2.get();
364   IOBuf* iob3ptr = iob3.get();
365   IOBuf* iob4ptr = iob4.get();
366   IOBuf* iob5ptr = iob5.get();
367
368   iob1->prependChain(std::move(iob2));
369   iob1->prependChain(std::move(iob4));
370   iob2ptr->appendChain(std::move(iob3));
371   iob1->prependChain(std::move(iob5));
372
373   EXPECT_EQ(iob2ptr, iob1->next());
374   EXPECT_EQ(iob3ptr, iob2ptr->next());
375   EXPECT_EQ(iob4ptr, iob3ptr->next());
376   EXPECT_EQ(iob5ptr, iob4ptr->next());
377   EXPECT_EQ(iob1.get(), iob5ptr->next());
378
379   EXPECT_EQ(iob5ptr, iob1->prev());
380   EXPECT_EQ(iob1.get(), iob2ptr->prev());
381   EXPECT_EQ(iob2ptr, iob3ptr->prev());
382   EXPECT_EQ(iob3ptr, iob4ptr->prev());
383   EXPECT_EQ(iob4ptr, iob5ptr->prev());
384
385   EXPECT_TRUE(iob1->isChained());
386   EXPECT_TRUE(iob2ptr->isChained());
387   EXPECT_TRUE(iob3ptr->isChained());
388   EXPECT_TRUE(iob4ptr->isChained());
389   EXPECT_TRUE(iob5ptr->isChained());
390
391   uint64_t fullLength = (iob1->length() + iob2ptr->length() +
392                          iob3ptr->length() + iob4ptr->length() +
393                         iob5ptr->length());
394   EXPECT_EQ(5, iob1->countChainElements());
395   EXPECT_EQ(fullLength, iob1->computeChainDataLength());
396
397   // Since iob3 is shared, the entire buffer should report itself as shared
398   EXPECT_TRUE(iob1->isShared());
399   // Unshare just iob3
400   iob3ptr->unshareOne();
401   EXPECT_FALSE(iob3ptr->isSharedOne());
402   // Now everything in the chain should be unshared.
403   // Check on all members of the chain just for good measure
404   EXPECT_FALSE(iob1->isShared());
405   EXPECT_FALSE(iob2ptr->isShared());
406   EXPECT_FALSE(iob3ptr->isShared());
407   EXPECT_FALSE(iob4ptr->isShared());
408   EXPECT_FALSE(iob5ptr->isShared());
409
410   // Check iteration
411   gen.seed(fillSeed);
412   size_t count = 0;
413   for (auto buf : *iob1) {
414     checkBuf(buf, gen);
415     ++count;
416   }
417   EXPECT_EQ(5, count);
418
419   // Clone one of the IOBufs in the chain
420   unique_ptr<IOBuf> iob4clone = iob4ptr->cloneOne();
421   gen.seed(fillSeed);
422   checkBuf(iob1.get(), gen);
423   checkBuf(iob2ptr, gen);
424   checkBuf(iob3ptr, gen);
425   checkBuf(iob4clone.get(), gen);
426   checkBuf(iob5ptr, gen);
427
428   EXPECT_TRUE(iob1->isShared());
429   EXPECT_TRUE(iob2ptr->isShared());
430   EXPECT_TRUE(iob3ptr->isShared());
431   EXPECT_TRUE(iob4ptr->isShared());
432   EXPECT_TRUE(iob5ptr->isShared());
433
434   EXPECT_FALSE(iob1->isSharedOne());
435   EXPECT_FALSE(iob2ptr->isSharedOne());
436   EXPECT_FALSE(iob3ptr->isSharedOne());
437   EXPECT_TRUE(iob4ptr->isSharedOne());
438   EXPECT_FALSE(iob5ptr->isSharedOne());
439
440   // Unshare that clone
441   EXPECT_TRUE(iob4clone->isSharedOne());
442   iob4clone->unshare();
443   EXPECT_FALSE(iob4clone->isSharedOne());
444   EXPECT_FALSE(iob4ptr->isSharedOne());
445   EXPECT_FALSE(iob1->isShared());
446   iob4clone.reset();
447
448
449   // Create a clone of a different IOBuf
450   EXPECT_FALSE(iob1->isShared());
451   EXPECT_FALSE(iob3ptr->isSharedOne());
452
453   unique_ptr<IOBuf> iob3clone = iob3ptr->cloneOne();
454   gen.seed(fillSeed);
455   checkBuf(iob1.get(), gen);
456   checkBuf(iob2ptr, gen);
457   checkBuf(iob3clone.get(), gen);
458   checkBuf(iob4ptr, gen);
459   checkBuf(iob5ptr, gen);
460
461   EXPECT_TRUE(iob1->isShared());
462   EXPECT_TRUE(iob3ptr->isSharedOne());
463   EXPECT_FALSE(iob1->isSharedOne());
464
465   // Delete the clone and make sure the original is unshared
466   iob3clone.reset();
467   EXPECT_FALSE(iob1->isShared());
468   EXPECT_FALSE(iob3ptr->isSharedOne());
469
470
471   // Clone the entire chain
472   unique_ptr<IOBuf> chainClone = iob1->clone();
473   // Verify that the data is correct.
474   EXPECT_EQ(fullLength, chainClone->computeChainDataLength());
475   gen.seed(fillSeed);
476   checkChain(chainClone.get(), gen);
477
478   // Check that the buffers report sharing correctly
479   EXPECT_TRUE(chainClone->isShared());
480   EXPECT_TRUE(iob1->isShared());
481
482   EXPECT_TRUE(iob1->isSharedOne());
483   EXPECT_TRUE(iob2ptr->isSharedOne());
484   EXPECT_TRUE(iob3ptr->isSharedOne());
485   EXPECT_TRUE(iob4ptr->isSharedOne());
486   EXPECT_TRUE(iob5ptr->isSharedOne());
487
488   // Unshare the cloned chain
489   chainClone->unshare();
490   EXPECT_FALSE(chainClone->isShared());
491   EXPECT_FALSE(iob1->isShared());
492
493   // Make sure the unshared result still has the same data
494   EXPECT_EQ(fullLength, chainClone->computeChainDataLength());
495   gen.seed(fillSeed);
496   checkChain(chainClone.get(), gen);
497
498   // Destroy this chain
499   chainClone.reset();
500
501
502   // Clone a new chain
503   EXPECT_FALSE(iob1->isShared());
504   chainClone = iob1->clone();
505   EXPECT_TRUE(iob1->isShared());
506   EXPECT_TRUE(chainClone->isShared());
507
508   // Delete the original chain
509   iob1.reset();
510   EXPECT_FALSE(chainClone->isShared());
511
512   // Coalesce the chain
513   //
514   // Coalescing this chain will create a new buffer and release the last
515   // refcount on the original buffers we created.  Also make sure
516   // that arrayBufFreeCount increases to one to indicate that arrayBuf was
517   // freed.
518   EXPECT_EQ(5, chainClone->countChainElements());
519   EXPECT_EQ(0, arrayBufFreeCount);
520
521   // Buffer lengths: 1500 20 1234 900 321
522   // Attempting to gather more data than available should fail
523   EXPECT_THROW(chainClone->gather(4000), std::overflow_error);
524   // Coalesce the first 3 buffers
525   chainClone->gather(1521);
526   EXPECT_EQ(3, chainClone->countChainElements());
527   EXPECT_EQ(0, arrayBufFreeCount);
528
529   // Make sure the data is still the same after coalescing
530   EXPECT_EQ(fullLength, chainClone->computeChainDataLength());
531   gen.seed(fillSeed);
532   checkChain(chainClone.get(), gen);
533
534   // Coalesce the entire chain
535   chainClone->coalesce();
536   EXPECT_EQ(1, chainClone->countChainElements());
537   EXPECT_EQ(1, arrayBufFreeCount);
538
539   // Make sure the data is still the same after coalescing
540   EXPECT_EQ(fullLength, chainClone->computeChainDataLength());
541   gen.seed(fillSeed);
542   checkChain(chainClone.get(), gen);
543
544   // Make a new chain to test the unlink and pop operations
545   iob1 = IOBuf::create(1);
546   iob1->append(1);
547   IOBuf *iob1ptr = iob1.get();
548   iob2 = IOBuf::create(3);
549   iob2->append(3);
550   iob2ptr = iob2.get();
551   iob3 = IOBuf::create(5);
552   iob3->append(5);
553   iob3ptr = iob3.get();
554   iob4 = IOBuf::create(7);
555   iob4->append(7);
556   iob4ptr = iob4.get();
557   iob1->appendChain(std::move(iob2));
558   iob1->prev()->appendChain(std::move(iob3));
559   iob1->prev()->appendChain(std::move(iob4));
560   EXPECT_EQ(4, iob1->countChainElements());
561   EXPECT_EQ(16, iob1->computeChainDataLength());
562
563   // Unlink from the middle of the chain
564   iob3 = iob3ptr->unlink();
565   EXPECT_TRUE(iob3.get() == iob3ptr);
566   EXPECT_EQ(3, iob1->countChainElements());
567   EXPECT_EQ(11, iob1->computeChainDataLength());
568
569   // Unlink from the end of the chain
570   iob4 = iob1->prev()->unlink();
571   EXPECT_TRUE(iob4.get() == iob4ptr);
572   EXPECT_EQ(2, iob1->countChainElements());
573   EXPECT_TRUE(iob1->next() == iob2ptr);
574   EXPECT_EQ(4, iob1->computeChainDataLength());
575
576   // Pop from the front of the chain
577   iob2 = iob1->pop();
578   EXPECT_TRUE(iob1.get() == iob1ptr);
579   EXPECT_EQ(1, iob1->countChainElements());
580   EXPECT_EQ(1, iob1->computeChainDataLength());
581   EXPECT_TRUE(iob2.get() == iob2ptr);
582   EXPECT_EQ(1, iob2->countChainElements());
583   EXPECT_EQ(3, iob2->computeChainDataLength());
584 }
585
586 void testFreeFn(void* buffer, void* ptr) {
587   uint32_t* freeCount = static_cast<uint32_t*>(ptr);;
588   delete[] static_cast<uint8_t*>(buffer);
589   if (freeCount) {
590     ++(*freeCount);
591   }
592 };
593
594 TEST(IOBuf, Reserve) {
595   uint32_t fillSeed = 0x23456789;
596   boost::mt19937 gen(fillSeed);
597
598   // Reserve does nothing if empty and doesn't have to grow the buffer
599   {
600     gen.seed(fillSeed);
601     unique_ptr<IOBuf> iob(IOBuf::create(2000));
602     EXPECT_EQ(0, iob->headroom());
603     const void* p1 = iob->buffer();
604     iob->reserve(5, 15);
605     EXPECT_LE(5, iob->headroom());
606     EXPECT_EQ(p1, iob->buffer());
607   }
608
609   // Reserve doesn't reallocate if we have enough total room
610   {
611     gen.seed(fillSeed);
612     unique_ptr<IOBuf> iob(IOBuf::create(2000));
613     iob->append(100);
614     fillBuf(iob.get(), gen);
615     EXPECT_EQ(0, iob->headroom());
616     EXPECT_EQ(100, iob->length());
617     const void* p1 = iob->buffer();
618     const uint8_t* d1 = iob->data();
619     iob->reserve(100, 1800);
620     EXPECT_LE(100, iob->headroom());
621     EXPECT_EQ(p1, iob->buffer());
622     EXPECT_EQ(d1 + 100, iob->data());
623     gen.seed(fillSeed);
624     checkBuf(iob.get(), gen);
625   }
626
627   // Reserve reallocates if we don't have enough total room.
628   // NOTE that, with jemalloc, we know that this won't reallocate in place
629   // as the size is less than jemallocMinInPlaceExpanadable
630   {
631     gen.seed(fillSeed);
632     unique_ptr<IOBuf> iob(IOBuf::create(2000));
633     iob->append(100);
634     fillBuf(iob.get(), gen);
635     EXPECT_EQ(0, iob->headroom());
636     EXPECT_EQ(100, iob->length());
637     const void* p1 = iob->buffer();
638     iob->reserve(100, 2512);  // allocation sizes are multiples of 256
639     EXPECT_LE(100, iob->headroom());
640     if (folly::usingJEMalloc()) {
641       EXPECT_NE(p1, iob->buffer());
642     }
643     gen.seed(fillSeed);
644     checkBuf(iob.get(), gen);
645   }
646
647   // Test reserve from internal buffer, this used to segfault
648   {
649     unique_ptr<IOBuf> iob(IOBuf::create(0));
650     iob->reserve(0, 2000);
651     EXPECT_EQ(0, iob->headroom());
652     EXPECT_LE(2000, iob->tailroom());
653   }
654
655   // Test reserving from a user-allocated buffer.
656   {
657     uint8_t* buf = static_cast<uint8_t*>(malloc(100));
658     auto iob = IOBuf::takeOwnership(buf, 100);
659     iob->reserve(0, 2000);
660     EXPECT_EQ(0, iob->headroom());
661     EXPECT_LE(2000, iob->tailroom());
662   }
663
664   // Test reserving from a user-allocated with a custom free function.
665   {
666     uint32_t freeCount{0};
667     uint8_t* buf = new uint8_t[100];
668     auto iob = IOBuf::takeOwnership(buf, 100, testFreeFn, &freeCount);
669     iob->reserve(0, 2000);
670     EXPECT_EQ(0, iob->headroom());
671     EXPECT_LE(2000, iob->tailroom());
672     EXPECT_EQ(1, freeCount);
673   }
674 }
675
676 TEST(IOBuf, copyBuffer) {
677   std::string s("hello");
678   auto buf = IOBuf::copyBuffer(s.data(), s.size(), 1, 2);
679   EXPECT_EQ(1, buf->headroom());
680   EXPECT_EQ(s, std::string(reinterpret_cast<const char*>(buf->data()),
681                            buf->length()));
682   EXPECT_LE(2, buf->tailroom());
683
684   buf = IOBuf::copyBuffer(s, 5, 7);
685   EXPECT_EQ(5, buf->headroom());
686   EXPECT_EQ(s, std::string(reinterpret_cast<const char*>(buf->data()),
687                            buf->length()));
688   EXPECT_LE(7, buf->tailroom());
689
690   std::string empty;
691   buf = IOBuf::copyBuffer(empty, 3, 6);
692   EXPECT_EQ(3, buf->headroom());
693   EXPECT_EQ(0, buf->length());
694   EXPECT_LE(6, buf->tailroom());
695
696   // A stack-allocated version
697   IOBuf stackBuf(IOBuf::COPY_BUFFER, s, 1, 2);
698   EXPECT_EQ(1, stackBuf.headroom());
699   EXPECT_EQ(s, std::string(reinterpret_cast<const char*>(stackBuf.data()),
700                            stackBuf.length()));
701   EXPECT_LE(2, stackBuf.tailroom());
702 }
703
704 TEST(IOBuf, maybeCopyBuffer) {
705   std::string s("this is a test");
706   auto buf = IOBuf::maybeCopyBuffer(s, 1, 2);
707   EXPECT_EQ(1, buf->headroom());
708   EXPECT_EQ(s, std::string(reinterpret_cast<const char*>(buf->data()),
709                            buf->length()));
710   EXPECT_LE(2, buf->tailroom());
711
712   std::string empty;
713   buf = IOBuf::maybeCopyBuffer("", 5, 7);
714   EXPECT_EQ(nullptr, buf.get());
715
716   buf = IOBuf::maybeCopyBuffer("");
717   EXPECT_EQ(nullptr, buf.get());
718 }
719
720 namespace {
721
722 int customDeleterCount = 0;
723 int destructorCount = 0;
724 struct OwnershipTestClass {
725   explicit OwnershipTestClass(int v = 0) : val(v) { }
726   ~OwnershipTestClass() {
727     ++destructorCount;
728   }
729   int val;
730 };
731
732 typedef std::function<void(OwnershipTestClass*)> CustomDeleter;
733
734 void customDelete(OwnershipTestClass* p) {
735   ++customDeleterCount;
736   delete p;
737 }
738
739 void customDeleteArray(OwnershipTestClass* p) {
740   ++customDeleterCount;
741   delete[] p;
742 }
743
744 }  // namespace
745
746 TEST(IOBuf, takeOwnershipUniquePtr) {
747   destructorCount = 0;
748   {
749     std::unique_ptr<OwnershipTestClass> p(new OwnershipTestClass());
750   }
751   EXPECT_EQ(1, destructorCount);
752
753   destructorCount = 0;
754   {
755     std::unique_ptr<OwnershipTestClass[]> p(new OwnershipTestClass[2]);
756   }
757   EXPECT_EQ(2, destructorCount);
758
759   destructorCount = 0;
760   {
761     std::unique_ptr<OwnershipTestClass> p(new OwnershipTestClass());
762     std::unique_ptr<IOBuf> buf(IOBuf::takeOwnership(std::move(p)));
763     EXPECT_EQ(sizeof(OwnershipTestClass), buf->length());
764     EXPECT_EQ(0, destructorCount);
765   }
766   EXPECT_EQ(1, destructorCount);
767
768   destructorCount = 0;
769   {
770     std::unique_ptr<OwnershipTestClass[]> p(new OwnershipTestClass[2]);
771     std::unique_ptr<IOBuf> buf(IOBuf::takeOwnership(std::move(p), 2));
772     EXPECT_EQ(2 * sizeof(OwnershipTestClass), buf->length());
773     EXPECT_EQ(0, destructorCount);
774   }
775   EXPECT_EQ(2, destructorCount);
776
777   customDeleterCount = 0;
778   destructorCount = 0;
779   {
780     std::unique_ptr<OwnershipTestClass, CustomDeleter>
781       p(new OwnershipTestClass(), customDelete);
782     std::unique_ptr<IOBuf> buf(IOBuf::takeOwnership(std::move(p)));
783     EXPECT_EQ(sizeof(OwnershipTestClass), buf->length());
784     EXPECT_EQ(0, destructorCount);
785   }
786   EXPECT_EQ(1, destructorCount);
787   EXPECT_EQ(1, customDeleterCount);
788
789   customDeleterCount = 0;
790   destructorCount = 0;
791   {
792     std::unique_ptr<OwnershipTestClass[], CustomDeleter>
793       p(new OwnershipTestClass[2], CustomDeleter(customDeleteArray));
794     std::unique_ptr<IOBuf> buf(IOBuf::takeOwnership(std::move(p), 2));
795     EXPECT_EQ(2 * sizeof(OwnershipTestClass), buf->length());
796     EXPECT_EQ(0, destructorCount);
797   }
798   EXPECT_EQ(2, destructorCount);
799   EXPECT_EQ(1, customDeleterCount);
800 }
801
802 TEST(IOBuf, Alignment) {
803   size_t alignment = alignof(std::max_align_t);
804
805   std::vector<size_t> sizes {0, 1, 64, 256, 1024, 1 << 10};
806   for (size_t size : sizes) {
807     auto buf = IOBuf::create(size);
808     uintptr_t p = reinterpret_cast<uintptr_t>(buf->data());
809     EXPECT_EQ(0, p & (alignment - 1)) << "size=" << size;
810   }
811 }
812
813 TEST(TypedIOBuf, Simple) {
814   auto buf = IOBuf::create(0);
815   TypedIOBuf<uint64_t> typed(buf.get());
816   const uint64_t n = 10000;
817   typed.reserve(0, n);
818   EXPECT_LE(n, typed.capacity());
819   for (uint64_t i = 0; i < n; i++) {
820     *typed.writableTail() = i;
821     typed.append(1);
822   }
823   EXPECT_EQ(n, typed.length());
824   for (uint64_t i = 0; i < n; i++) {
825     EXPECT_EQ(i, typed.data()[i]);
826   }
827 }
828 enum BufType {
829   CREATE,
830   TAKE_OWNERSHIP_MALLOC,
831   TAKE_OWNERSHIP_CUSTOM,
832   USER_OWNED,
833 };
834
835 // chain element size, number of elements in chain, shared
836 class MoveToFbStringTest
837   : public ::testing::TestWithParam<std::tr1::tuple<int, int, bool, BufType>> {
838  protected:
839   void SetUp() override {
840     elementSize_ = std::tr1::get<0>(GetParam());
841     elementCount_ = std::tr1::get<1>(GetParam());
842     shared_ = std::tr1::get<2>(GetParam());
843     type_ = std::tr1::get<3>(GetParam());
844
845     buf_ = makeBuf();
846     for (int i = 0; i < elementCount_ - 1; ++i) {
847       buf_->prependChain(makeBuf());
848     }
849     EXPECT_EQ(elementCount_, buf_->countChainElements());
850     EXPECT_EQ(elementCount_ * elementSize_, buf_->computeChainDataLength());
851     if (shared_) {
852       buf2_ = buf_->clone();
853       EXPECT_EQ(elementCount_, buf2_->countChainElements());
854       EXPECT_EQ(elementCount_ * elementSize_, buf2_->computeChainDataLength());
855     }
856   }
857
858   std::unique_ptr<IOBuf> makeBuf() {
859     unique_ptr<IOBuf> buf;
860     switch (type_) {
861       case CREATE:
862         buf = IOBuf::create(elementSize_);
863         buf->append(elementSize_);
864         break;
865       case TAKE_OWNERSHIP_MALLOC: {
866         void* data = malloc(elementSize_);
867         if (!data) {
868           throw std::bad_alloc();
869         }
870         buf = IOBuf::takeOwnership(data, elementSize_);
871         break;
872       }
873       case TAKE_OWNERSHIP_CUSTOM: {
874         uint8_t* data = new uint8_t[elementSize_];
875         buf = IOBuf::takeOwnership(data, elementSize_, testFreeFn);
876         break;
877       }
878       case USER_OWNED: {
879         unique_ptr<uint8_t[]> data(new uint8_t[elementSize_]);
880         buf = IOBuf::wrapBuffer(data.get(), elementSize_);
881         ownedBuffers_.emplace_back(std::move(data));
882         break;
883       }
884       default:
885         throw std::invalid_argument("unexpected buffer type parameter");
886         break;
887     }
888     memset(buf->writableData(), 'x', elementSize_);
889     return buf;
890   }
891
892   void check(std::unique_ptr<IOBuf>& buf) {
893     fbstring str = buf->moveToFbString();
894     EXPECT_EQ(elementCount_ * elementSize_, str.size());
895     EXPECT_EQ(elementCount_ * elementSize_, strspn(str.c_str(), "x"));
896     EXPECT_EQ(0, buf->length());
897     EXPECT_EQ(1, buf->countChainElements());
898     EXPECT_EQ(0, buf->computeChainDataLength());
899     EXPECT_FALSE(buf->isChained());
900   }
901
902   int elementSize_;
903   int elementCount_;
904   bool shared_;
905   BufType type_;
906   std::unique_ptr<IOBuf> buf_;
907   std::unique_ptr<IOBuf> buf2_;
908   std::vector<std::unique_ptr<uint8_t[]>> ownedBuffers_;
909 };
910
911 TEST_P(MoveToFbStringTest, Simple) {
912   check(buf_);
913   if (shared_) {
914     check(buf2_);
915   }
916 }
917
918 INSTANTIATE_TEST_CASE_P(
919     MoveToFbString,
920     MoveToFbStringTest,
921     ::testing::Combine(
922         ::testing::Values(0, 1, 24, 256, 1 << 10, 1 << 20),  // element size
923         ::testing::Values(1, 2, 10),                         // element count
924         ::testing::Bool(),                                   // shared
925         ::testing::Values(CREATE, TAKE_OWNERSHIP_MALLOC,
926                           TAKE_OWNERSHIP_CUSTOM, USER_OWNED)));
927
928 TEST(IOBuf, getIov) {
929   uint32_t fillSeed = 0xdeadbeef;
930   boost::mt19937 gen(fillSeed);
931
932   size_t len = 4096;
933   size_t count = 32;
934   auto buf = IOBuf::create(len + 1);
935   buf->append(rand() % len + 1);
936   fillBuf(buf.get(), gen);
937
938   for (size_t i = 0; i < count - 1; i++) {
939     auto buf2 = IOBuf::create(len + 1);
940     buf2->append(rand() % len + 1);
941     fillBuf(buf2.get(), gen);
942     buf->prependChain(std::move(buf2));
943   }
944   EXPECT_EQ(count, buf->countChainElements());
945
946   auto iov = buf->getIov();
947   EXPECT_EQ(count, iov.size());
948
949   IOBuf const* p = buf.get();
950   for (size_t i = 0; i < count; i++, p = p->next()) {
951     EXPECT_EQ(p->data(), iov[i].iov_base);
952     EXPECT_EQ(p->length(), iov[i].iov_len);
953   }
954
955   // an empty buf should be skipped in the iov.
956   buf->next()->clear();
957   iov = buf->getIov();
958   EXPECT_EQ(count - 1, iov.size());
959   EXPECT_EQ(buf->next()->next()->data(), iov[1].iov_base);
960
961   // same for the first one being empty
962   buf->clear();
963   iov = buf->getIov();
964   EXPECT_EQ(count - 2, iov.size());
965   EXPECT_EQ(buf->next()->next()->data(), iov[0].iov_base);
966
967   // and the last one
968   buf->prev()->clear();
969   iov = buf->getIov();
970   EXPECT_EQ(count - 3, iov.size());
971
972   // test appending to an existing iovec array
973   iov.clear();
974   const char localBuf[] = "hello";
975   iov.push_back({(void*)localBuf, sizeof(localBuf)});
976   iov.push_back({(void*)localBuf, sizeof(localBuf)});
977   buf->appendToIov(&iov);
978   EXPECT_EQ(count - 1, iov.size());
979   EXPECT_EQ(localBuf, iov[0].iov_base);
980   EXPECT_EQ(localBuf, iov[1].iov_base);
981   // The first two IOBufs were cleared, so the next iov entry
982   // should be the third IOBuf in the chain.
983   EXPECT_EQ(buf->next()->next()->data(), iov[2].iov_base);
984 }
985
986 TEST(IOBuf, move) {
987   // Default allocate an IOBuf on the stack
988   IOBuf outerBuf;
989   char data[] = "foobar";
990   uint32_t length = sizeof(data);
991   uint32_t actualCapacity{0};
992   const void* ptr{nullptr};
993
994   {
995     // Create a small IOBuf on the stack.
996     // Note that IOBufs created on the stack always use an external buffer.
997     IOBuf b1(IOBuf::CREATE, 10);
998     actualCapacity = b1.capacity();
999     EXPECT_GE(actualCapacity, 10);
1000     EXPECT_EQ(0, b1.length());
1001     EXPECT_FALSE(b1.isShared());
1002     ptr = b1.data();
1003     ASSERT_TRUE(ptr != nullptr);
1004     memcpy(b1.writableTail(), data, length);
1005     b1.append(length);
1006     EXPECT_EQ(length, b1.length());
1007
1008     // Use the move constructor
1009     IOBuf b2(std::move(b1));
1010     EXPECT_EQ(ptr, b2.data());
1011     EXPECT_EQ(length, b2.length());
1012     EXPECT_EQ(actualCapacity, b2.capacity());
1013     EXPECT_FALSE(b2.isShared());
1014
1015     // Use the move assignment operator
1016     outerBuf = std::move(b2);
1017     // Close scope, destroying b1 and b2
1018     // (which are both be invalid now anyway after moving out of them)
1019   }
1020
1021   EXPECT_EQ(ptr, outerBuf.data());
1022   EXPECT_EQ(length, outerBuf.length());
1023   EXPECT_EQ(actualCapacity, outerBuf.capacity());
1024   EXPECT_FALSE(outerBuf.isShared());
1025 }
1026
1027 namespace {
1028 std::unique_ptr<IOBuf> fromStr(StringPiece sp) {
1029   return IOBuf::copyBuffer(ByteRange(sp));
1030 }
1031 }  // namespace
1032
1033 TEST(IOBuf, HashAndEqual) {
1034   folly::IOBufEqual eq;
1035   folly::IOBufHash hash;
1036
1037   EXPECT_TRUE(eq(nullptr, nullptr));
1038   EXPECT_EQ(0, hash(nullptr));
1039
1040   auto empty = IOBuf::create(0);
1041
1042   EXPECT_TRUE(eq(*empty, *empty));
1043   EXPECT_TRUE(eq(empty, empty));
1044
1045   EXPECT_FALSE(eq(nullptr, empty));
1046   EXPECT_FALSE(eq(empty, nullptr));
1047
1048   EXPECT_EQ(hash(*empty), hash(empty));
1049   EXPECT_NE(0, hash(empty));
1050
1051   auto a = fromStr("hello");
1052
1053   EXPECT_TRUE(eq(*a, *a));
1054   EXPECT_TRUE(eq(a, a));
1055
1056   EXPECT_FALSE(eq(nullptr, a));
1057   EXPECT_FALSE(eq(a, nullptr));
1058
1059   EXPECT_EQ(hash(*a), hash(a));
1060   EXPECT_NE(0, hash(a));
1061
1062   auto b = fromStr("hello");
1063
1064   EXPECT_TRUE(eq(*a, *b));
1065   EXPECT_TRUE(eq(a, b));
1066
1067   EXPECT_EQ(hash(a), hash(b));
1068
1069   auto c = fromStr("hellow");
1070
1071   EXPECT_FALSE(eq(a, c));
1072   EXPECT_NE(hash(a), hash(c));
1073
1074   auto d = fromStr("world");
1075
1076   EXPECT_FALSE(eq(a, d));
1077   EXPECT_NE(hash(a), hash(d));
1078
1079   auto e = fromStr("helloworld");
1080   auto f = fromStr("hello");
1081   f->prependChain(fromStr("wo"));
1082   f->prependChain(fromStr("rld"));
1083
1084   EXPECT_TRUE(eq(e, f));
1085   EXPECT_EQ(hash(e), hash(f));
1086 }
1087
1088 // reserveSlow() had a bug when reallocating the buffer in place. It would
1089 // preserve old headroom if it's not too much (heuristically) but wouldn't
1090 // adjust the requested amount of memory to account for that; the end result
1091 // would be that reserve() would return with less tailroom than requested.
1092 TEST(IOBuf, ReserveWithHeadroom) {
1093   // This is assuming jemalloc, where we know that 4096 and 8192 bytes are
1094   // valid (and consecutive) allocation sizes. We're hoping that our
1095   // 4096-byte buffer can be expanded in place to 8192 (in practice, this
1096   // usually happens).
1097   const char data[] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
1098   constexpr size_t reservedSize = 24;  // sizeof(SharedInfo)
1099   // chosen carefully so that the buffer is exactly 4096 bytes
1100   IOBuf buf(IOBuf::CREATE, 4096 - reservedSize);
1101   buf.advance(10);
1102   memcpy(buf.writableData(), data, sizeof(data));
1103   buf.append(sizeof(data));
1104   EXPECT_EQ(sizeof(data), buf.length());
1105
1106   // Grow the buffer (hopefully in place); this would incorrectly reserve
1107   // the 10 bytes of headroom, giving us 10 bytes less than requested.
1108   size_t tailroom = 8192 - reservedSize - sizeof(data);
1109   buf.reserve(0, tailroom);
1110   EXPECT_LE(tailroom, buf.tailroom());
1111   EXPECT_EQ(sizeof(data), buf.length());
1112   EXPECT_EQ(0, memcmp(data, buf.data(), sizeof(data)));
1113 }
1114
1115 TEST(IOBuf, CopyConstructorAndAssignmentOperator) {
1116   auto buf = IOBuf::create(4096);
1117   append(buf, "hello world");
1118   auto buf2 = IOBuf::create(4096);
1119   append(buf2, " goodbye");
1120   buf->prependChain(std::move(buf2));
1121   EXPECT_FALSE(buf->isShared());
1122
1123   {
1124     auto copy = *buf;
1125     EXPECT_TRUE(buf->isShared());
1126     EXPECT_TRUE(copy.isShared());
1127     EXPECT_EQ((void*)buf->data(), (void*)copy.data());
1128     EXPECT_NE(buf->next(), copy.next());  // actually different buffers
1129
1130     auto copy2 = *buf;
1131     copy2.coalesce();
1132     EXPECT_TRUE(buf->isShared());
1133     EXPECT_TRUE(copy.isShared());
1134     EXPECT_FALSE(copy2.isShared());
1135
1136     auto p = reinterpret_cast<const char*>(copy2.data());
1137     EXPECT_EQ("hello world goodbye", std::string(p, copy2.length()));
1138   }
1139
1140   EXPECT_FALSE(buf->isShared());
1141
1142   {
1143     folly::IOBuf newBuf(folly::IOBuf::CREATE, 4096);
1144     EXPECT_FALSE(newBuf.isShared());
1145
1146     auto newBufCopy = newBuf;
1147     EXPECT_TRUE(newBuf.isShared());
1148     EXPECT_TRUE(newBufCopy.isShared());
1149
1150     newBufCopy = *buf;
1151     EXPECT_TRUE(buf->isShared());
1152     EXPECT_FALSE(newBuf.isShared());
1153     EXPECT_TRUE(newBufCopy.isShared());
1154   }
1155
1156   EXPECT_FALSE(buf->isShared());
1157 }
1158
1159 TEST(IOBuf, CloneAsValue) {
1160   auto buf = IOBuf::create(4096);
1161   append(buf, "hello world");
1162   {
1163     auto buf2 = IOBuf::create(4096);
1164     append(buf2, " goodbye");
1165     buf->prependChain(std::move(buf2));
1166     EXPECT_FALSE(buf->isShared());
1167   }
1168
1169   {
1170     auto copy = buf->cloneOneAsValue();
1171     EXPECT_TRUE(buf->isShared());
1172     EXPECT_TRUE(copy.isShared());
1173     EXPECT_EQ((void*)buf->data(), (void*)copy.data());
1174     EXPECT_TRUE(buf->isChained());
1175     EXPECT_FALSE(copy.isChained());
1176
1177     auto copy2 = buf->cloneAsValue();
1178     EXPECT_TRUE(buf->isShared());
1179     EXPECT_TRUE(copy.isShared());
1180     EXPECT_TRUE(copy2.isShared());
1181     EXPECT_TRUE(buf->isChained());
1182     EXPECT_TRUE(copy2.isChained());
1183
1184     copy.unshareOne();
1185     EXPECT_TRUE(buf->isShared());
1186     EXPECT_FALSE(copy.isShared());
1187     EXPECT_NE((void*)buf->data(), (void*)copy.data());
1188     EXPECT_TRUE(copy2.isShared());
1189
1190     auto p = reinterpret_cast<const char*>(copy.data());
1191     EXPECT_EQ("hello world", std::string(p, copy.length()));
1192
1193     copy2.coalesce();
1194     EXPECT_FALSE(buf->isShared());
1195     EXPECT_FALSE(copy.isShared());
1196     EXPECT_FALSE(copy2.isShared());
1197     EXPECT_FALSE(copy2.isChained());
1198
1199     auto p2 = reinterpret_cast<const char*>(copy2.data());
1200     EXPECT_EQ("hello world goodbye", std::string(p2, copy2.length()));
1201   }
1202
1203   EXPECT_FALSE(buf->isShared());
1204 }
1205
1206 namespace {
1207 // Use with string literals only
1208 std::unique_ptr<IOBuf> wrap(const char* str) {
1209   return IOBuf::wrapBuffer(str, strlen(str));
1210 }
1211
1212 std::unique_ptr<IOBuf> copy(const char* str) {
1213   // At least 1KiB of tailroom, to ensure an external buffer
1214   return IOBuf::copyBuffer(str, strlen(str), 0, 1024);
1215 }
1216
1217 std::string toString(const folly::IOBuf& buf) {
1218   std::string result;
1219   result.reserve(buf.computeChainDataLength());
1220   for (auto& b : buf) {
1221     result.append(reinterpret_cast<const char*>(b.data()), b.size());
1222   }
1223   return result;
1224 }
1225
1226 char* writableStr(folly::IOBuf& buf) {
1227   return reinterpret_cast<char*>(buf.writableData());
1228 }
1229
1230 }  // namespace
1231
1232 TEST(IOBuf, ExternallyShared) {
1233   struct Item {
1234     Item(const char* src, size_t len) : size(len) {
1235       CHECK_LE(len, sizeof(buffer));
1236       memcpy(buffer, src, len);
1237     }
1238     uint32_t refcount{0};
1239     uint8_t size;
1240     char buffer[256];
1241   };
1242
1243   auto hello = "hello";
1244   struct Item it(hello, strlen(hello));
1245
1246   {
1247     auto freeFn = [](void* /* unused */, void* userData) {
1248       auto it = static_cast<struct Item*>(userData);
1249       it->refcount--;
1250     };
1251     it.refcount++;
1252     auto buf1 = IOBuf::takeOwnership(it.buffer, it.size, freeFn, &it);
1253     EXPECT_TRUE(buf1->isManagedOne());
1254     EXPECT_FALSE(buf1->isSharedOne());
1255
1256     buf1->markExternallyShared();
1257     EXPECT_TRUE(buf1->isSharedOne());
1258
1259     {
1260       auto buf2 = buf1->clone();
1261       EXPECT_TRUE(buf2->isManagedOne());
1262       EXPECT_TRUE(buf2->isSharedOne());
1263       EXPECT_EQ(buf1->data(), buf2->data());
1264       EXPECT_EQ(it.refcount, 1);
1265     }
1266     EXPECT_EQ(it.refcount, 1);
1267   }
1268   EXPECT_EQ(it.refcount, 0);
1269 }
1270
1271 TEST(IOBuf, Managed) {
1272   auto hello = "hello";
1273   auto buf1UP = wrap(hello);
1274   auto buf1 = buf1UP.get();
1275   EXPECT_FALSE(buf1->isManagedOne());
1276   auto buf2UP = copy("world");
1277   auto buf2 = buf2UP.get();
1278   EXPECT_TRUE(buf2->isManagedOne());
1279   auto buf3UP = wrap(hello);
1280   auto buf3 = buf3UP.get();
1281   auto buf4UP = buf2->clone();
1282   auto buf4 = buf4UP.get();
1283
1284   // buf1 and buf3 share the same memory (but are unmanaged)
1285   EXPECT_FALSE(buf1->isManagedOne());
1286   EXPECT_FALSE(buf3->isManagedOne());
1287   EXPECT_TRUE(buf1->isSharedOne());
1288   EXPECT_TRUE(buf3->isSharedOne());
1289   EXPECT_EQ(buf1->data(), buf3->data());
1290
1291   // buf2 and buf4 share the same memory (but are managed)
1292   EXPECT_TRUE(buf2->isManagedOne());
1293   EXPECT_TRUE(buf4->isManagedOne());
1294   EXPECT_TRUE(buf2->isSharedOne());
1295   EXPECT_TRUE(buf4->isSharedOne());
1296   EXPECT_EQ(buf2->data(), buf4->data());
1297
1298   buf1->prependChain(std::move(buf2UP));
1299   buf1->prependChain(std::move(buf3UP));
1300   buf1->prependChain(std::move(buf4UP));
1301
1302   EXPECT_EQ("helloworldhelloworld", toString(*buf1));
1303   EXPECT_FALSE(buf1->isManaged());
1304
1305   buf1->makeManaged();
1306   EXPECT_TRUE(buf1->isManaged());
1307
1308   // buf1 and buf3 are now unshared (because they were unmanaged)
1309   EXPECT_TRUE(buf1->isManagedOne());
1310   EXPECT_TRUE(buf3->isManagedOne());
1311   EXPECT_FALSE(buf1->isSharedOne());
1312   EXPECT_FALSE(buf3->isSharedOne());
1313   EXPECT_NE(buf1->data(), buf3->data());
1314
1315   // buf2 and buf4 are still shared
1316   EXPECT_TRUE(buf2->isManagedOne());
1317   EXPECT_TRUE(buf4->isManagedOne());
1318   EXPECT_TRUE(buf2->isSharedOne());
1319   EXPECT_TRUE(buf4->isSharedOne());
1320   EXPECT_EQ(buf2->data(), buf4->data());
1321
1322   // And verify that the truth is what we expect: modify a byte in buf1 and
1323   // buf2, see that the change from buf1 is *not* reflected in buf3, but the
1324   // change from buf2 is reflected in buf4.
1325   writableStr(*buf1)[0] = 'j';
1326   writableStr(*buf2)[0] = 'x';
1327   EXPECT_EQ("jelloxorldhelloxorld", toString(*buf1));
1328 }