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