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