Do not use small category in fbstring when in ASan mode
[folly.git] / folly / FBString.h
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 // @author: Andrei Alexandrescu (aalexandre)
18 // String type.
19
20 #ifndef FOLLY_BASE_FBSTRING_H_
21 #define FOLLY_BASE_FBSTRING_H_
22
23 #include <atomic>
24 #include <limits>
25 #include <type_traits>
26
27 // This file appears in two locations: inside fbcode and in the
28 // libstdc++ source code (when embedding fbstring as std::string).
29 // To aid in this schizophrenic use, _LIBSTDCXX_FBSTRING is defined in
30 // libstdc++'s c++config.h, to gate use inside fbcode v. libstdc++.
31 #ifdef _LIBSTDCXX_FBSTRING
32
33 #pragma GCC system_header
34
35 // When used as std::string replacement always disable assertions.
36 #ifndef NDEBUG
37 #define NDEBUG
38 #define FOLLY_DEFINED_NDEBUG_FOR_FBSTRING
39 #endif // NDEBUG
40
41 // Handle the cases where the fbcode version (folly/Malloc.h) is included
42 // either before or after this inclusion.
43 #ifdef FOLLY_MALLOC_H_
44 #undef FOLLY_MALLOC_H_
45 #include "basic_fbstring_malloc.h" // nolint
46 #else
47 #include "basic_fbstring_malloc.h" // nolint
48 #undef FOLLY_MALLOC_H_
49 #endif
50
51 #else // !_LIBSTDCXX_FBSTRING
52
53 #include <folly/Portability.h>
54
55 // libc++ doesn't provide this header, nor does msvc
56 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
57 #include <bits/c++config.h>
58 #endif
59
60 #include <string>
61 #include <cstring>
62 #include <cassert>
63 #include <algorithm>
64
65 #include <folly/Traits.h>
66 #include <folly/Malloc.h>
67 #include <folly/Hash.h>
68 #include <folly/ScopeGuard.h>
69
70 #if FOLLY_HAVE_DEPRECATED_ASSOC
71 #ifdef _GLIBCXX_SYMVER
72 #include <ext/hash_set>
73 #include <ext/hash_map>
74 #endif
75 #endif
76
77 #endif
78
79 // We defined these here rather than including Likely.h to avoid
80 // redefinition errors when fbstring is imported into libstdc++.
81 #if defined(__GNUC__) && __GNUC__ >= 4
82 #define FBSTRING_LIKELY(x)   (__builtin_expect((x), 1))
83 #define FBSTRING_UNLIKELY(x) (__builtin_expect((x), 0))
84 #else
85 #define FBSTRING_LIKELY(x)   (x)
86 #define FBSTRING_UNLIKELY(x) (x)
87 #endif
88
89 #pragma GCC diagnostic push
90 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
91 #pragma GCC diagnostic ignored "-Wshadow"
92 // GCC 4.9 has a false positive in setSmallSize (probably
93 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59124), disable
94 // compile-time array bound checking.
95 #pragma GCC diagnostic ignored "-Warray-bounds"
96
97 // FBString cannot use throw when replacing std::string, though it may still
98 // use std::__throw_*
99 // nolint
100 #define throw FOLLY_FBSTRING_MAY_NOT_USE_THROW
101
102 #ifdef _LIBSTDCXX_FBSTRING
103 namespace std _GLIBCXX_VISIBILITY(default) {
104 _GLIBCXX_BEGIN_NAMESPACE_VERSION
105 #else
106 namespace folly {
107 #endif
108
109 #if defined(__clang__)
110 # if __has_feature(address_sanitizer)
111 #  define FBSTRING_SANITIZE_ADDRESS
112 # endif
113 #elif defined (__GNUC__) && \
114       (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ >= 5)) && \
115       __SANITIZE_ADDRESS__
116 # define FBSTRING_SANITIZE_ADDRESS
117 #endif
118
119 // When compiling with ASan, always heap-allocate the string even if
120 // it would fit in-situ, so that ASan can detect access to the string
121 // buffer after it has been invalidated (destroyed, resized, etc.).
122 // Note that this flag doesn't remove support for in-situ strings, as
123 // that would break ABI-compatibility and wouldn't allow linking code
124 // compiled with this flag with code compiled without.
125 #ifdef FBSTRING_SANITIZE_ADDRESS
126 # define FBSTRING_DISABLE_SMALL_STRING_OPTIMIZATION
127 #endif
128
129 namespace fbstring_detail {
130
131 template <class InIt, class OutIt>
132 inline
133 OutIt copy_n(InIt b,
134              typename std::iterator_traits<InIt>::difference_type n,
135              OutIt d) {
136   for (; n != 0; --n, ++b, ++d) {
137     *d = *b;
138   }
139   return d;
140 }
141
142 template <class Pod, class T>
143 inline void pod_fill(Pod* b, Pod* e, T c) {
144   assert(b && e && b <= e);
145   /*static*/ if (sizeof(T) == 1) {
146     memset(b, c, e - b);
147   } else {
148     auto const ee = b + ((e - b) & ~7u);
149     for (; b != ee; b += 8) {
150       b[0] = c;
151       b[1] = c;
152       b[2] = c;
153       b[3] = c;
154       b[4] = c;
155       b[5] = c;
156       b[6] = c;
157       b[7] = c;
158     }
159     // Leftovers
160     for (; b != e; ++b) {
161       *b = c;
162     }
163   }
164 }
165
166 /*
167  * Lightly structured memcpy, simplifies copying PODs and introduces
168  * some asserts. Unfortunately using this function may cause
169  * measurable overhead (presumably because it adjusts from a begin/end
170  * convention to a pointer/size convention, so it does some extra
171  * arithmetic even though the caller might have done the inverse
172  * adaptation outside).
173  */
174 template <class Pod>
175 inline void pod_copy(const Pod* b, const Pod* e, Pod* d) {
176   assert(e >= b);
177   assert(d >= e || d + (e - b) <= b);
178   memcpy(d, b, (e - b) * sizeof(Pod));
179 }
180
181 /*
182  * Lightly structured memmove, simplifies copying PODs and introduces
183  * some asserts
184  */
185 template <class Pod>
186 inline void pod_move(const Pod* b, const Pod* e, Pod* d) {
187   assert(e >= b);
188   memmove(d, b, (e - b) * sizeof(*b));
189 }
190
191 } // namespace fbstring_detail
192
193 /**
194  * Defines a special acquisition method for constructing fbstring
195  * objects. AcquireMallocatedString means that the user passes a
196  * pointer to a malloc-allocated string that the fbstring object will
197  * take into custody.
198  */
199 enum class AcquireMallocatedString {};
200
201 /*
202  * fbstring_core_model is a mock-up type that defines all required
203  * signatures of a fbstring core. The fbstring class itself uses such
204  * a core object to implement all of the numerous member functions
205  * required by the standard.
206  *
207  * If you want to define a new core, copy the definition below and
208  * implement the primitives. Then plug the core into basic_fbstring as
209  * a template argument.
210
211 template <class Char>
212 class fbstring_core_model {
213 public:
214   fbstring_core_model();
215   fbstring_core_model(const fbstring_core_model &);
216   ~fbstring_core_model();
217   // Returns a pointer to string's buffer (currently only contiguous
218   // strings are supported). The pointer is guaranteed to be valid
219   // until the next call to a non-const member function.
220   const Char * data() const;
221   // Much like data(), except the string is prepared to support
222   // character-level changes. This call is a signal for
223   // e.g. reference-counted implementation to fork the data. The
224   // pointer is guaranteed to be valid until the next call to a
225   // non-const member function.
226   Char * mutable_data();
227   // Returns a pointer to string's buffer and guarantees that a
228   // readable '\0' lies right after the buffer. The pointer is
229   // guaranteed to be valid until the next call to a non-const member
230   // function.
231   const Char * c_str() const;
232   // Shrinks the string by delta characters. Asserts that delta <=
233   // size().
234   void shrink(size_t delta);
235   // Expands the string by delta characters (i.e. after this call
236   // size() will report the old size() plus delta) but without
237   // initializing the expanded region. The expanded region is
238   // zero-terminated. Returns a pointer to the memory to be
239   // initialized (the beginning of the expanded portion). The caller
240   // is expected to fill the expanded area appropriately.
241   // If expGrowth is true, exponential growth is guaranteed.
242   Char* expand_noinit(size_t delta, bool expGrowth);
243   // Expands the string by one character and sets the last character
244   // to c.
245   void push_back(Char c);
246   // Returns the string's size.
247   size_t size() const;
248   // Returns the string's capacity, i.e. maximum size that the string
249   // can grow to without reallocation. Note that for reference counted
250   // strings that's technically a lie - even assigning characters
251   // within the existing size would cause a reallocation.
252   size_t capacity() const;
253   // Returns true if the data underlying the string is actually shared
254   // across multiple strings (in a refcounted fashion).
255   bool isShared() const;
256   // Makes sure that at least minCapacity characters are available for
257   // the string without reallocation. For reference-counted strings,
258   // it should fork the data even if minCapacity < size().
259   void reserve(size_t minCapacity);
260 private:
261   // Do not implement
262   fbstring_core_model& operator=(const fbstring_core_model &);
263 };
264 */
265
266 /**
267  * This is the core of the string. The code should work on 32- and
268  * 64-bit and both big- and little-endianan architectures with any
269  * Char size.
270  *
271  * The storage is selected as follows (assuming we store one-byte
272  * characters on a 64-bit machine): (a) "small" strings between 0 and
273  * 23 chars are stored in-situ without allocation (the rightmost byte
274  * stores the size); (b) "medium" strings from 24 through 254 chars
275  * are stored in malloc-allocated memory that is copied eagerly; (c)
276  * "large" strings of 255 chars and above are stored in a similar
277  * structure as medium arrays, except that the string is
278  * reference-counted and copied lazily. the reference count is
279  * allocated right before the character array.
280  *
281  * The discriminator between these three strategies sits in two
282  * bits of the rightmost char of the storage. If neither is set, then the
283  * string is small (and its length sits in the lower-order bits on
284  * little-endian or the high-order bits on big-endian of that
285  * rightmost character). If the MSb is set, the string is medium width.
286  * If the second MSb is set, then the string is large. On little-endian,
287  * these 2 bits are the 2 MSbs of MediumLarge::capacity_, while on
288  * big-endian, these 2 bits are the 2 LSbs. This keeps both little-endian
289  * and big-endian fbstring_core equivalent with merely different ops used
290  * to extract capacity/category.
291  */
292 template <class Char> class fbstring_core {
293 public:
294   fbstring_core() noexcept { reset(); }
295
296   fbstring_core(const fbstring_core & rhs) {
297     assert(&rhs != this);
298     // Simplest case first: small strings are bitblitted
299     if (rhs.category() == Category::isSmall) {
300       static_assert(offsetof(MediumLarge, data_) == 0,
301           "fbstring layout failure");
302       static_assert(offsetof(MediumLarge, size_) == sizeof(ml_.data_),
303           "fbstring layout failure");
304       static_assert(offsetof(MediumLarge, capacity_) == 2 * sizeof(ml_.data_),
305           "fbstring layout failure");
306       // Just write the whole thing, don't look at details. In
307       // particular we need to copy capacity anyway because we want
308       // to set the size (don't forget that the last character,
309       // which stores a short string's length, is shared with the
310       // ml_.capacity field).
311       ml_ = rhs.ml_;
312       assert(category() == Category::isSmall && this->size() == rhs.size());
313     } else if (rhs.category() == Category::isLarge) {
314       // Large strings are just refcounted
315       ml_ = rhs.ml_;
316       RefCounted::incrementRefs(ml_.data_);
317       assert(category() == Category::isLarge && size() == rhs.size());
318     } else {
319       // Medium strings are copied eagerly. Don't forget to allocate
320       // one extra Char for the null terminator.
321       auto const allocSize =
322            goodMallocSize((1 + rhs.ml_.size_) * sizeof(Char));
323       ml_.data_ = static_cast<Char*>(checkedMalloc(allocSize));
324       // Also copies terminator.
325       fbstring_detail::pod_copy(rhs.ml_.data_,
326                                 rhs.ml_.data_ + rhs.ml_.size_ + 1,
327                                 ml_.data_);
328       ml_.size_ = rhs.ml_.size_;
329       ml_.setCapacity(allocSize / sizeof(Char) - 1, Category::isMedium);
330       assert(category() == Category::isMedium);
331     }
332     assert(size() == rhs.size());
333     assert(memcmp(data(), rhs.data(), size() * sizeof(Char)) == 0);
334   }
335
336   fbstring_core(fbstring_core&& goner) noexcept {
337     // Take goner's guts
338     ml_ = goner.ml_;
339     // Clean goner's carcass
340     goner.reset();
341   }
342
343   fbstring_core(const Char *const data, const size_t size) {
344 #ifndef NDEBUG
345 #ifndef _LIBSTDCXX_FBSTRING
346     SCOPE_EXIT {
347       assert(this->size() == size);
348       assert(memcmp(this->data(), data, size * sizeof(Char)) == 0);
349     };
350 #endif
351 #endif
352
353 #ifndef FBSTRING_DISABLE_SMALL_STRING_OPTIMIZATION
354     // Simplest case first: small strings are bitblitted
355     if (size <= maxSmallSize) {
356       // Layout is: Char* data_, size_t size_, size_t capacity_
357       static_assert(sizeof(*this) == sizeof(Char*) + 2 * sizeof(size_t),
358           "fbstring has unexpected size");
359       static_assert(sizeof(Char*) == sizeof(size_t),
360           "fbstring size assumption violation");
361       // sizeof(size_t) must be a power of 2
362       static_assert((sizeof(size_t) & (sizeof(size_t) - 1)) == 0,
363           "fbstring size assumption violation");
364
365       // If data is aligned, use fast word-wise copying. Otherwise,
366       // use conservative memcpy.
367       if (reinterpret_cast<size_t>(data) & (sizeof(size_t) - 1)) {
368         fbstring_detail::pod_copy(data, data + size, small_);
369       } else {
370         // Copy one word at a time.
371         // NOTE: This reads bytes which are outside the range of the
372         // string, and makes ASan unhappy, but the small case is
373         // disabled under ASan.
374
375         const size_t byteSize = size * sizeof(Char);
376         constexpr size_t wordWidth = sizeof(size_t);
377         switch ((byteSize + wordWidth - 1) / wordWidth) { // Number of words.
378         case 3:
379           ml_.capacity_ = reinterpret_cast<const size_t*>(data)[2];
380         case 2:
381           ml_.size_ = reinterpret_cast<const size_t*>(data)[1];
382         case 1:
383           ml_.data_ = *reinterpret_cast<Char**>(const_cast<Char*>(data));
384         case 0:
385           break;
386         }
387       }
388       setSmallSize(size);
389     } else
390 #endif // FBSTRING_DISABLE_SMALL_STRING_OPTIMIZATION
391     {
392       if (size <= maxMediumSize) {
393         // Medium strings are allocated normally. Don't forget to
394         // allocate one extra Char for the terminating null.
395         auto const allocSize = goodMallocSize((1 + size) * sizeof(Char));
396         ml_.data_ = static_cast<Char*>(checkedMalloc(allocSize));
397         fbstring_detail::pod_copy(data, data + size, ml_.data_);
398         ml_.size_ = size;
399         ml_.setCapacity(allocSize / sizeof(Char) - 1, Category::isMedium);
400       } else {
401         // Large strings are allocated differently
402         size_t effectiveCapacity = size;
403         auto const newRC = RefCounted::create(data, & effectiveCapacity);
404         ml_.data_ = newRC->data_;
405         ml_.size_ = size;
406         ml_.setCapacity(effectiveCapacity, Category::isLarge);
407       }
408       ml_.data_[size] = '\0';
409     }
410   }
411
412   ~fbstring_core() noexcept {
413     auto const c = category();
414     if (c == Category::isSmall) {
415       return;
416     }
417     if (c == Category::isMedium) {
418       free(ml_.data_);
419       return;
420     }
421     RefCounted::decrementRefs(ml_.data_);
422   }
423
424   // Snatches a previously mallocated string. The parameter "size"
425   // is the size of the string, and the parameter "allocatedSize"
426   // is the size of the mallocated block.  The string must be
427   // \0-terminated, so allocatedSize >= size + 1 and data[size] == '\0'.
428   //
429   // So if you want a 2-character string, pass malloc(3) as "data",
430   // pass 2 as "size", and pass 3 as "allocatedSize".
431   fbstring_core(Char * const data,
432                 const size_t size,
433                 const size_t allocatedSize,
434                 AcquireMallocatedString) {
435     if (size > 0) {
436       assert(allocatedSize >= size + 1);
437       assert(data[size] == '\0');
438       // Use the medium string storage
439       ml_.data_ = data;
440       ml_.size_ = size;
441       // Don't forget about null terminator
442       ml_.setCapacity(allocatedSize - 1, Category::isMedium);
443     } else {
444       // No need for the memory
445       free(data);
446       reset();
447     }
448   }
449
450   // swap below doesn't test whether &rhs == this (and instead
451   // potentially does extra work) on the premise that the rarity of
452   // that situation actually makes the check more expensive than is
453   // worth.
454   void swap(fbstring_core & rhs) {
455     auto const t = ml_;
456     ml_ = rhs.ml_;
457     rhs.ml_ = t;
458   }
459
460   // In C++11 data() and c_str() are 100% equivalent.
461   const Char * data() const {
462     return c_str();
463   }
464
465   Char * mutable_data() {
466     auto const c = category();
467     if (c == Category::isSmall) {
468       return small_;
469     }
470     assert(c == Category::isMedium || c == Category::isLarge);
471     if (c == Category::isLarge && RefCounted::refs(ml_.data_) > 1) {
472       // Ensure unique.
473       size_t effectiveCapacity = ml_.capacity();
474       auto const newRC = RefCounted::create(& effectiveCapacity);
475       // If this fails, someone placed the wrong capacity in an
476       // fbstring.
477       assert(effectiveCapacity >= ml_.capacity());
478       // Also copies terminator.
479       fbstring_detail::pod_copy(ml_.data_, ml_.data_ + ml_.size_ + 1,
480                                 newRC->data_);
481       RefCounted::decrementRefs(ml_.data_);
482       ml_.data_ = newRC->data_;
483     }
484     return ml_.data_;
485   }
486
487   const Char * c_str() const {
488     auto const c = category();
489     if (c == Category::isSmall) {
490       assert(small_[smallSize()] == '\0');
491       return small_;
492     }
493     assert(c == Category::isMedium || c == Category::isLarge);
494     assert(ml_.data_[ml_.size_] == '\0');
495     return ml_.data_;
496   }
497
498   void shrink(const size_t delta) {
499     if (category() == Category::isSmall) {
500       // Check for underflow
501       assert(delta <= smallSize());
502       setSmallSize(smallSize() - delta);
503     } else if (category() == Category::isMedium ||
504                RefCounted::refs(ml_.data_) == 1) {
505       // Medium strings and unique large strings need no special
506       // handling.
507       assert(ml_.size_ >= delta);
508       ml_.size_ -= delta;
509       ml_.data_[ml_.size_] = '\0';
510     } else {
511       assert(ml_.size_ >= delta);
512       // Shared large string, must make unique. This is because of the
513       // durn terminator must be written, which may trample the shared
514       // data.
515       if (delta) {
516         fbstring_core(ml_.data_, ml_.size_ - delta).swap(*this);
517       }
518       // No need to write the terminator.
519     }
520   }
521
522   void reserve(size_t minCapacity) {
523     if (category() == Category::isLarge) {
524       // Ensure unique
525       if (RefCounted::refs(ml_.data_) > 1) {
526         // We must make it unique regardless; in-place reallocation is
527         // useless if the string is shared. In order to not surprise
528         // people, reserve the new block at current capacity or
529         // more. That way, a string's capacity never shrinks after a
530         // call to reserve.
531         minCapacity = std::max(minCapacity, ml_.capacity());
532         auto const newRC = RefCounted::create(& minCapacity);
533         // Also copies terminator.
534         fbstring_detail::pod_copy(ml_.data_, ml_.data_ + ml_.size_ + 1,
535                                    newRC->data_);
536         RefCounted::decrementRefs(ml_.data_);
537         ml_.data_ = newRC->data_;
538         ml_.setCapacity(minCapacity, Category::isLarge);
539         // size remains unchanged
540       } else {
541         // String is not shared, so let's try to realloc (if needed)
542         if (minCapacity > ml_.capacity()) {
543           // Asking for more memory
544           auto const newRC =
545                RefCounted::reallocate(ml_.data_, ml_.size_,
546                                       ml_.capacity(), minCapacity);
547           ml_.data_ = newRC->data_;
548           ml_.setCapacity(minCapacity, Category::isLarge);
549         }
550         assert(capacity() >= minCapacity);
551       }
552     } else if (category() == Category::isMedium) {
553       // String is not shared
554       if (minCapacity <= ml_.capacity()) {
555         return; // nothing to do, there's enough room
556       }
557       if (minCapacity <= maxMediumSize) {
558         // Keep the string at medium size. Don't forget to allocate
559         // one extra Char for the terminating null.
560         size_t capacityBytes = goodMallocSize((1 + minCapacity) * sizeof(Char));
561         // Also copies terminator.
562         ml_.data_ = static_cast<Char *>(
563           smartRealloc(
564             ml_.data_,
565             (ml_.size_ + 1) * sizeof(Char),
566             (ml_.capacity() + 1) * sizeof(Char),
567             capacityBytes));
568         ml_.setCapacity(capacityBytes / sizeof(Char) - 1, Category::isMedium);
569       } else {
570         // Conversion from medium to large string
571         fbstring_core nascent;
572         // Will recurse to another branch of this function
573         nascent.reserve(minCapacity);
574         nascent.ml_.size_ = ml_.size_;
575         // Also copies terminator.
576         fbstring_detail::pod_copy(ml_.data_, ml_.data_ + ml_.size_ + 1,
577                                   nascent.ml_.data_);
578         nascent.swap(*this);
579         assert(capacity() >= minCapacity);
580       }
581     } else {
582       assert(category() == Category::isSmall);
583 #ifndef FBSTRING_DISABLE_SMALL_STRING_OPTIMIZATION
584       if (minCapacity <= maxSmallSize) {
585         // small
586         // Nothing to do, everything stays put
587       } else
588 #endif // FBSTRING_DISABLE_SMALL_STRING_OPTIMIZATION
589       if (minCapacity <= maxMediumSize) {
590         // medium
591         // Don't forget to allocate one extra Char for the terminating null
592         auto const allocSizeBytes =
593           goodMallocSize((1 + minCapacity) * sizeof(Char));
594         auto const pData = static_cast<Char*>(checkedMalloc(allocSizeBytes));
595         auto const size = smallSize();
596         // Also copies terminator.
597         fbstring_detail::pod_copy(small_, small_ + size + 1, pData);
598         ml_.data_ = pData;
599         ml_.size_ = size;
600         ml_.setCapacity(allocSizeBytes / sizeof(Char) - 1, Category::isMedium);
601       } else {
602         // large
603         auto const newRC = RefCounted::create(& minCapacity);
604         auto const size = smallSize();
605         // Also copies terminator.
606         fbstring_detail::pod_copy(small_, small_ + size + 1, newRC->data_);
607         ml_.data_ = newRC->data_;
608         ml_.size_ = size;
609         ml_.setCapacity(minCapacity, Category::isLarge);
610         assert(capacity() >= minCapacity);
611       }
612     }
613     assert(capacity() >= minCapacity);
614   }
615
616   Char * expand_noinit(const size_t delta, bool expGrowth = false) {
617     // Strategy is simple: make room, then change size
618     assert(capacity() >= size());
619     size_t sz, newSz;
620     if (category() == Category::isSmall) {
621       sz = smallSize();
622       newSz = sz + delta;
623 #ifndef FBSTRING_DISABLE_SMALL_STRING_OPTIMIZATION
624       if (FBSTRING_LIKELY(newSz <= maxSmallSize)) {
625         setSmallSize(newSz);
626         return small_ + sz;
627       }
628 #endif // FBSTRING_DISABLE_SMALL_STRING_OPTIMIZATION
629       reserve(expGrowth ? std::max(newSz, 2 * maxSmallSize) : newSz);
630     } else {
631       sz = ml_.size_;
632       newSz = sz + delta;
633       if (FBSTRING_UNLIKELY(newSz > capacity())) {
634         // ensures not shared
635         reserve(expGrowth ? std::max(newSz, 1 + capacity() * 3 / 2) : newSz);
636       }
637     }
638     assert(capacity() >= newSz);
639     // Category can't be small - we took care of that above
640     assert(category() == Category::isMedium || category() == Category::isLarge);
641     ml_.size_ = newSz;
642     ml_.data_[newSz] = '\0';
643     assert(size() == newSz);
644     return ml_.data_ + sz;
645   }
646
647   void push_back(Char c) {
648     *expand_noinit(1, /* expGrowth */ true) = c;
649   }
650
651   size_t size() const {
652     return category() == Category::isSmall ? smallSize() : ml_.size_;
653   }
654
655   size_t capacity() const {
656     switch (category()) {
657       case Category::isSmall:
658         return maxSmallSize;
659       case Category::isLarge:
660         // For large-sized strings, a multi-referenced chunk has no
661         // available capacity. This is because any attempt to append
662         // data would trigger a new allocation.
663         if (RefCounted::refs(ml_.data_) > 1) return ml_.size_;
664       default: {}
665     }
666     return ml_.capacity();
667   }
668
669   bool isShared() const {
670     return category() == Category::isLarge && RefCounted::refs(ml_.data_) > 1;
671   }
672
673 private:
674   // Disabled
675   fbstring_core & operator=(const fbstring_core & rhs);
676
677   // Equivalent to setSmallSize(0) but a few ns faster in
678   // microbenchmarks.
679   void reset() {
680     ml_.capacity_ = kIsLittleEndian
681       ? maxSmallSize << (8 * (sizeof(size_t) - sizeof(Char)))
682       : maxSmallSize << 2;
683     small_[0] = '\0';
684     assert(category() == Category::isSmall && size() == 0);
685   }
686
687   struct RefCounted {
688     std::atomic<size_t> refCount_;
689     Char data_[1];
690
691     static RefCounted * fromData(Char * p) {
692       return static_cast<RefCounted*>(
693         static_cast<void*>(
694           static_cast<unsigned char*>(static_cast<void*>(p))
695           - sizeof(refCount_)));
696     }
697
698     static size_t refs(Char * p) {
699       return fromData(p)->refCount_.load(std::memory_order_acquire);
700     }
701
702     static void incrementRefs(Char * p) {
703       fromData(p)->refCount_.fetch_add(1, std::memory_order_acq_rel);
704     }
705
706     static void decrementRefs(Char * p) {
707       auto const dis = fromData(p);
708       size_t oldcnt = dis->refCount_.fetch_sub(1, std::memory_order_acq_rel);
709       assert(oldcnt > 0);
710       if (oldcnt == 1) {
711         free(dis);
712       }
713     }
714
715     static RefCounted * create(size_t * size) {
716       // Don't forget to allocate one extra Char for the terminating
717       // null. In this case, however, one Char is already part of the
718       // struct.
719       const size_t allocSize = goodMallocSize(
720         sizeof(RefCounted) + *size * sizeof(Char));
721       auto result = static_cast<RefCounted*>(checkedMalloc(allocSize));
722       result->refCount_.store(1, std::memory_order_release);
723       *size = (allocSize - sizeof(RefCounted)) / sizeof(Char);
724       return result;
725     }
726
727     static RefCounted * create(const Char * data, size_t * size) {
728       const size_t effectiveSize = *size;
729       auto result = create(size);
730       fbstring_detail::pod_copy(data, data + effectiveSize, result->data_);
731       return result;
732     }
733
734     static RefCounted * reallocate(Char *const data,
735                                    const size_t currentSize,
736                                    const size_t currentCapacity,
737                                    const size_t newCapacity) {
738       assert(newCapacity > 0 && newCapacity > currentSize);
739       auto const dis = fromData(data);
740       assert(dis->refCount_.load(std::memory_order_acquire) == 1);
741       // Don't forget to allocate one extra Char for the terminating
742       // null. In this case, however, one Char is already part of the
743       // struct.
744       auto result = static_cast<RefCounted*>(
745              smartRealloc(dis,
746                           sizeof(RefCounted) + currentSize * sizeof(Char),
747                           sizeof(RefCounted) + currentCapacity * sizeof(Char),
748                           sizeof(RefCounted) + newCapacity * sizeof(Char)));
749       assert(result->refCount_.load(std::memory_order_acquire) == 1);
750       return result;
751     }
752   };
753
754   typedef std::conditional<sizeof(size_t) == 4, uint32_t, uint64_t>::type
755           category_type;
756
757   enum class Category : category_type {
758     isSmall = 0,
759     isMedium = kIsLittleEndian
760       ? sizeof(size_t) == 4 ? 0x80000000 : 0x8000000000000000
761       : 0x2,
762     isLarge =  kIsLittleEndian
763       ? sizeof(size_t) == 4 ? 0x40000000 : 0x4000000000000000
764       : 0x1,
765   };
766
767   Category category() const {
768     // works for both big-endian and little-endian
769     return static_cast<Category>(ml_.capacity_ & categoryExtractMask);
770   }
771
772   struct MediumLarge {
773     Char * data_;
774     size_t size_;
775     size_t capacity_;
776
777     size_t capacity() const {
778       return kIsLittleEndian
779         ? capacity_ & capacityExtractMask
780         : capacity_ >> 2;
781     }
782
783     void setCapacity(size_t cap, Category cat) {
784         capacity_ = kIsLittleEndian
785           ? cap | static_cast<category_type>(cat)
786           : (cap << 2) | static_cast<category_type>(cat);
787     }
788   };
789
790   union {
791     Char small_[sizeof(MediumLarge) / sizeof(Char)];
792     MediumLarge ml_;
793   };
794
795   enum : size_t {
796     lastChar = sizeof(MediumLarge) - 1,
797     maxSmallSize = lastChar / sizeof(Char),
798     maxMediumSize = 254 / sizeof(Char),            // coincides with the small
799                                                    // bin size in dlmalloc
800     categoryExtractMask = kIsLittleEndian
801       ? sizeof(size_t) == 4 ? 0xC0000000 : 0xC000000000000000
802       : 0x3,
803     capacityExtractMask = kIsLittleEndian
804       ? ~categoryExtractMask
805       : 0x0 /*unused*/,
806   };
807   static_assert(!(sizeof(MediumLarge) % sizeof(Char)),
808                 "Corrupt memory layout for fbstring.");
809
810   size_t smallSize() const {
811     assert(category() == Category::isSmall);
812     constexpr auto shift = kIsLittleEndian ? 0 : 2;
813     auto smallShifted = static_cast<size_t>(small_[maxSmallSize]) >> shift;
814     assert(static_cast<size_t>(maxSmallSize) >= smallShifted);
815     return static_cast<size_t>(maxSmallSize) - smallShifted;
816   }
817
818   void setSmallSize(size_t s) {
819     // Warning: this should work with uninitialized strings too,
820     // so don't assume anything about the previous value of
821     // small_[maxSmallSize].
822     assert(s <= maxSmallSize);
823     constexpr auto shift = kIsLittleEndian ? 0 : 2;
824     small_[maxSmallSize] = (maxSmallSize - s) << shift;
825     small_[s] = '\0';
826     assert(category() == Category::isSmall && size() == s);
827   }
828 };
829
830 #ifndef _LIBSTDCXX_FBSTRING
831 /**
832  * Dummy fbstring core that uses an actual std::string. This doesn't
833  * make any sense - it's just for testing purposes.
834  */
835 template <class Char>
836 class dummy_fbstring_core {
837 public:
838   dummy_fbstring_core() {
839   }
840   dummy_fbstring_core(const dummy_fbstring_core& another)
841       : backend_(another.backend_) {
842   }
843   dummy_fbstring_core(const Char * s, size_t n)
844       : backend_(s, n) {
845   }
846   void swap(dummy_fbstring_core & rhs) {
847     backend_.swap(rhs.backend_);
848   }
849   const Char * data() const {
850     return backend_.data();
851   }
852   Char * mutable_data() {
853     //assert(!backend_.empty());
854     return &*backend_.begin();
855   }
856   void shrink(size_t delta) {
857     assert(delta <= size());
858     backend_.resize(size() - delta);
859   }
860   Char * expand_noinit(size_t delta) {
861     auto const sz = size();
862     backend_.resize(size() + delta);
863     return backend_.data() + sz;
864   }
865   void push_back(Char c) {
866     backend_.push_back(c);
867   }
868   size_t size() const {
869     return backend_.size();
870   }
871   size_t capacity() const {
872     return backend_.capacity();
873   }
874   bool isShared() const {
875     return false;
876   }
877   void reserve(size_t minCapacity) {
878     backend_.reserve(minCapacity);
879   }
880
881 private:
882   std::basic_string<Char> backend_;
883 };
884 #endif // !_LIBSTDCXX_FBSTRING
885
886 /**
887  * This is the basic_string replacement. For conformity,
888  * basic_fbstring takes the same template parameters, plus the last
889  * one which is the core.
890  */
891 #ifdef _LIBSTDCXX_FBSTRING
892 template <typename E, class T, class A, class Storage>
893 #else
894 template <typename E,
895           class T = std::char_traits<E>,
896           class A = std::allocator<E>,
897           class Storage = fbstring_core<E> >
898 #endif
899 class basic_fbstring {
900
901   static void enforce(
902       bool condition,
903       void (*throw_exc)(const char*),
904       const char* msg) {
905     if (!condition) throw_exc(msg);
906   }
907
908   bool isSane() const {
909     return
910       begin() <= end() &&
911       empty() == (size() == 0) &&
912       empty() == (begin() == end()) &&
913       size() <= max_size() &&
914       capacity() <= max_size() &&
915       size() <= capacity() &&
916       begin()[size()] == '\0';
917   }
918
919   struct Invariant;
920   friend struct Invariant;
921   struct Invariant {
922 #ifndef NDEBUG
923     explicit Invariant(const basic_fbstring& s) : s_(s) {
924       assert(s_.isSane());
925     }
926     ~Invariant() {
927       assert(s_.isSane());
928     }
929   private:
930     const basic_fbstring& s_;
931 #else
932     explicit Invariant(const basic_fbstring&) {}
933 #endif
934     Invariant& operator=(const Invariant&);
935   };
936
937 public:
938   // types
939   typedef T traits_type;
940   typedef typename traits_type::char_type value_type;
941   typedef A allocator_type;
942   typedef typename A::size_type size_type;
943   typedef typename A::difference_type difference_type;
944
945   typedef typename A::reference reference;
946   typedef typename A::const_reference const_reference;
947   typedef typename A::pointer pointer;
948   typedef typename A::const_pointer const_pointer;
949
950   typedef E* iterator;
951   typedef const E* const_iterator;
952   typedef std::reverse_iterator<iterator
953 #ifdef NO_ITERATOR_TRAITS
954                                 , value_type
955 #endif
956                                 > reverse_iterator;
957   typedef std::reverse_iterator<const_iterator
958 #ifdef NO_ITERATOR_TRAITS
959                                 , const value_type
960 #endif
961                                 > const_reverse_iterator;
962
963   static const size_type npos;                     // = size_type(-1)
964
965 private:
966   static void procrustes(size_type& n, size_type nmax) {
967     if (n > nmax) n = nmax;
968   }
969
970 public:
971   // C++11 21.4.2 construct/copy/destroy
972
973   // Note: while the following two constructors can be (and previously were)
974   // collapsed into one constructor written this way:
975   //
976   //   explicit basic_fbstring(const A& a = A()) noexcept { }
977   //
978   // This can cause Clang (at least version 3.7) to fail with the error:
979   //   "chosen constructor is explicit in copy-initialization ...
980   //   in implicit initialization of field '(x)' with omitted initializer"
981   //
982   // if used in a struct which is default-initialized.  Hence the split into
983   // these two separate constructors.
984
985   basic_fbstring() noexcept : basic_fbstring(A()) {
986   }
987
988   explicit basic_fbstring(const A&) noexcept {
989   }
990
991   basic_fbstring(const basic_fbstring& str)
992       : store_(str.store_) {
993   }
994
995   // Move constructor
996   basic_fbstring(basic_fbstring&& goner) noexcept
997       : store_(std::move(goner.store_)) {
998   }
999
1000 #ifndef _LIBSTDCXX_FBSTRING
1001   // This is defined for compatibility with std::string
1002   /* implicit */ basic_fbstring(const std::string& str)
1003       : store_(str.data(), str.size()) {
1004   }
1005 #endif
1006
1007   basic_fbstring(const basic_fbstring& str,
1008                  size_type pos,
1009                  size_type n = npos,
1010                  const A& /* a */ = A()) {
1011     assign(str, pos, n);
1012   }
1013
1014   /* implicit */ basic_fbstring(const value_type* s, const A& /*a*/ = A())
1015       : store_(s, s
1016           ? traits_type::length(s)
1017           : (std::__throw_logic_error(
1018                 "basic_fbstring: null pointer initializer not valid"),
1019              0)) {
1020   }
1021
1022   basic_fbstring(const value_type* s, size_type n, const A& /*a*/ = A())
1023       : store_(s, n) {
1024   }
1025
1026   basic_fbstring(size_type n, value_type c, const A& /*a*/ = A()) {
1027     auto const pData = store_.expand_noinit(n);
1028     fbstring_detail::pod_fill(pData, pData + n, c);
1029   }
1030
1031   template <class InIt>
1032   basic_fbstring(InIt begin, InIt end,
1033                  typename std::enable_if<
1034                  !std::is_same<typename std::remove_const<InIt>::type,
1035                  value_type*>::value, const A>::type & /*a*/ = A()) {
1036     assign(begin, end);
1037   }
1038
1039   // Specialization for const char*, const char*
1040   basic_fbstring(const value_type* b, const value_type* e)
1041       : store_(b, e - b) {
1042   }
1043
1044   // Nonstandard constructor
1045   basic_fbstring(value_type *s, size_type n, size_type c,
1046                  AcquireMallocatedString a)
1047       : store_(s, n, c, a) {
1048   }
1049
1050   // Construction from initialization list
1051   basic_fbstring(std::initializer_list<value_type> il) {
1052     assign(il.begin(), il.end());
1053   }
1054
1055   ~basic_fbstring() noexcept {
1056   }
1057
1058   basic_fbstring& operator=(const basic_fbstring& lhs) {
1059     Invariant checker(*this);
1060
1061     if (FBSTRING_UNLIKELY(&lhs == this)) {
1062       return *this;
1063     }
1064     auto const oldSize = size();
1065     auto const srcSize = lhs.size();
1066     if (capacity() >= srcSize && !store_.isShared()) {
1067       // great, just copy the contents
1068       if (oldSize < srcSize) {
1069         store_.expand_noinit(srcSize - oldSize);
1070       } else {
1071         store_.shrink(oldSize - srcSize);
1072       }
1073       assert(size() == srcSize);
1074       auto srcData = lhs.data();
1075       fbstring_detail::pod_copy(
1076           srcData, srcData + srcSize, store_.mutable_data());
1077     } else {
1078       // need to reallocate, so we may as well create a brand new string
1079       basic_fbstring(lhs).swap(*this);
1080     }
1081     return *this;
1082   }
1083
1084   // Move assignment
1085   basic_fbstring& operator=(basic_fbstring&& goner) noexcept {
1086     if (FBSTRING_UNLIKELY(&goner == this)) {
1087       // Compatibility with std::basic_string<>,
1088       // C++11 21.4.2 [string.cons] / 23 requires self-move-assignment support.
1089       return *this;
1090     }
1091     // No need of this anymore
1092     this->~basic_fbstring();
1093     // Move the goner into this
1094     new(&store_) fbstring_core<E>(std::move(goner.store_));
1095     return *this;
1096   }
1097
1098 #ifndef _LIBSTDCXX_FBSTRING
1099   // Compatibility with std::string
1100   basic_fbstring & operator=(const std::string & rhs) {
1101     return assign(rhs.data(), rhs.size());
1102   }
1103
1104   // Compatibility with std::string
1105   std::string toStdString() const {
1106     return std::string(data(), size());
1107   }
1108 #else
1109   // A lot of code in fbcode still uses this method, so keep it here for now.
1110   const basic_fbstring& toStdString() const {
1111     return *this;
1112   }
1113 #endif
1114
1115   basic_fbstring& operator=(const value_type* s) {
1116     return assign(s);
1117   }
1118
1119   basic_fbstring& operator=(value_type c) {
1120     Invariant checker(*this);
1121
1122     if (empty()) {
1123       store_.expand_noinit(1);
1124     } else if (store_.isShared()) {
1125       basic_fbstring(1, c).swap(*this);
1126       return *this;
1127     } else {
1128       store_.shrink(size() - 1);
1129     }
1130     front() = c;
1131     return *this;
1132   }
1133
1134   basic_fbstring& operator=(std::initializer_list<value_type> il) {
1135     return assign(il.begin(), il.end());
1136   }
1137
1138   // C++11 21.4.3 iterators:
1139   iterator begin() { return store_.mutable_data(); }
1140
1141   const_iterator begin() const { return store_.data(); }
1142
1143   const_iterator cbegin() const { return begin(); }
1144
1145   iterator end() {
1146     return store_.mutable_data() + store_.size();
1147   }
1148
1149   const_iterator end() const {
1150     return store_.data() + store_.size();
1151   }
1152
1153   const_iterator cend() const { return end(); }
1154
1155   reverse_iterator rbegin() {
1156     return reverse_iterator(end());
1157   }
1158
1159   const_reverse_iterator rbegin() const {
1160     return const_reverse_iterator(end());
1161   }
1162
1163   const_reverse_iterator crbegin() const { return rbegin(); }
1164
1165   reverse_iterator rend() {
1166     return reverse_iterator(begin());
1167   }
1168
1169   const_reverse_iterator rend() const {
1170     return const_reverse_iterator(begin());
1171   }
1172
1173   const_reverse_iterator crend() const { return rend(); }
1174
1175   // Added by C++11
1176   // C++11 21.4.5, element access:
1177   const value_type& front() const { return *begin(); }
1178   const value_type& back() const {
1179     assert(!empty());
1180     // Should be begin()[size() - 1], but that branches twice
1181     return *(end() - 1);
1182   }
1183   value_type& front() { return *begin(); }
1184   value_type& back() {
1185     assert(!empty());
1186     // Should be begin()[size() - 1], but that branches twice
1187     return *(end() - 1);
1188   }
1189   void pop_back() {
1190     assert(!empty());
1191     store_.shrink(1);
1192   }
1193
1194   // C++11 21.4.4 capacity:
1195   size_type size() const { return store_.size(); }
1196
1197   size_type length() const { return size(); }
1198
1199   size_type max_size() const {
1200     return std::numeric_limits<size_type>::max();
1201   }
1202
1203   void resize(const size_type n, const value_type c = value_type()) {
1204     Invariant checker(*this);
1205
1206     auto size = this->size();
1207     if (n <= size) {
1208       store_.shrink(size - n);
1209     } else {
1210       auto const delta = n - size;
1211       auto pData = store_.expand_noinit(delta);
1212       fbstring_detail::pod_fill(pData, pData + delta, c);
1213     }
1214     assert(this->size() == n);
1215   }
1216
1217   size_type capacity() const { return store_.capacity(); }
1218
1219   void reserve(size_type res_arg = 0) {
1220     enforce(res_arg <= max_size(), std::__throw_length_error, "");
1221     store_.reserve(res_arg);
1222   }
1223
1224   void shrink_to_fit() {
1225     // Shrink only if slack memory is sufficiently large
1226     if (capacity() < size() * 3 / 2) {
1227       return;
1228     }
1229     basic_fbstring(cbegin(), cend()).swap(*this);
1230   }
1231
1232   void clear() { resize(0); }
1233
1234   bool empty() const { return size() == 0; }
1235
1236   // C++11 21.4.5 element access:
1237   const_reference operator[](size_type pos) const {
1238     return *(begin() + pos);
1239   }
1240
1241   reference operator[](size_type pos) {
1242     return *(begin() + pos);
1243   }
1244
1245   const_reference at(size_type n) const {
1246     enforce(n <= size(), std::__throw_out_of_range, "");
1247     return (*this)[n];
1248   }
1249
1250   reference at(size_type n) {
1251     enforce(n < size(), std::__throw_out_of_range, "");
1252     return (*this)[n];
1253   }
1254
1255   // C++11 21.4.6 modifiers:
1256   basic_fbstring& operator+=(const basic_fbstring& str) {
1257     return append(str);
1258   }
1259
1260   basic_fbstring& operator+=(const value_type* s) {
1261     return append(s);
1262   }
1263
1264   basic_fbstring& operator+=(const value_type c) {
1265     push_back(c);
1266     return *this;
1267   }
1268
1269   basic_fbstring& operator+=(std::initializer_list<value_type> il) {
1270     append(il);
1271     return *this;
1272   }
1273
1274   basic_fbstring& append(const basic_fbstring& str) {
1275 #ifndef NDEBUG
1276     auto desiredSize = size() + str.size();
1277 #endif
1278     append(str.data(), str.size());
1279     assert(size() == desiredSize);
1280     return *this;
1281   }
1282
1283   basic_fbstring& append(const basic_fbstring& str, const size_type pos,
1284                          size_type n) {
1285     const size_type sz = str.size();
1286     enforce(pos <= sz, std::__throw_out_of_range, "");
1287     procrustes(n, sz - pos);
1288     return append(str.data() + pos, n);
1289   }
1290
1291   basic_fbstring& append(const value_type* s, size_type n) {
1292     Invariant checker(*this);
1293
1294     if (FBSTRING_UNLIKELY(!n)) {
1295       // Unlikely but must be done
1296       return *this;
1297     }
1298     auto const oldSize = size();
1299     auto const oldData = data();
1300     // Check for aliasing (rare). We could use "<=" here but in theory
1301     // those do not work for pointers unless the pointers point to
1302     // elements in the same array. For that reason we use
1303     // std::less_equal, which is guaranteed to offer a total order
1304     // over pointers. See discussion at http://goo.gl/Cy2ya for more
1305     // info.
1306     std::less_equal<const value_type*> le;
1307     if (FBSTRING_UNLIKELY(le(oldData, s) && !le(oldData + oldSize, s))) {
1308       assert(le(s + n, oldData + oldSize));
1309       const size_type offset = s - oldData;
1310       store_.reserve(oldSize + n);
1311       // Restore the source
1312       s = data() + offset;
1313     }
1314
1315     fbstring_detail::pod_copy(
1316         s, s + n, store_.expand_noinit(n, /* expGrowth */ true));
1317     assert(size() == oldSize + n);
1318     return *this;
1319   }
1320
1321   basic_fbstring& append(const value_type* s) {
1322     return append(s, traits_type::length(s));
1323   }
1324
1325   basic_fbstring& append(size_type n, value_type c) {
1326     resize(size() + n, c);
1327     return *this;
1328   }
1329
1330   template<class InputIterator>
1331   basic_fbstring& append(InputIterator first, InputIterator last) {
1332     insert(end(), first, last);
1333     return *this;
1334   }
1335
1336   basic_fbstring& append(std::initializer_list<value_type> il) {
1337     return append(il.begin(), il.end());
1338   }
1339
1340   void push_back(const value_type c) {             // primitive
1341     store_.push_back(c);
1342   }
1343
1344   basic_fbstring& assign(const basic_fbstring& str) {
1345     if (&str == this) return *this;
1346     return assign(str.data(), str.size());
1347   }
1348
1349   basic_fbstring& assign(basic_fbstring&& str) {
1350     return *this = std::move(str);
1351   }
1352
1353   basic_fbstring& assign(const basic_fbstring& str, const size_type pos,
1354                          size_type n) {
1355     const size_type sz = str.size();
1356     enforce(pos <= sz, std::__throw_out_of_range, "");
1357     procrustes(n, sz - pos);
1358     return assign(str.data() + pos, n);
1359   }
1360
1361   basic_fbstring& assign(const value_type* s, const size_type n) {
1362     Invariant checker(*this);
1363
1364     // s can alias this, we need to use pod_move.
1365     if (size() >= n) {
1366       fbstring_detail::pod_move(s, s + n, store_.mutable_data());
1367       resize(n);
1368       assert(size() == n);
1369     } else {
1370       const value_type *const s2 = s + size();
1371       fbstring_detail::pod_move(s, s2, store_.mutable_data());
1372       append(s2, n - size());
1373       assert(size() == n);
1374     }
1375     assert(size() == n);
1376     return *this;
1377   }
1378
1379   basic_fbstring& assign(const value_type* s) {
1380     return assign(s, traits_type::length(s));
1381   }
1382
1383   basic_fbstring& assign(std::initializer_list<value_type> il) {
1384     return assign(il.begin(), il.end());
1385   }
1386
1387   template <class ItOrLength, class ItOrChar>
1388   basic_fbstring& assign(ItOrLength first_or_n, ItOrChar last_or_c) {
1389     return replace(begin(), end(), first_or_n, last_or_c);
1390   }
1391
1392   basic_fbstring& insert(size_type pos1, const basic_fbstring& str) {
1393     return insert(pos1, str.data(), str.size());
1394   }
1395
1396   basic_fbstring& insert(size_type pos1, const basic_fbstring& str,
1397                          size_type pos2, size_type n) {
1398     enforce(pos2 <= str.length(), std::__throw_out_of_range, "");
1399     procrustes(n, str.length() - pos2);
1400     return insert(pos1, str.data() + pos2, n);
1401   }
1402
1403   basic_fbstring& insert(size_type pos, const value_type* s, size_type n) {
1404     enforce(pos <= length(), std::__throw_out_of_range, "");
1405     insert(begin() + pos, s, s + n);
1406     return *this;
1407   }
1408
1409   basic_fbstring& insert(size_type pos, const value_type* s) {
1410     return insert(pos, s, traits_type::length(s));
1411   }
1412
1413   basic_fbstring& insert(size_type pos, size_type n, value_type c) {
1414     enforce(pos <= length(), std::__throw_out_of_range, "");
1415     insert(begin() + pos, n, c);
1416     return *this;
1417   }
1418
1419   iterator insert(const_iterator p, const value_type c) {
1420     const size_type pos = p - begin();
1421     insert(p, 1, c);
1422     return begin() + pos;
1423   }
1424
1425 #ifndef _LIBSTDCXX_FBSTRING
1426  private:
1427   typedef std::basic_istream<value_type, traits_type> istream_type;
1428
1429  public:
1430   friend inline istream_type& getline(istream_type& is,
1431                                       basic_fbstring& str,
1432                                       value_type delim) {
1433     Invariant checker(str);
1434
1435     str.clear();
1436     size_t size = 0;
1437     while (true) {
1438       size_t avail = str.capacity() - size;
1439       // fbstring has 1 byte extra capacity for the null terminator,
1440       // and getline null-terminates the read string.
1441       is.getline(str.store_.expand_noinit(avail), avail + 1, delim);
1442       size += is.gcount();
1443
1444       if (is.bad() || is.eof() || !is.fail()) {
1445         // Done by either failure, end of file, or normal read.
1446         if (!is.bad() && !is.eof()) {
1447           --size; // gcount() also accounts for the delimiter.
1448         }
1449         str.resize(size);
1450         break;
1451       }
1452
1453       assert(size == str.size());
1454       assert(size == str.capacity());
1455       // Start at minimum allocation 63 + terminator = 64.
1456       str.reserve(std::max<size_t>(63, 3 * size / 2));
1457       // Clear the error so we can continue reading.
1458       is.clear();
1459     }
1460     return is;
1461   }
1462
1463   friend inline istream_type& getline(istream_type& is, basic_fbstring& str) {
1464     return getline(is, str, '\n');
1465   }
1466 #endif
1467
1468 private:
1469   template <int i> class Selector {};
1470
1471   iterator insertImplDiscr(const_iterator p,
1472                            size_type n, value_type c, Selector<1>) {
1473     Invariant checker(*this);
1474
1475     auto const pos = p - begin();
1476     assert(p >= begin() && p <= end());
1477     if (capacity() - size() < n) {
1478       const size_type sz = p - begin();
1479       reserve(size() + n);
1480       p = begin() + sz;
1481     }
1482     const iterator oldEnd = end();
1483     if (n < size_type(oldEnd - p)) {
1484       append(oldEnd - n, oldEnd);
1485       // Also copies terminator.
1486       fbstring_detail::pod_move(&*p, &*oldEnd - n + 1, begin() + pos + n);
1487       std::fill(begin() + pos, begin() + pos + n, c);
1488     } else {
1489       append(n - (end() - p), c);
1490       append(iterator(p), oldEnd);
1491       std::fill(iterator(p), oldEnd, c);
1492     }
1493     return begin() + pos;
1494   }
1495
1496   template<class InputIter>
1497   iterator insertImplDiscr(const_iterator i,
1498                            InputIter b, InputIter e, Selector<0>) {
1499     return insertImpl(i, b, e,
1500                typename std::iterator_traits<InputIter>::iterator_category());
1501   }
1502
1503   template <class FwdIterator>
1504   iterator insertImpl(const_iterator i,
1505                   FwdIterator s1, FwdIterator s2, std::forward_iterator_tag) {
1506     Invariant checker(*this);
1507
1508     const size_type pos = i - begin();
1509     const typename std::iterator_traits<FwdIterator>::difference_type n2 =
1510       std::distance(s1, s2);
1511     assert(n2 >= 0);
1512     using namespace fbstring_detail;
1513     assert(pos <= size());
1514
1515     const typename std::iterator_traits<FwdIterator>::difference_type maxn2 =
1516       capacity() - size();
1517     if (maxn2 < n2) {
1518       // realloc the string
1519       reserve(size() + n2);
1520       i = begin() + pos;
1521     }
1522     if (pos + n2 <= size()) {
1523       const iterator tailBegin = end() - n2;
1524       store_.expand_noinit(n2);
1525       fbstring_detail::pod_copy(tailBegin, tailBegin + n2, end() - n2);
1526       std::copy(const_reverse_iterator(tailBegin), const_reverse_iterator(i),
1527                 reverse_iterator(tailBegin + n2));
1528       std::copy(s1, s2, begin() + pos);
1529     } else {
1530       FwdIterator t = s1;
1531       const size_type old_size = size();
1532       std::advance(t, old_size - pos);
1533       const size_t newElems = std::distance(t, s2);
1534       store_.expand_noinit(n2);
1535       std::copy(t, s2, begin() + old_size);
1536       fbstring_detail::pod_copy(data() + pos, data() + old_size,
1537                                  begin() + old_size + newElems);
1538       std::copy(s1, t, begin() + pos);
1539     }
1540     return begin() + pos;
1541   }
1542
1543   template <class InputIterator>
1544   iterator insertImpl(const_iterator i,
1545                       InputIterator b, InputIterator e,
1546                       std::input_iterator_tag) {
1547     const auto pos = i - begin();
1548     basic_fbstring temp(begin(), i);
1549     for (; b != e; ++b) {
1550       temp.push_back(*b);
1551     }
1552     temp.append(i, cend());
1553     swap(temp);
1554     return begin() + pos;
1555   }
1556
1557 public:
1558   template <class ItOrLength, class ItOrChar>
1559   iterator insert(const_iterator p, ItOrLength first_or_n, ItOrChar last_or_c) {
1560     Selector<std::numeric_limits<ItOrLength>::is_specialized> sel;
1561     return insertImplDiscr(p, first_or_n, last_or_c, sel);
1562   }
1563
1564   iterator insert(const_iterator p, std::initializer_list<value_type> il) {
1565     return insert(p, il.begin(), il.end());
1566   }
1567
1568   basic_fbstring& erase(size_type pos = 0, size_type n = npos) {
1569     Invariant checker(*this);
1570
1571     enforce(pos <= length(), std::__throw_out_of_range, "");
1572     procrustes(n, length() - pos);
1573     std::copy(begin() + pos + n, end(), begin() + pos);
1574     resize(length() - n);
1575     return *this;
1576   }
1577
1578   iterator erase(iterator position) {
1579     const size_type pos(position - begin());
1580     enforce(pos <= size(), std::__throw_out_of_range, "");
1581     erase(pos, 1);
1582     return begin() + pos;
1583   }
1584
1585   iterator erase(iterator first, iterator last) {
1586     const size_type pos(first - begin());
1587     erase(pos, last - first);
1588     return begin() + pos;
1589   }
1590
1591   // Replaces at most n1 chars of *this, starting with pos1 with the
1592   // content of str
1593   basic_fbstring& replace(size_type pos1, size_type n1,
1594                           const basic_fbstring& str) {
1595     return replace(pos1, n1, str.data(), str.size());
1596   }
1597
1598   // Replaces at most n1 chars of *this, starting with pos1,
1599   // with at most n2 chars of str starting with pos2
1600   basic_fbstring& replace(size_type pos1, size_type n1,
1601                           const basic_fbstring& str,
1602                           size_type pos2, size_type n2) {
1603     enforce(pos2 <= str.length(), std::__throw_out_of_range, "");
1604     return replace(pos1, n1, str.data() + pos2,
1605                    std::min(n2, str.size() - pos2));
1606   }
1607
1608   // Replaces at most n1 chars of *this, starting with pos, with chars from s
1609   basic_fbstring& replace(size_type pos, size_type n1, const value_type* s) {
1610     return replace(pos, n1, s, traits_type::length(s));
1611   }
1612
1613   // Replaces at most n1 chars of *this, starting with pos, with n2
1614   // occurrences of c
1615   //
1616   // consolidated with
1617   //
1618   // Replaces at most n1 chars of *this, starting with pos, with at
1619   // most n2 chars of str.  str must have at least n2 chars.
1620   template <class StrOrLength, class NumOrChar>
1621   basic_fbstring& replace(size_type pos, size_type n1,
1622                           StrOrLength s_or_n2, NumOrChar n_or_c) {
1623     Invariant checker(*this);
1624
1625     enforce(pos <= size(), std::__throw_out_of_range, "");
1626     procrustes(n1, length() - pos);
1627     const iterator b = begin() + pos;
1628     return replace(b, b + n1, s_or_n2, n_or_c);
1629   }
1630
1631   basic_fbstring& replace(iterator i1, iterator i2, const basic_fbstring& str) {
1632     return replace(i1, i2, str.data(), str.length());
1633   }
1634
1635   basic_fbstring& replace(iterator i1, iterator i2, const value_type* s) {
1636     return replace(i1, i2, s, traits_type::length(s));
1637   }
1638
1639 private:
1640   basic_fbstring& replaceImplDiscr(iterator i1, iterator i2,
1641                                    const value_type* s, size_type n,
1642                                    Selector<2>) {
1643     assert(i1 <= i2);
1644     assert(begin() <= i1 && i1 <= end());
1645     assert(begin() <= i2 && i2 <= end());
1646     return replace(i1, i2, s, s + n);
1647   }
1648
1649   basic_fbstring& replaceImplDiscr(iterator i1, iterator i2,
1650                                    size_type n2, value_type c, Selector<1>) {
1651     const size_type n1 = i2 - i1;
1652     if (n1 > n2) {
1653       std::fill(i1, i1 + n2, c);
1654       erase(i1 + n2, i2);
1655     } else {
1656       std::fill(i1, i2, c);
1657       insert(i2, n2 - n1, c);
1658     }
1659     assert(isSane());
1660     return *this;
1661   }
1662
1663   template <class InputIter>
1664   basic_fbstring& replaceImplDiscr(iterator i1, iterator i2,
1665                                    InputIter b, InputIter e,
1666                                    Selector<0>) {
1667     replaceImpl(i1, i2, b, e,
1668                 typename std::iterator_traits<InputIter>::iterator_category());
1669     return *this;
1670   }
1671
1672 private:
1673  template <class FwdIterator>
1674  bool replaceAliased(iterator /* i1 */,
1675                      iterator /* i2 */,
1676                      FwdIterator /* s1 */,
1677                      FwdIterator /* s2 */,
1678                      std::false_type) {
1679     return false;
1680   }
1681
1682   template <class FwdIterator>
1683   bool replaceAliased(iterator i1, iterator i2,
1684                       FwdIterator s1, FwdIterator s2, std::true_type) {
1685     static const std::less_equal<const value_type*> le =
1686       std::less_equal<const value_type*>();
1687     const bool aliased = le(&*begin(), &*s1) && le(&*s1, &*end());
1688     if (!aliased) {
1689       return false;
1690     }
1691     // Aliased replace, copy to new string
1692     basic_fbstring temp;
1693     temp.reserve(size() - (i2 - i1) + std::distance(s1, s2));
1694     temp.append(begin(), i1).append(s1, s2).append(i2, end());
1695     swap(temp);
1696     return true;
1697   }
1698
1699   template <class FwdIterator>
1700   void replaceImpl(iterator i1, iterator i2,
1701                    FwdIterator s1, FwdIterator s2, std::forward_iterator_tag) {
1702     Invariant checker(*this);
1703
1704     // Handle aliased replace
1705     if (replaceAliased(i1, i2, s1, s2,
1706           std::integral_constant<bool,
1707             std::is_same<FwdIterator, iterator>::value ||
1708             std::is_same<FwdIterator, const_iterator>::value>())) {
1709       return;
1710     }
1711
1712     auto const n1 = i2 - i1;
1713     assert(n1 >= 0);
1714     auto const n2 = std::distance(s1, s2);
1715     assert(n2 >= 0);
1716
1717     if (n1 > n2) {
1718       // shrinks
1719       std::copy(s1, s2, i1);
1720       erase(i1 + n2, i2);
1721     } else {
1722       // grows
1723       fbstring_detail::copy_n(s1, n1, i1);
1724       std::advance(s1, n1);
1725       insert(i2, s1, s2);
1726     }
1727     assert(isSane());
1728   }
1729
1730   template <class InputIterator>
1731   void replaceImpl(iterator i1, iterator i2,
1732                    InputIterator b, InputIterator e, std::input_iterator_tag) {
1733     basic_fbstring temp(begin(), i1);
1734     temp.append(b, e).append(i2, end());
1735     swap(temp);
1736   }
1737
1738 public:
1739   template <class T1, class T2>
1740   basic_fbstring& replace(iterator i1, iterator i2,
1741                           T1 first_or_n_or_s, T2 last_or_c_or_n) {
1742     const bool
1743       num1 = std::numeric_limits<T1>::is_specialized,
1744       num2 = std::numeric_limits<T2>::is_specialized;
1745     return replaceImplDiscr(
1746       i1, i2, first_or_n_or_s, last_or_c_or_n,
1747       Selector<num1 ? (num2 ? 1 : -1) : (num2 ? 2 : 0)>());
1748   }
1749
1750   size_type copy(value_type* s, size_type n, size_type pos = 0) const {
1751     enforce(pos <= size(), std::__throw_out_of_range, "");
1752     procrustes(n, size() - pos);
1753
1754     fbstring_detail::pod_copy(
1755       data() + pos,
1756       data() + pos + n,
1757       s);
1758     return n;
1759   }
1760
1761   void swap(basic_fbstring& rhs) {
1762     store_.swap(rhs.store_);
1763   }
1764
1765   const value_type* c_str() const {
1766     return store_.c_str();
1767   }
1768
1769   const value_type* data() const { return c_str(); }
1770
1771   allocator_type get_allocator() const {
1772     return allocator_type();
1773   }
1774
1775   size_type find(const basic_fbstring& str, size_type pos = 0) const {
1776     return find(str.data(), pos, str.length());
1777   }
1778
1779   size_type find(const value_type* needle, const size_type pos,
1780                  const size_type nsize) const {
1781     if (!nsize) return pos;
1782     auto const size = this->size();
1783     // nsize + pos can overflow (eg pos == npos), guard against that by checking
1784     // that nsize + pos does not wrap around.
1785     if (nsize + pos > size || nsize + pos < pos) return npos;
1786     // Don't use std::search, use a Boyer-Moore-like trick by comparing
1787     // the last characters first
1788     auto const haystack = data();
1789     auto const nsize_1 = nsize - 1;
1790     auto const lastNeedle = needle[nsize_1];
1791
1792     // Boyer-Moore skip value for the last char in the needle. Zero is
1793     // not a valid value; skip will be computed the first time it's
1794     // needed.
1795     size_type skip = 0;
1796
1797     const E * i = haystack + pos;
1798     auto iEnd = haystack + size - nsize_1;
1799
1800     while (i < iEnd) {
1801       // Boyer-Moore: match the last element in the needle
1802       while (i[nsize_1] != lastNeedle) {
1803         if (++i == iEnd) {
1804           // not found
1805           return npos;
1806         }
1807       }
1808       // Here we know that the last char matches
1809       // Continue in pedestrian mode
1810       for (size_t j = 0; ; ) {
1811         assert(j < nsize);
1812         if (i[j] != needle[j]) {
1813           // Not found, we can skip
1814           // Compute the skip value lazily
1815           if (skip == 0) {
1816             skip = 1;
1817             while (skip <= nsize_1 && needle[nsize_1 - skip] != lastNeedle) {
1818               ++skip;
1819             }
1820           }
1821           i += skip;
1822           break;
1823         }
1824         // Check if done searching
1825         if (++j == nsize) {
1826           // Yay
1827           return i - haystack;
1828         }
1829       }
1830     }
1831     return npos;
1832   }
1833
1834   size_type find(const value_type* s, size_type pos = 0) const {
1835     return find(s, pos, traits_type::length(s));
1836   }
1837
1838   size_type find (value_type c, size_type pos = 0) const {
1839     return find(&c, pos, 1);
1840   }
1841
1842   size_type rfind(const basic_fbstring& str, size_type pos = npos) const {
1843     return rfind(str.data(), pos, str.length());
1844   }
1845
1846   size_type rfind(const value_type* s, size_type pos, size_type n) const {
1847     if (n > length()) return npos;
1848     pos = std::min(pos, length() - n);
1849     if (n == 0) return pos;
1850
1851     const_iterator i(begin() + pos);
1852     for (; ; --i) {
1853       if (traits_type::eq(*i, *s)
1854           && traits_type::compare(&*i, s, n) == 0) {
1855         return i - begin();
1856       }
1857       if (i == begin()) break;
1858     }
1859     return npos;
1860   }
1861
1862   size_type rfind(const value_type* s, size_type pos = npos) const {
1863     return rfind(s, pos, traits_type::length(s));
1864   }
1865
1866   size_type rfind(value_type c, size_type pos = npos) const {
1867     return rfind(&c, pos, 1);
1868   }
1869
1870   size_type find_first_of(const basic_fbstring& str, size_type pos = 0) const {
1871     return find_first_of(str.data(), pos, str.length());
1872   }
1873
1874   size_type find_first_of(const value_type* s,
1875                           size_type pos, size_type n) const {
1876     if (pos > length() || n == 0) return npos;
1877     const_iterator i(begin() + pos),
1878       finish(end());
1879     for (; i != finish; ++i) {
1880       if (traits_type::find(s, n, *i) != 0) {
1881         return i - begin();
1882       }
1883     }
1884     return npos;
1885   }
1886
1887   size_type find_first_of(const value_type* s, size_type pos = 0) const {
1888     return find_first_of(s, pos, traits_type::length(s));
1889   }
1890
1891   size_type find_first_of(value_type c, size_type pos = 0) const {
1892     return find_first_of(&c, pos, 1);
1893   }
1894
1895   size_type find_last_of (const basic_fbstring& str,
1896                           size_type pos = npos) const {
1897     return find_last_of(str.data(), pos, str.length());
1898   }
1899
1900   size_type find_last_of (const value_type* s, size_type pos,
1901                           size_type n) const {
1902     if (!empty() && n > 0) {
1903       pos = std::min(pos, length() - 1);
1904       const_iterator i(begin() + pos);
1905       for (;; --i) {
1906         if (traits_type::find(s, n, *i) != 0) {
1907           return i - begin();
1908         }
1909         if (i == begin()) break;
1910       }
1911     }
1912     return npos;
1913   }
1914
1915   size_type find_last_of (const value_type* s,
1916                           size_type pos = npos) const {
1917     return find_last_of(s, pos, traits_type::length(s));
1918   }
1919
1920   size_type find_last_of (value_type c, size_type pos = npos) const {
1921     return find_last_of(&c, pos, 1);
1922   }
1923
1924   size_type find_first_not_of(const basic_fbstring& str,
1925                               size_type pos = 0) const {
1926     return find_first_not_of(str.data(), pos, str.size());
1927   }
1928
1929   size_type find_first_not_of(const value_type* s, size_type pos,
1930                               size_type n) const {
1931     if (pos < length()) {
1932       const_iterator
1933         i(begin() + pos),
1934         finish(end());
1935       for (; i != finish; ++i) {
1936         if (traits_type::find(s, n, *i) == 0) {
1937           return i - begin();
1938         }
1939       }
1940     }
1941     return npos;
1942   }
1943
1944   size_type find_first_not_of(const value_type* s,
1945                               size_type pos = 0) const {
1946     return find_first_not_of(s, pos, traits_type::length(s));
1947   }
1948
1949   size_type find_first_not_of(value_type c, size_type pos = 0) const {
1950     return find_first_not_of(&c, pos, 1);
1951   }
1952
1953   size_type find_last_not_of(const basic_fbstring& str,
1954                              size_type pos = npos) const {
1955     return find_last_not_of(str.data(), pos, str.length());
1956   }
1957
1958   size_type find_last_not_of(const value_type* s, size_type pos,
1959                              size_type n) const {
1960     if (!this->empty()) {
1961       pos = std::min(pos, size() - 1);
1962       const_iterator i(begin() + pos);
1963       for (;; --i) {
1964         if (traits_type::find(s, n, *i) == 0) {
1965           return i - begin();
1966         }
1967         if (i == begin()) break;
1968       }
1969     }
1970     return npos;
1971   }
1972
1973   size_type find_last_not_of(const value_type* s,
1974                              size_type pos = npos) const {
1975     return find_last_not_of(s, pos, traits_type::length(s));
1976   }
1977
1978   size_type find_last_not_of (value_type c, size_type pos = npos) const {
1979     return find_last_not_of(&c, pos, 1);
1980   }
1981
1982   basic_fbstring substr(size_type pos = 0, size_type n = npos) const& {
1983     enforce(pos <= size(), std::__throw_out_of_range, "");
1984     return basic_fbstring(data() + pos, std::min(n, size() - pos));
1985   }
1986
1987   basic_fbstring substr(size_type pos = 0, size_type n = npos) && {
1988     enforce(pos <= size(), std::__throw_out_of_range, "");
1989     erase(0, pos);
1990     if (n < size()) resize(n);
1991     return std::move(*this);
1992   }
1993
1994   int compare(const basic_fbstring& str) const {
1995     // FIX due to Goncalo N M de Carvalho July 18, 2005
1996     return compare(0, size(), str);
1997   }
1998
1999   int compare(size_type pos1, size_type n1,
2000               const basic_fbstring& str) const {
2001     return compare(pos1, n1, str.data(), str.size());
2002   }
2003
2004   int compare(size_type pos1, size_type n1,
2005               const value_type* s) const {
2006     return compare(pos1, n1, s, traits_type::length(s));
2007   }
2008
2009   int compare(size_type pos1, size_type n1,
2010               const value_type* s, size_type n2) const {
2011     enforce(pos1 <= size(), std::__throw_out_of_range, "");
2012     procrustes(n1, size() - pos1);
2013     // The line below fixed by Jean-Francois Bastien, 04-23-2007. Thanks!
2014     const int r = traits_type::compare(pos1 + data(), s, std::min(n1, n2));
2015     return r != 0 ? r : n1 > n2 ? 1 : n1 < n2 ? -1 : 0;
2016   }
2017
2018   int compare(size_type pos1, size_type n1,
2019               const basic_fbstring& str,
2020               size_type pos2, size_type n2) const {
2021     enforce(pos2 <= str.size(), std::__throw_out_of_range, "");
2022     return compare(pos1, n1, str.data() + pos2,
2023                    std::min(n2, str.size() - pos2));
2024   }
2025
2026   // Code from Jean-Francois Bastien (03/26/2007)
2027   int compare(const value_type* s) const {
2028     // Could forward to compare(0, size(), s, traits_type::length(s))
2029     // but that does two extra checks
2030     const size_type n1(size()), n2(traits_type::length(s));
2031     const int r = traits_type::compare(data(), s, std::min(n1, n2));
2032     return r != 0 ? r : n1 > n2 ? 1 : n1 < n2 ? -1 : 0;
2033   }
2034
2035 private:
2036   // Data
2037   Storage store_;
2038 };
2039
2040 // non-member functions
2041 // C++11 21.4.8.1/1
2042 template <typename E, class T, class A, class S>
2043 inline
2044 basic_fbstring<E, T, A, S> operator+(const basic_fbstring<E, T, A, S>& lhs,
2045                                      const basic_fbstring<E, T, A, S>& rhs) {
2046
2047   basic_fbstring<E, T, A, S> result;
2048   result.reserve(lhs.size() + rhs.size());
2049   result.append(lhs).append(rhs);
2050   return std::move(result);
2051 }
2052
2053 // C++11 21.4.8.1/2
2054 template <typename E, class T, class A, class S>
2055 inline
2056 basic_fbstring<E, T, A, S> operator+(basic_fbstring<E, T, A, S>&& lhs,
2057                                      const basic_fbstring<E, T, A, S>& rhs) {
2058   return std::move(lhs.append(rhs));
2059 }
2060
2061 // C++11 21.4.8.1/3
2062 template <typename E, class T, class A, class S>
2063 inline
2064 basic_fbstring<E, T, A, S> operator+(const basic_fbstring<E, T, A, S>& lhs,
2065                                      basic_fbstring<E, T, A, S>&& rhs) {
2066   if (rhs.capacity() >= lhs.size() + rhs.size()) {
2067     // Good, at least we don't need to reallocate
2068     return std::move(rhs.insert(0, lhs));
2069   }
2070   // Meh, no go. Forward to operator+(const&, const&).
2071   auto const& rhsC = rhs;
2072   return lhs + rhsC;
2073 }
2074
2075 // C++11 21.4.8.1/4
2076 template <typename E, class T, class A, class S>
2077 inline
2078 basic_fbstring<E, T, A, S> operator+(basic_fbstring<E, T, A, S>&& lhs,
2079                                      basic_fbstring<E, T, A, S>&& rhs) {
2080   return std::move(lhs.append(rhs));
2081 }
2082
2083 // C++11 21.4.8.1/5
2084 template <typename E, class T, class A, class S>
2085 inline
2086 basic_fbstring<E, T, A, S> operator+(
2087   const E* lhs,
2088   const basic_fbstring<E, T, A, S>& rhs) {
2089   //
2090   basic_fbstring<E, T, A, S> result;
2091   const auto len = basic_fbstring<E, T, A, S>::traits_type::length(lhs);
2092   result.reserve(len + rhs.size());
2093   result.append(lhs, len).append(rhs);
2094   return result;
2095 }
2096
2097 // C++11 21.4.8.1/6
2098 template <typename E, class T, class A, class S>
2099 inline
2100 basic_fbstring<E, T, A, S> operator+(
2101   const E* lhs,
2102   basic_fbstring<E, T, A, S>&& rhs) {
2103   //
2104   const auto len = basic_fbstring<E, T, A, S>::traits_type::length(lhs);
2105   if (rhs.capacity() >= len + rhs.size()) {
2106     // Good, at least we don't need to reallocate
2107     rhs.insert(rhs.begin(), lhs, lhs + len);
2108     return rhs;
2109   }
2110   // Meh, no go. Do it by hand since we have len already.
2111   basic_fbstring<E, T, A, S> result;
2112   result.reserve(len + rhs.size());
2113   result.append(lhs, len).append(rhs);
2114   return result;
2115 }
2116
2117 // C++11 21.4.8.1/7
2118 template <typename E, class T, class A, class S>
2119 inline
2120 basic_fbstring<E, T, A, S> operator+(
2121   E lhs,
2122   const basic_fbstring<E, T, A, S>& rhs) {
2123
2124   basic_fbstring<E, T, A, S> result;
2125   result.reserve(1 + rhs.size());
2126   result.push_back(lhs);
2127   result.append(rhs);
2128   return result;
2129 }
2130
2131 // C++11 21.4.8.1/8
2132 template <typename E, class T, class A, class S>
2133 inline
2134 basic_fbstring<E, T, A, S> operator+(
2135   E lhs,
2136   basic_fbstring<E, T, A, S>&& rhs) {
2137   //
2138   if (rhs.capacity() > rhs.size()) {
2139     // Good, at least we don't need to reallocate
2140     rhs.insert(rhs.begin(), lhs);
2141     return rhs;
2142   }
2143   // Meh, no go. Forward to operator+(E, const&).
2144   auto const& rhsC = rhs;
2145   return lhs + rhsC;
2146 }
2147
2148 // C++11 21.4.8.1/9
2149 template <typename E, class T, class A, class S>
2150 inline
2151 basic_fbstring<E, T, A, S> operator+(
2152   const basic_fbstring<E, T, A, S>& lhs,
2153   const E* rhs) {
2154
2155   typedef typename basic_fbstring<E, T, A, S>::size_type size_type;
2156   typedef typename basic_fbstring<E, T, A, S>::traits_type traits_type;
2157
2158   basic_fbstring<E, T, A, S> result;
2159   const size_type len = traits_type::length(rhs);
2160   result.reserve(lhs.size() + len);
2161   result.append(lhs).append(rhs, len);
2162   return result;
2163 }
2164
2165 // C++11 21.4.8.1/10
2166 template <typename E, class T, class A, class S>
2167 inline
2168 basic_fbstring<E, T, A, S> operator+(
2169   basic_fbstring<E, T, A, S>&& lhs,
2170   const E* rhs) {
2171   //
2172   return std::move(lhs += rhs);
2173 }
2174
2175 // C++11 21.4.8.1/11
2176 template <typename E, class T, class A, class S>
2177 inline
2178 basic_fbstring<E, T, A, S> operator+(
2179   const basic_fbstring<E, T, A, S>& lhs,
2180   E rhs) {
2181
2182   basic_fbstring<E, T, A, S> result;
2183   result.reserve(lhs.size() + 1);
2184   result.append(lhs);
2185   result.push_back(rhs);
2186   return result;
2187 }
2188
2189 // C++11 21.4.8.1/12
2190 template <typename E, class T, class A, class S>
2191 inline
2192 basic_fbstring<E, T, A, S> operator+(
2193   basic_fbstring<E, T, A, S>&& lhs,
2194   E rhs) {
2195   //
2196   return std::move(lhs += rhs);
2197 }
2198
2199 template <typename E, class T, class A, class S>
2200 inline
2201 bool operator==(const basic_fbstring<E, T, A, S>& lhs,
2202                 const basic_fbstring<E, T, A, S>& rhs) {
2203   return lhs.size() == rhs.size() && lhs.compare(rhs) == 0; }
2204
2205 template <typename E, class T, class A, class S>
2206 inline
2207 bool operator==(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2208                 const basic_fbstring<E, T, A, S>& rhs) {
2209   return rhs == lhs; }
2210
2211 template <typename E, class T, class A, class S>
2212 inline
2213 bool operator==(const basic_fbstring<E, T, A, S>& lhs,
2214                 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2215   return lhs.compare(rhs) == 0; }
2216
2217 template <typename E, class T, class A, class S>
2218 inline
2219 bool operator!=(const basic_fbstring<E, T, A, S>& lhs,
2220                 const basic_fbstring<E, T, A, S>& rhs) {
2221   return !(lhs == rhs); }
2222
2223 template <typename E, class T, class A, class S>
2224 inline
2225 bool operator!=(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2226                 const basic_fbstring<E, T, A, S>& rhs) {
2227   return !(lhs == rhs); }
2228
2229 template <typename E, class T, class A, class S>
2230 inline
2231 bool operator!=(const basic_fbstring<E, T, A, S>& lhs,
2232                 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2233   return !(lhs == rhs); }
2234
2235 template <typename E, class T, class A, class S>
2236 inline
2237 bool operator<(const basic_fbstring<E, T, A, S>& lhs,
2238                const basic_fbstring<E, T, A, S>& rhs) {
2239   return lhs.compare(rhs) < 0; }
2240
2241 template <typename E, class T, class A, class S>
2242 inline
2243 bool operator<(const basic_fbstring<E, T, A, S>& lhs,
2244                const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2245   return lhs.compare(rhs) < 0; }
2246
2247 template <typename E, class T, class A, class S>
2248 inline
2249 bool operator<(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2250                const basic_fbstring<E, T, A, S>& rhs) {
2251   return rhs.compare(lhs) > 0; }
2252
2253 template <typename E, class T, class A, class S>
2254 inline
2255 bool operator>(const basic_fbstring<E, T, A, S>& lhs,
2256                const basic_fbstring<E, T, A, S>& rhs) {
2257   return rhs < lhs; }
2258
2259 template <typename E, class T, class A, class S>
2260 inline
2261 bool operator>(const basic_fbstring<E, T, A, S>& lhs,
2262                const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2263   return rhs < lhs; }
2264
2265 template <typename E, class T, class A, class S>
2266 inline
2267 bool operator>(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2268                const basic_fbstring<E, T, A, S>& rhs) {
2269   return rhs < lhs; }
2270
2271 template <typename E, class T, class A, class S>
2272 inline
2273 bool operator<=(const basic_fbstring<E, T, A, S>& lhs,
2274                 const basic_fbstring<E, T, A, S>& rhs) {
2275   return !(rhs < lhs); }
2276
2277 template <typename E, class T, class A, class S>
2278 inline
2279 bool operator<=(const basic_fbstring<E, T, A, S>& lhs,
2280                 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2281   return !(rhs < lhs); }
2282
2283 template <typename E, class T, class A, class S>
2284 inline
2285 bool operator<=(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2286                 const basic_fbstring<E, T, A, S>& rhs) {
2287   return !(rhs < lhs); }
2288
2289 template <typename E, class T, class A, class S>
2290 inline
2291 bool operator>=(const basic_fbstring<E, T, A, S>& lhs,
2292                 const basic_fbstring<E, T, A, S>& rhs) {
2293   return !(lhs < rhs); }
2294
2295 template <typename E, class T, class A, class S>
2296 inline
2297 bool operator>=(const basic_fbstring<E, T, A, S>& lhs,
2298                 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2299   return !(lhs < rhs); }
2300
2301 template <typename E, class T, class A, class S>
2302 inline
2303 bool operator>=(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2304                 const basic_fbstring<E, T, A, S>& rhs) {
2305  return !(lhs < rhs);
2306 }
2307
2308 // C++11 21.4.8.8
2309 template <typename E, class T, class A, class S>
2310 void swap(basic_fbstring<E, T, A, S>& lhs, basic_fbstring<E, T, A, S>& rhs) {
2311   lhs.swap(rhs);
2312 }
2313
2314 // TODO: make this faster.
2315 template <typename E, class T, class A, class S>
2316 inline
2317 std::basic_istream<
2318   typename basic_fbstring<E, T, A, S>::value_type,
2319   typename basic_fbstring<E, T, A, S>::traits_type>&
2320   operator>>(
2321     std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2322     typename basic_fbstring<E, T, A, S>::traits_type>& is,
2323     basic_fbstring<E, T, A, S>& str) {
2324   typename std::basic_istream<E, T>::sentry sentry(is);
2325   typedef std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2326                              typename basic_fbstring<E, T, A, S>::traits_type>
2327                         __istream_type;
2328   typedef typename __istream_type::ios_base __ios_base;
2329   size_t extracted = 0;
2330   auto err = __ios_base::goodbit;
2331   if (sentry) {
2332     auto n = is.width();
2333     if (n <= 0) {
2334       n = str.max_size();
2335     }
2336     str.erase();
2337     for (auto got = is.rdbuf()->sgetc(); extracted != size_t(n); ++extracted) {
2338       if (got == T::eof()) {
2339         err |= __ios_base::eofbit;
2340         is.width(0);
2341         break;
2342       }
2343       if (isspace(got)) break;
2344       str.push_back(got);
2345       got = is.rdbuf()->snextc();
2346     }
2347   }
2348   if (!extracted) {
2349     err |= __ios_base::failbit;
2350   }
2351   if (err) {
2352     is.setstate(err);
2353   }
2354   return is;
2355 }
2356
2357 template <typename E, class T, class A, class S>
2358 inline
2359 std::basic_ostream<typename basic_fbstring<E, T, A, S>::value_type,
2360                    typename basic_fbstring<E, T, A, S>::traits_type>&
2361 operator<<(
2362   std::basic_ostream<typename basic_fbstring<E, T, A, S>::value_type,
2363   typename basic_fbstring<E, T, A, S>::traits_type>& os,
2364     const basic_fbstring<E, T, A, S>& str) {
2365 #if _LIBCPP_VERSION
2366   typename std::basic_ostream<
2367     typename basic_fbstring<E, T, A, S>::value_type,
2368     typename basic_fbstring<E, T, A, S>::traits_type>::sentry __s(os);
2369   if (__s) {
2370     typedef std::ostreambuf_iterator<
2371       typename basic_fbstring<E, T, A, S>::value_type,
2372       typename basic_fbstring<E, T, A, S>::traits_type> _Ip;
2373     size_t __len = str.size();
2374     bool __left =
2375       (os.flags() & std::ios_base::adjustfield) == std::ios_base::left;
2376     if (__pad_and_output(_Ip(os),
2377                          str.data(),
2378                          __left ? str.data() + __len : str.data(),
2379                          str.data() + __len,
2380                          os,
2381                          os.fill()).failed()) {
2382       os.setstate(std::ios_base::badbit | std::ios_base::failbit);
2383     }
2384   }
2385 #elif defined(_MSC_VER)
2386   // MSVC doesn't define __ostream_insert
2387   os.write(str.data(), str.size());
2388 #else
2389   std::__ostream_insert(os, str.data(), str.size());
2390 #endif
2391   return os;
2392 }
2393
2394 template <typename E1, class T, class A, class S>
2395 const typename basic_fbstring<E1, T, A, S>::size_type
2396 basic_fbstring<E1, T, A, S>::npos =
2397               static_cast<typename basic_fbstring<E1, T, A, S>::size_type>(-1);
2398
2399 #ifndef _LIBSTDCXX_FBSTRING
2400 // basic_string compatibility routines
2401
2402 template <typename E, class T, class A, class S>
2403 inline
2404 bool operator==(const basic_fbstring<E, T, A, S>& lhs,
2405                 const std::string& rhs) {
2406   return lhs.compare(0, lhs.size(), rhs.data(), rhs.size()) == 0;
2407 }
2408
2409 template <typename E, class T, class A, class S>
2410 inline
2411 bool operator==(const std::string& lhs,
2412                 const basic_fbstring<E, T, A, S>& rhs) {
2413   return rhs == lhs;
2414 }
2415
2416 template <typename E, class T, class A, class S>
2417 inline
2418 bool operator!=(const basic_fbstring<E, T, A, S>& lhs,
2419                 const std::string& rhs) {
2420   return !(lhs == rhs);
2421 }
2422
2423 template <typename E, class T, class A, class S>
2424 inline
2425 bool operator!=(const std::string& lhs,
2426                 const basic_fbstring<E, T, A, S>& rhs) {
2427   return !(lhs == rhs);
2428 }
2429
2430 #if !defined(_LIBSTDCXX_FBSTRING)
2431 typedef basic_fbstring<char> fbstring;
2432 #endif
2433
2434 // fbstring is relocatable
2435 template <class T, class R, class A, class S>
2436 FOLLY_ASSUME_RELOCATABLE(basic_fbstring<T, R, A, S>);
2437
2438 #else
2439 _GLIBCXX_END_NAMESPACE_VERSION
2440 #endif
2441
2442 } // namespace folly
2443
2444 #ifndef _LIBSTDCXX_FBSTRING
2445
2446 // Hash functions to make fbstring usable with e.g. hash_map
2447 //
2448 // Handle interaction with different C++ standard libraries, which
2449 // expect these types to be in different namespaces.
2450
2451 #define FOLLY_FBSTRING_HASH1(T) \
2452   template <> \
2453   struct hash< ::folly::basic_fbstring<T> > { \
2454     size_t operator()(const ::folly::fbstring& s) const { \
2455       return ::folly::hash::fnv32_buf(s.data(), s.size()); \
2456     } \
2457   };
2458
2459 // The C++11 standard says that these four are defined
2460 #define FOLLY_FBSTRING_HASH \
2461   FOLLY_FBSTRING_HASH1(char) \
2462   FOLLY_FBSTRING_HASH1(char16_t) \
2463   FOLLY_FBSTRING_HASH1(char32_t) \
2464   FOLLY_FBSTRING_HASH1(wchar_t)
2465
2466 namespace std {
2467
2468 FOLLY_FBSTRING_HASH
2469
2470 }  // namespace std
2471
2472 #if FOLLY_HAVE_DEPRECATED_ASSOC
2473 #if defined(_GLIBCXX_SYMVER) && !defined(__BIONIC__)
2474 namespace __gnu_cxx {
2475
2476 FOLLY_FBSTRING_HASH
2477
2478 }  // namespace __gnu_cxx
2479 #endif // _GLIBCXX_SYMVER && !__BIONIC__
2480 #endif // FOLLY_HAVE_DEPRECATED_ASSOC
2481
2482 #undef FOLLY_FBSTRING_HASH
2483 #undef FOLLY_FBSTRING_HASH1
2484
2485 #endif // _LIBSTDCXX_FBSTRING
2486
2487 #pragma GCC diagnostic pop
2488
2489 #undef FBSTRING_DISABLE_SMALL_STRING_OPTIMIZATION
2490 #undef FBSTRING_SANITIZE_ADDRESS
2491 #undef throw
2492 #undef FBSTRING_LIKELY
2493 #undef FBSTRING_UNLIKELY
2494
2495 #ifdef FOLLY_DEFINED_NDEBUG_FOR_FBSTRING
2496 #undef NDEBUG
2497 #undef FOLLY_DEFINED_NDEBUG_FOR_FBSTRING
2498 #endif // FOLLY_DEFINED_NDEBUG_FOR_FBSTRING
2499
2500 #endif // FOLLY_BASE_FBSTRING_H_