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