Drop support for GCC < 4.8 in folly/FBString.h
[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  * This is the core of the string. The code should work on 32- and
260  * 64-bit and both big- and little-endianan architectures with any
261  * Char size.
262  *
263  * The storage is selected as follows (assuming we store one-byte
264  * characters on a 64-bit machine): (a) "small" strings between 0 and
265  * 23 chars are stored in-situ without allocation (the rightmost byte
266  * stores the size); (b) "medium" strings from 24 through 254 chars
267  * are stored in malloc-allocated memory that is copied eagerly; (c)
268  * "large" strings of 255 chars and above are stored in a similar
269  * structure as medium arrays, except that the string is
270  * reference-counted and copied lazily. the reference count is
271  * allocated right before the character array.
272  *
273  * The discriminator between these three strategies sits in two
274  * bits of the rightmost char of the storage. If neither is set, then the
275  * string is small (and its length sits in the lower-order bits on
276  * little-endian or the high-order bits on big-endian of that
277  * rightmost character). If the MSb is set, the string is medium width.
278  * If the second MSb is set, then the string is large. On little-endian,
279  * these 2 bits are the 2 MSbs of MediumLarge::capacity_, while on
280  * big-endian, these 2 bits are the 2 LSbs. This keeps both little-endian
281  * and big-endian fbstring_core equivalent with merely different ops used
282  * to extract capacity/category.
283  */
284 template <class Char> class fbstring_core {
285 public:
286   fbstring_core() noexcept {
287     // Only initialize the tag, will set the MSBs (i.e. the small
288     // string size) to zero too
289 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
290     ml_.capacity_ = maxSmallSize << (8 * (sizeof(size_t) - sizeof(Char)));
291 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
292     ml_.capacity_ = maxSmallSize << 2;
293 #else
294 #error Unable to identify target endianness
295 #endif
296     // or: setSmallSize(0);
297     writeTerminator();
298     assert(category() == Category::isSmall && size() == 0);
299   }
300
301   fbstring_core(const fbstring_core & rhs) {
302     assert(&rhs != this);
303     // Simplest case first: small strings are bitblitted
304     if (rhs.category() == Category::isSmall) {
305       static_assert(offsetof(MediumLarge, data_) == 0,
306           "fbstring layout failure");
307       static_assert(offsetof(MediumLarge, size_) == sizeof(ml_.data_),
308           "fbstring layout failure");
309       static_assert(offsetof(MediumLarge, capacity_) == 2 * sizeof(ml_.data_),
310           "fbstring layout failure");
311       const size_t size = rhs.smallSize();
312       if (size == 0) {
313         ml_.capacity_ = rhs.ml_.capacity_;
314         writeTerminator();
315       } else {
316         // Just write the whole thing, don't look at details. In
317         // particular we need to copy capacity anyway because we want
318         // to set the size (don't forget that the last character,
319         // which stores a short string's length, is shared with the
320         // ml_.capacity field).
321         ml_ = rhs.ml_;
322       }
323       assert(category() == Category::isSmall && this->size() == rhs.size());
324     } else if (rhs.category() == Category::isLarge) {
325       // Large strings are just refcounted
326       ml_ = rhs.ml_;
327       RefCounted::incrementRefs(ml_.data_);
328       assert(category() == Category::isLarge && size() == rhs.size());
329     } else {
330       // Medium strings are copied eagerly. Don't forget to allocate
331       // one extra Char for the null terminator.
332       auto const allocSize =
333            goodMallocSize((1 + rhs.ml_.size_) * sizeof(Char));
334       ml_.data_ = static_cast<Char*>(checkedMalloc(allocSize));
335       fbstring_detail::pod_copy(rhs.ml_.data_,
336                                 // 1 for terminator
337                                 rhs.ml_.data_ + rhs.ml_.size_ + 1,
338                                 ml_.data_);
339       // No need for writeTerminator() here, we copied one extra
340       // element just above.
341       ml_.size_ = rhs.ml_.size_;
342       ml_.setCapacity(allocSize / sizeof(Char) - 1, Category::isMedium);
343       assert(category() == Category::isMedium);
344     }
345     assert(size() == rhs.size());
346     assert(memcmp(data(), rhs.data(), size() * sizeof(Char)) == 0);
347   }
348
349   fbstring_core(fbstring_core&& goner) noexcept {
350     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_.setCapacity(allocSize / sizeof(Char) - 1, Category::isMedium);
418     } else {
419       // Large strings are allocated differently
420       size_t effectiveCapacity = size;
421       auto const newRC = RefCounted::create(data, & effectiveCapacity);
422       ml_.data_ = newRC->data_;
423       ml_.size_ = size;
424       ml_.setCapacity(effectiveCapacity, Category::isLarge);
425     }
426     writeTerminator();
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       setSmallSize(0);
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       fbstring_detail::pod_copy(ml_.data_, ml_.data_ + ml_.size_ + 1,
496                                 newRC->data_);
497       RefCounted::decrementRefs(ml_.data_);
498       ml_.data_ = newRC->data_;
499       // No need to call writeTerminator(), we have + 1 above.
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       writeTerminator();
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) {
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         fbstring_detail::pod_copy(ml_.data_, ml_.data_ + ml_.size_ + 1,
551                                    newRC->data_);
552         // Done with the old data. No need to call writeTerminator(),
553         // we have + 1 above.
554         RefCounted::decrementRefs(ml_.data_);
555         ml_.data_ = newRC->data_;
556         ml_.setCapacity(minCapacity, Category::isLarge);
557         // size remains unchanged
558       } else {
559         // String is not shared, so let's try to realloc (if needed)
560         if (minCapacity > ml_.capacity()) {
561           // Asking for more memory
562           auto const newRC =
563                RefCounted::reallocate(ml_.data_, ml_.size_,
564                                       ml_.capacity(), minCapacity);
565           ml_.data_ = newRC->data_;
566           ml_.setCapacity(minCapacity, Category::isLarge);
567           writeTerminator();
568         }
569         assert(capacity() >= minCapacity);
570       }
571     } else if (category() == Category::isMedium) {
572       // String is not shared
573       if (minCapacity <= ml_.capacity()) {
574         return; // nothing to do, there's enough room
575       }
576       if (minCapacity <= maxMediumSize) {
577         // Keep the string at medium size. Don't forget to allocate
578         // one extra Char for the terminating null.
579         size_t capacityBytes = goodMallocSize((1 + minCapacity) * sizeof(Char));
580         ml_.data_ = static_cast<Char *>(
581           smartRealloc(
582             ml_.data_,
583             ml_.size_ * sizeof(Char),
584             (ml_.capacity() + 1) * sizeof(Char),
585             capacityBytes));
586         writeTerminator();
587         ml_.setCapacity(capacityBytes / sizeof(Char) - 1, Category::isMedium);
588       } else {
589         // Conversion from medium to large string
590         fbstring_core nascent;
591         // Will recurse to another branch of this function
592         nascent.reserve(minCapacity);
593         nascent.ml_.size_ = ml_.size_;
594         fbstring_detail::pod_copy(ml_.data_, ml_.data_ + ml_.size_,
595                                   nascent.ml_.data_);
596         nascent.swap(*this);
597         writeTerminator();
598         assert(capacity() >= minCapacity);
599       }
600     } else {
601       assert(category() == Category::isSmall);
602       if (minCapacity > maxMediumSize) {
603         // large
604         auto const newRC = RefCounted::create(& minCapacity);
605         auto const size = smallSize();
606         fbstring_detail::pod_copy(small_, small_ + size + 1, newRC->data_);
607         // No need for writeTerminator(), we wrote it above with + 1.
608         ml_.data_ = newRC->data_;
609         ml_.size_ = size;
610         ml_.setCapacity(minCapacity, Category::isLarge);
611         assert(capacity() >= minCapacity);
612       } else if (minCapacity > maxSmallSize) {
613         // medium
614         // Don't forget to allocate one extra Char for the terminating null
615         auto const allocSizeBytes =
616           goodMallocSize((1 + minCapacity) * sizeof(Char));
617         auto const data = static_cast<Char*>(checkedMalloc(allocSizeBytes));
618         auto const size = smallSize();
619         fbstring_detail::pod_copy(small_, small_ + size + 1, data);
620         // No need for writeTerminator(), we wrote it above with + 1.
621         ml_.data_ = data;
622         ml_.size_ = size;
623         ml_.setCapacity(allocSizeBytes / sizeof(Char) - 1, Category::isMedium);
624       } else {
625         // small
626         // Nothing to do, everything stays put
627       }
628     }
629     assert(capacity() >= minCapacity);
630   }
631
632   Char * expand_noinit(const size_t delta) {
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 (newSz <= maxSmallSize) {
640         setSmallSize(newSz);
641         return small_ + sz;
642       }
643       reserve(newSz);
644     } else {
645       sz = ml_.size_;
646       newSz = ml_.size_ + delta;
647       if (newSz > capacity()) {
648         reserve(newSz);
649       }
650     }
651     assert(capacity() >= newSz);
652     // Category can't be small - we took care of that above
653     assert(category() == Category::isMedium || category() == Category::isLarge);
654     ml_.size_ = newSz;
655     writeTerminator();
656     assert(size() == newSz);
657     return ml_.data_ + sz;
658   }
659
660   void push_back(Char c) {
661     assert(capacity() >= size());
662     size_t sz;
663     if (category() == Category::isSmall) {
664       sz = smallSize();
665       if (sz < maxSmallSize) {
666         small_[sz] = c;
667         setSmallSize(sz + 1);
668         return;
669       }
670       reserve(maxSmallSize * 2);
671     } else {
672       sz = ml_.size_;
673       if (sz == capacity()) {  // always true for isShared()
674         reserve(1 + sz * 3 / 2);  // ensures not shared
675       }
676     }
677     assert(!isShared());
678     assert(capacity() >= sz + 1);
679     // Category can't be small - we took care of that above
680     assert(category() == Category::isMedium || category() == Category::isLarge);
681     ml_.size_ = sz + 1;
682     ml_.data_[sz] = c;
683     writeTerminator();
684   }
685
686   size_t size() const {
687     return category() == Category::isSmall ? smallSize() : ml_.size_;
688   }
689
690   size_t capacity() const {
691     switch (category()) {
692       case Category::isSmall:
693         return maxSmallSize;
694       case Category::isLarge:
695         // For large-sized strings, a multi-referenced chunk has no
696         // available capacity. This is because any attempt to append
697         // data would trigger a new allocation.
698         if (RefCounted::refs(ml_.data_) > 1) return ml_.size_;
699       default: {}
700     }
701     return ml_.capacity();
702   }
703
704   bool isShared() const {
705     return category() == Category::isLarge && RefCounted::refs(ml_.data_) > 1;
706   }
707
708   void writeTerminator() {
709     if (category() == Category::isSmall) {
710       const auto s = smallSize();
711       if (s != maxSmallSize) {
712         small_[s] = '\0';
713       }
714     } else {
715       ml_.data_[ml_.size_] = '\0';
716     }
717   }
718
719 private:
720   // Disabled
721   fbstring_core & operator=(const fbstring_core & rhs);
722
723   struct RefCounted {
724     std::atomic<size_t> refCount_;
725     Char data_[1];
726
727     static RefCounted * fromData(Char * p) {
728       return static_cast<RefCounted*>(
729         static_cast<void*>(
730           static_cast<unsigned char*>(static_cast<void*>(p))
731           - sizeof(refCount_)));
732     }
733
734     static size_t refs(Char * p) {
735       return fromData(p)->refCount_.load(std::memory_order_acquire);
736     }
737
738     static void incrementRefs(Char * p) {
739       fromData(p)->refCount_.fetch_add(1, std::memory_order_acq_rel);
740     }
741
742     static void decrementRefs(Char * p) {
743       auto const dis = fromData(p);
744       size_t oldcnt = dis->refCount_.fetch_sub(1, std::memory_order_acq_rel);
745       assert(oldcnt > 0);
746       if (oldcnt == 1) {
747         free(dis);
748       }
749     }
750
751     static RefCounted * create(size_t * size) {
752       // Don't forget to allocate one extra Char for the terminating
753       // null. In this case, however, one Char is already part of the
754       // struct.
755       const size_t allocSize = goodMallocSize(
756         sizeof(RefCounted) + *size * sizeof(Char));
757       auto result = static_cast<RefCounted*>(checkedMalloc(allocSize));
758       result->refCount_.store(1, std::memory_order_release);
759       *size = (allocSize - sizeof(RefCounted)) / sizeof(Char);
760       return result;
761     }
762
763     static RefCounted * create(const Char * data, size_t * size) {
764       const size_t effectiveSize = *size;
765       auto result = create(size);
766       fbstring_detail::pod_copy(data, data + effectiveSize, result->data_);
767       return result;
768     }
769
770     static RefCounted * reallocate(Char *const data,
771                                    const size_t currentSize,
772                                    const size_t currentCapacity,
773                                    const size_t newCapacity) {
774       assert(newCapacity > 0 && newCapacity > currentSize);
775       auto const dis = fromData(data);
776       assert(dis->refCount_.load(std::memory_order_acquire) == 1);
777       // Don't forget to allocate one extra Char for the terminating
778       // null. In this case, however, one Char is already part of the
779       // struct.
780       auto result = static_cast<RefCounted*>(
781              smartRealloc(dis,
782                           sizeof(RefCounted) + currentSize * sizeof(Char),
783                           sizeof(RefCounted) + currentCapacity * sizeof(Char),
784                           sizeof(RefCounted) + newCapacity * sizeof(Char)));
785       assert(result->refCount_.load(std::memory_order_acquire) == 1);
786       return result;
787     }
788   };
789
790   typedef std::conditional<sizeof(size_t) == 4, uint32_t, uint64_t>::type
791           category_type;
792
793   enum class Category : category_type {
794     isSmall = 0,
795 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
796     isMedium = sizeof(size_t) == 4 ? 0x80000000 : 0x8000000000000000,
797     isLarge =  sizeof(size_t) == 4 ? 0x40000000 : 0x4000000000000000,
798 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
799     isMedium = 0x2,
800     isLarge =  0x1,
801 #else
802 #error Unable to identify target endianness
803 #endif
804   };
805
806   Category category() const {
807     // works for both big-endian and little-endian
808     return static_cast<Category>(ml_.capacity_ & categoryExtractMask);
809   }
810
811   struct MediumLarge {
812     Char * data_;
813     size_t size_;
814     size_t capacity_;
815
816     size_t capacity() const {
817 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
818       return capacity_ & capacityExtractMask;
819 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
820       return capacity_ >> 2;
821 #else
822 #error Unable to identify target endianness
823 #endif
824     }
825
826     void setCapacity(size_t cap, Category cat) {
827 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
828         capacity_ = cap | static_cast<category_type>(cat);
829 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
830         capacity_ = (cap << 2) | static_cast<category_type>(cat);
831 #else
832 #error Unable to identify target endianness
833 #endif
834     }
835   };
836
837   union {
838     Char small_[sizeof(MediumLarge) / sizeof(Char)];
839     MediumLarge ml_;
840   };
841
842   enum : size_t {
843     lastChar = sizeof(MediumLarge) - 1,
844     maxSmallSize = lastChar / sizeof(Char),
845     maxMediumSize = 254 / sizeof(Char),            // coincides with the small
846                                                    // bin size in dlmalloc
847 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
848     categoryExtractMask = sizeof(size_t) == 4 ? 0xC0000000 : 0xC000000000000000,
849     capacityExtractMask = ~categoryExtractMask,
850 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
851     categoryExtractMask = 0x3,
852 #else
853 #error Unable to identify target endianness
854 #endif
855   };
856   static_assert(!(sizeof(MediumLarge) % sizeof(Char)),
857                 "Corrupt memory layout for fbstring.");
858
859   size_t smallSize() const {
860 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
861     assert(category() == Category::isSmall &&
862            static_cast<size_t>(small_[maxSmallSize])
863            <= static_cast<size_t>(maxSmallSize));
864     return static_cast<size_t>(maxSmallSize)
865       - static_cast<size_t>(small_[maxSmallSize]);
866 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
867     assert(category() == Category::isSmall &&
868            (static_cast<size_t>(small_[maxSmallSize]) >> 2)
869            <= static_cast<size_t>(maxSmallSize));
870     return static_cast<size_t>(maxSmallSize)
871       - (static_cast<size_t>(small_[maxSmallSize]) >> 2);
872 #else
873 #error Unable to identify target endianness
874 #endif
875   }
876
877   void setSmallSize(size_t s) {
878     // Warning: this should work with uninitialized strings too,
879     // so don't assume anything about the previous value of
880     // small_[maxSmallSize].
881     assert(s <= maxSmallSize);
882 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
883     small_[maxSmallSize] = maxSmallSize - s;
884 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
885     small_[maxSmallSize] = (maxSmallSize - s) << 2;
886 #else
887 #error Unable to identify target endianness
888 #endif
889     writeTerminator();
890   }
891 };
892
893 #ifndef _LIBSTDCXX_FBSTRING
894 /**
895  * Dummy fbstring core that uses an actual std::string. This doesn't
896  * make any sense - it's just for testing purposes.
897  */
898 template <class Char>
899 class dummy_fbstring_core {
900 public:
901   dummy_fbstring_core() {
902   }
903   dummy_fbstring_core(const dummy_fbstring_core& another)
904       : backend_(another.backend_) {
905   }
906   dummy_fbstring_core(const Char * s, size_t n)
907       : backend_(s, n) {
908   }
909   void swap(dummy_fbstring_core & rhs) {
910     backend_.swap(rhs.backend_);
911   }
912   const Char * data() const {
913     return backend_.data();
914   }
915   Char * mutable_data() {
916     //assert(!backend_.empty());
917     return &*backend_.begin();
918   }
919   void shrink(size_t delta) {
920     assert(delta <= size());
921     backend_.resize(size() - delta);
922   }
923   Char * expand_noinit(size_t delta) {
924     auto const sz = size();
925     backend_.resize(size() + delta);
926     return backend_.data() + sz;
927   }
928   void push_back(Char c) {
929     backend_.push_back(c);
930   }
931   size_t size() const {
932     return backend_.size();
933   }
934   size_t capacity() const {
935     return backend_.capacity();
936   }
937   bool isShared() const {
938     return false;
939   }
940   void reserve(size_t minCapacity) {
941     backend_.reserve(minCapacity);
942   }
943
944 private:
945   std::basic_string<Char> backend_;
946 };
947 #endif // !_LIBSTDCXX_FBSTRING
948
949 /**
950  * This is the basic_string replacement. For conformity,
951  * basic_fbstring takes the same template parameters, plus the last
952  * one which is the core.
953  */
954 #ifdef _LIBSTDCXX_FBSTRING
955 template <typename E, class T, class A, class Storage>
956 #else
957 template <typename E,
958           class T = std::char_traits<E>,
959           class A = std::allocator<E>,
960           class Storage = fbstring_core<E> >
961 #endif
962 class basic_fbstring {
963
964   static void enforce(
965       bool condition,
966       void (*throw_exc)(const char*),
967       const char* msg) {
968     if (!condition) throw_exc(msg);
969   }
970
971   bool isSane() const {
972     return
973       begin() <= end() &&
974       empty() == (size() == 0) &&
975       empty() == (begin() == end()) &&
976       size() <= max_size() &&
977       capacity() <= max_size() &&
978       size() <= capacity() &&
979       begin()[size()] == '\0';
980   }
981
982   struct Invariant;
983   friend struct Invariant;
984   struct Invariant {
985 #ifndef NDEBUG
986     explicit Invariant(const basic_fbstring& s) : s_(s) {
987       assert(s_.isSane());
988     }
989     ~Invariant() {
990       assert(s_.isSane());
991     }
992   private:
993     const basic_fbstring& s_;
994 #else
995     explicit Invariant(const basic_fbstring&) {}
996 #endif
997     Invariant& operator=(const Invariant&);
998   };
999
1000 public:
1001   // types
1002   typedef T traits_type;
1003   typedef typename traits_type::char_type value_type;
1004   typedef A allocator_type;
1005   typedef typename A::size_type size_type;
1006   typedef typename A::difference_type difference_type;
1007
1008   typedef typename A::reference reference;
1009   typedef typename A::const_reference const_reference;
1010   typedef typename A::pointer pointer;
1011   typedef typename A::const_pointer const_pointer;
1012
1013   typedef E* iterator;
1014   typedef const E* const_iterator;
1015   typedef std::reverse_iterator<iterator
1016 #ifdef NO_ITERATOR_TRAITS
1017                                 , value_type
1018 #endif
1019                                 > reverse_iterator;
1020   typedef std::reverse_iterator<const_iterator
1021 #ifdef NO_ITERATOR_TRAITS
1022                                 , const value_type
1023 #endif
1024                                 > const_reverse_iterator;
1025
1026   static const size_type npos;                     // = size_type(-1)
1027
1028 private:
1029   static void procrustes(size_type& n, size_type nmax) {
1030     if (n > nmax) n = nmax;
1031   }
1032
1033 public:
1034   // C++11 21.4.2 construct/copy/destroy
1035   explicit basic_fbstring(const A& /*a*/ = A()) noexcept {
1036   }
1037
1038   basic_fbstring(const basic_fbstring& str)
1039       : store_(str.store_) {
1040   }
1041
1042   // Move constructor
1043   basic_fbstring(basic_fbstring&& goner) noexcept
1044       : store_(std::move(goner.store_)) {
1045   }
1046
1047 #ifndef _LIBSTDCXX_FBSTRING
1048   // This is defined for compatibility with std::string
1049   /* implicit */ basic_fbstring(const std::string& str)
1050       : store_(str.data(), str.size()) {
1051   }
1052 #endif
1053
1054   basic_fbstring(const basic_fbstring& str, size_type pos,
1055                  size_type n = npos, const A& a = A()) {
1056     assign(str, pos, n);
1057   }
1058
1059   /* implicit */ basic_fbstring(const value_type* s, const A& /*a*/ = A())
1060       : store_(s, s
1061           ? traits_type::length(s)
1062           : (std::__throw_logic_error(
1063                 "basic_fbstring: null pointer initializer not valid"),
1064              0)) {
1065   }
1066
1067   basic_fbstring(const value_type* s, size_type n, const A& /*a*/ = A())
1068       : store_(s, n) {
1069   }
1070
1071   basic_fbstring(size_type n, value_type c, const A& /*a*/ = A()) {
1072     auto const data = store_.expand_noinit(n);
1073     fbstring_detail::pod_fill(data, data + n, c);
1074     store_.writeTerminator();
1075   }
1076
1077   template <class InIt>
1078   basic_fbstring(InIt begin, InIt end,
1079                  typename std::enable_if<
1080                  !std::is_same<typename std::remove_const<InIt>::type,
1081                  value_type*>::value, const A>::type & /*a*/ = A()) {
1082     assign(begin, end);
1083   }
1084
1085   // Specialization for const char*, const char*
1086   basic_fbstring(const value_type* b, const value_type* e)
1087       : store_(b, e - b) {
1088   }
1089
1090   // Nonstandard constructor
1091   basic_fbstring(value_type *s, size_type n, size_type c,
1092                  AcquireMallocatedString a)
1093       : store_(s, n, c, a) {
1094   }
1095
1096   // Construction from initialization list
1097   basic_fbstring(std::initializer_list<value_type> il) {
1098     assign(il.begin(), il.end());
1099   }
1100
1101   ~basic_fbstring() noexcept {
1102   }
1103
1104   basic_fbstring& operator=(const basic_fbstring& lhs) {
1105     if (FBSTRING_UNLIKELY(&lhs == this)) {
1106       return *this;
1107     }
1108     auto const oldSize = size();
1109     auto const srcSize = lhs.size();
1110     if (capacity() >= srcSize && !store_.isShared()) {
1111       // great, just copy the contents
1112       if (oldSize < srcSize)
1113         store_.expand_noinit(srcSize - oldSize);
1114       else
1115         store_.shrink(oldSize - srcSize);
1116       assert(size() == srcSize);
1117       fbstring_detail::pod_copy(lhs.begin(), lhs.end(), begin());
1118       store_.writeTerminator();
1119     } else {
1120       // need to reallocate, so we may as well create a brand new string
1121       basic_fbstring(lhs).swap(*this);
1122     }
1123     return *this;
1124   }
1125
1126   // Move assignment
1127   basic_fbstring& operator=(basic_fbstring&& goner) noexcept {
1128     if (FBSTRING_UNLIKELY(&goner == this)) {
1129       // Compatibility with std::basic_string<>,
1130       // C++11 21.4.2 [string.cons] / 23 requires self-move-assignment support.
1131       return *this;
1132     }
1133     // No need of this anymore
1134     this->~basic_fbstring();
1135     // Move the goner into this
1136     new(&store_) fbstring_core<E>(std::move(goner.store_));
1137     return *this;
1138   }
1139
1140 #ifndef _LIBSTDCXX_FBSTRING
1141   // Compatibility with std::string
1142   basic_fbstring & operator=(const std::string & rhs) {
1143     return assign(rhs.data(), rhs.size());
1144   }
1145
1146   // Compatibility with std::string
1147   std::string toStdString() const {
1148     return std::string(data(), size());
1149   }
1150 #else
1151   // A lot of code in fbcode still uses this method, so keep it here for now.
1152   const basic_fbstring& toStdString() const {
1153     return *this;
1154   }
1155 #endif
1156
1157   basic_fbstring& operator=(const value_type* s) {
1158     return assign(s);
1159   }
1160
1161   basic_fbstring& operator=(value_type c) {
1162     if (empty()) {
1163       store_.expand_noinit(1);
1164     } else if (store_.isShared()) {
1165       basic_fbstring(1, c).swap(*this);
1166       return *this;
1167     } else {
1168       store_.shrink(size() - 1);
1169     }
1170     *store_.mutable_data() = c;
1171     store_.writeTerminator();
1172     return *this;
1173   }
1174
1175   basic_fbstring& operator=(std::initializer_list<value_type> il) {
1176     return assign(il.begin(), il.end());
1177   }
1178
1179   // C++11 21.4.3 iterators:
1180   iterator begin() { return store_.mutable_data(); }
1181
1182   const_iterator begin() const { return store_.data(); }
1183
1184   const_iterator cbegin() const { return begin(); }
1185
1186   iterator end() {
1187     return store_.mutable_data() + store_.size();
1188   }
1189
1190   const_iterator end() const {
1191     return store_.data() + store_.size();
1192   }
1193
1194   const_iterator cend() const { return end(); }
1195
1196   reverse_iterator rbegin() {
1197     return reverse_iterator(end());
1198   }
1199
1200   const_reverse_iterator rbegin() const {
1201     return const_reverse_iterator(end());
1202   }
1203
1204   const_reverse_iterator crbegin() const { return rbegin(); }
1205
1206   reverse_iterator rend() {
1207     return reverse_iterator(begin());
1208   }
1209
1210   const_reverse_iterator rend() const {
1211     return const_reverse_iterator(begin());
1212   }
1213
1214   const_reverse_iterator crend() const { return rend(); }
1215
1216   // Added by C++11
1217   // C++11 21.4.5, element access:
1218   const value_type& front() const { return *begin(); }
1219   const value_type& back() const {
1220     assert(!empty());
1221     // Should be begin()[size() - 1], but that branches twice
1222     return *(end() - 1);
1223   }
1224   value_type& front() { return *begin(); }
1225   value_type& back() {
1226     assert(!empty());
1227     // Should be begin()[size() - 1], but that branches twice
1228     return *(end() - 1);
1229   }
1230   void pop_back() {
1231     assert(!empty());
1232     store_.shrink(1);
1233   }
1234
1235   // C++11 21.4.4 capacity:
1236   size_type size() const { return store_.size(); }
1237
1238   size_type length() const { return size(); }
1239
1240   size_type max_size() const {
1241     return std::numeric_limits<size_type>::max();
1242   }
1243
1244   void resize(const size_type n, const value_type c = value_type()) {
1245     auto size = this->size();
1246     if (n <= size) {
1247       store_.shrink(size - n);
1248     } else {
1249       // Do this in two steps to minimize slack memory copied (see
1250       // smartRealloc).
1251       auto const capacity = this->capacity();
1252       assert(capacity >= size);
1253       if (size < capacity) {
1254         auto delta = std::min(n, capacity) - size;
1255         store_.expand_noinit(delta);
1256         fbstring_detail::pod_fill(begin() + size, end(), c);
1257         size += delta;
1258         if (size == n) {
1259           store_.writeTerminator();
1260           return;
1261         }
1262         assert(size < n);
1263       }
1264       auto const delta = n - size;
1265       store_.expand_noinit(delta);
1266       fbstring_detail::pod_fill(end() - delta, end(), c);
1267       store_.writeTerminator();
1268     }
1269     assert(this->size() == n);
1270   }
1271
1272   size_type capacity() const { return store_.capacity(); }
1273
1274   void reserve(size_type res_arg = 0) {
1275     enforce(res_arg <= max_size(), std::__throw_length_error, "");
1276     store_.reserve(res_arg);
1277   }
1278
1279   void shrink_to_fit() {
1280     // Shrink only if slack memory is sufficiently large
1281     if (capacity() < size() * 3 / 2) {
1282       return;
1283     }
1284     basic_fbstring(cbegin(), cend()).swap(*this);
1285   }
1286
1287   void clear() { resize(0); }
1288
1289   bool empty() const { return size() == 0; }
1290
1291   // C++11 21.4.5 element access:
1292   const_reference operator[](size_type pos) const {
1293     return *(begin() + pos);
1294   }
1295
1296   reference operator[](size_type pos) {
1297     return *(begin() + pos);
1298   }
1299
1300   const_reference at(size_type n) const {
1301     enforce(n <= size(), std::__throw_out_of_range, "");
1302     return (*this)[n];
1303   }
1304
1305   reference at(size_type n) {
1306     enforce(n < size(), std::__throw_out_of_range, "");
1307     return (*this)[n];
1308   }
1309
1310   // C++11 21.4.6 modifiers:
1311   basic_fbstring& operator+=(const basic_fbstring& str) {
1312     return append(str);
1313   }
1314
1315   basic_fbstring& operator+=(const value_type* s) {
1316     return append(s);
1317   }
1318
1319   basic_fbstring& operator+=(const value_type c) {
1320     push_back(c);
1321     return *this;
1322   }
1323
1324   basic_fbstring& operator+=(std::initializer_list<value_type> il) {
1325     append(il);
1326     return *this;
1327   }
1328
1329   basic_fbstring& append(const basic_fbstring& str) {
1330 #ifndef NDEBUG
1331     auto desiredSize = size() + str.size();
1332 #endif
1333     append(str.data(), str.size());
1334     assert(size() == desiredSize);
1335     return *this;
1336   }
1337
1338   basic_fbstring& append(const basic_fbstring& str, const size_type pos,
1339                          size_type n) {
1340     const size_type sz = str.size();
1341     enforce(pos <= sz, std::__throw_out_of_range, "");
1342     procrustes(n, sz - pos);
1343     return append(str.data() + pos, n);
1344   }
1345
1346   basic_fbstring& append(const value_type* s, size_type n) {
1347 #ifndef NDEBUG
1348     Invariant checker(*this);
1349     (void) checker;
1350 #endif
1351     if (FBSTRING_UNLIKELY(!n)) {
1352       // Unlikely but must be done
1353       return *this;
1354     }
1355     auto const oldSize = size();
1356     auto const oldData = data();
1357     // Check for aliasing (rare). We could use "<=" here but in theory
1358     // those do not work for pointers unless the pointers point to
1359     // elements in the same array. For that reason we use
1360     // std::less_equal, which is guaranteed to offer a total order
1361     // over pointers. See discussion at http://goo.gl/Cy2ya for more
1362     // info.
1363     std::less_equal<const value_type*> le;
1364     if (FBSTRING_UNLIKELY(le(oldData, s) && !le(oldData + oldSize, s))) {
1365       assert(le(s + n, oldData + oldSize));
1366       const size_type offset = s - oldData;
1367       store_.reserve(oldSize + n);
1368       // Restore the source
1369       s = data() + offset;
1370     }
1371     // Warning! Repeated appends with short strings may actually incur
1372     // practically quadratic performance. Avoid that by pushing back
1373     // the first character (which ensures exponential growth) and then
1374     // appending the rest normally. Worst case the append may incur a
1375     // second allocation but that will be rare.
1376     push_back(*s++);
1377     --n;
1378     memcpy(store_.expand_noinit(n), s, n * sizeof(value_type));
1379     assert(size() == oldSize + n + 1);
1380     return *this;
1381   }
1382
1383   basic_fbstring& append(const value_type* s) {
1384     return append(s, traits_type::length(s));
1385   }
1386
1387   basic_fbstring& append(size_type n, value_type c) {
1388     resize(size() + n, c);
1389     return *this;
1390   }
1391
1392   template<class InputIterator>
1393   basic_fbstring& append(InputIterator first, InputIterator last) {
1394     insert(end(), first, last);
1395     return *this;
1396   }
1397
1398   basic_fbstring& append(std::initializer_list<value_type> il) {
1399     return append(il.begin(), il.end());
1400   }
1401
1402   void push_back(const value_type c) {             // primitive
1403     store_.push_back(c);
1404   }
1405
1406   basic_fbstring& assign(const basic_fbstring& str) {
1407     if (&str == this) return *this;
1408     return assign(str.data(), str.size());
1409   }
1410
1411   basic_fbstring& assign(basic_fbstring&& str) {
1412     return *this = std::move(str);
1413   }
1414
1415   basic_fbstring& assign(const basic_fbstring& str, const size_type pos,
1416                          size_type n) {
1417     const size_type sz = str.size();
1418     enforce(pos <= sz, std::__throw_out_of_range, "");
1419     procrustes(n, sz - pos);
1420     return assign(str.data() + pos, n);
1421   }
1422
1423   basic_fbstring& assign(const value_type* s, const size_type n) {
1424     Invariant checker(*this);
1425     (void) checker;
1426     if (size() >= n) {
1427       std::copy(s, s + n, begin());
1428       resize(n);
1429       assert(size() == n);
1430     } else {
1431       const value_type *const s2 = s + size();
1432       std::copy(s, s2, begin());
1433       append(s2, n - size());
1434       assert(size() == n);
1435     }
1436     store_.writeTerminator();
1437     assert(size() == n);
1438     return *this;
1439   }
1440
1441   basic_fbstring& assign(const value_type* s) {
1442     return assign(s, traits_type::length(s));
1443   }
1444
1445   basic_fbstring& assign(std::initializer_list<value_type> il) {
1446     return assign(il.begin(), il.end());
1447   }
1448
1449   template <class ItOrLength, class ItOrChar>
1450   basic_fbstring& assign(ItOrLength first_or_n, ItOrChar last_or_c) {
1451     return replace(begin(), end(), first_or_n, last_or_c);
1452   }
1453
1454   basic_fbstring& insert(size_type pos1, const basic_fbstring& str) {
1455     return insert(pos1, str.data(), str.size());
1456   }
1457
1458   basic_fbstring& insert(size_type pos1, const basic_fbstring& str,
1459                          size_type pos2, size_type n) {
1460     enforce(pos2 <= str.length(), std::__throw_out_of_range, "");
1461     procrustes(n, str.length() - pos2);
1462     return insert(pos1, str.data() + pos2, n);
1463   }
1464
1465   basic_fbstring& insert(size_type pos, const value_type* s, size_type n) {
1466     enforce(pos <= length(), std::__throw_out_of_range, "");
1467     insert(begin() + pos, s, s + n);
1468     return *this;
1469   }
1470
1471   basic_fbstring& insert(size_type pos, const value_type* s) {
1472     return insert(pos, s, traits_type::length(s));
1473   }
1474
1475   basic_fbstring& insert(size_type pos, size_type n, value_type c) {
1476     enforce(pos <= length(), std::__throw_out_of_range, "");
1477     insert(begin() + pos, n, c);
1478     return *this;
1479   }
1480
1481   iterator insert(const_iterator p, const value_type c) {
1482     const size_type pos = p - begin();
1483     insert(p, 1, c);
1484     return begin() + pos;
1485   }
1486
1487 private:
1488   template <int i> class Selector {};
1489
1490   iterator insertImplDiscr(const_iterator p,
1491                            size_type n, value_type c, Selector<1>) {
1492     Invariant checker(*this);
1493     (void) checker;
1494     auto const pos = p - begin();
1495     assert(p >= begin() && p <= end());
1496     if (capacity() - size() < n) {
1497       const size_type sz = p - begin();
1498       reserve(size() + n);
1499       p = begin() + sz;
1500     }
1501     const iterator oldEnd = end();
1502     if (n < size_type(oldEnd - p)) {
1503       append(oldEnd - n, oldEnd);
1504       //std::copy(
1505       //    reverse_iterator(oldEnd - n),
1506       //    reverse_iterator(p),
1507       //    reverse_iterator(oldEnd));
1508       fbstring_detail::pod_move(&*p, &*oldEnd - n,
1509                                 begin() + pos + n);
1510       std::fill(begin() + pos, begin() + pos + n, c);
1511     } else {
1512       append(n - (end() - p), c);
1513       append(iterator(p), oldEnd);
1514       std::fill(iterator(p), oldEnd, c);
1515     }
1516     store_.writeTerminator();
1517     return begin() + pos;
1518   }
1519
1520   template<class InputIter>
1521   iterator insertImplDiscr(const_iterator i,
1522                            InputIter b, InputIter e, Selector<0>) {
1523     return insertImpl(i, b, e,
1524                typename std::iterator_traits<InputIter>::iterator_category());
1525   }
1526
1527   template <class FwdIterator>
1528   iterator insertImpl(const_iterator i,
1529                   FwdIterator s1, FwdIterator s2, std::forward_iterator_tag) {
1530     Invariant checker(*this);
1531     (void) checker;
1532     const size_type pos = i - begin();
1533     const typename std::iterator_traits<FwdIterator>::difference_type n2 =
1534       std::distance(s1, s2);
1535     assert(n2 >= 0);
1536     using namespace fbstring_detail;
1537     assert(pos <= size());
1538
1539     const typename std::iterator_traits<FwdIterator>::difference_type maxn2 =
1540       capacity() - size();
1541     if (maxn2 < n2) {
1542       // realloc the string
1543       reserve(size() + n2);
1544       i = begin() + pos;
1545     }
1546     if (pos + n2 <= size()) {
1547       const iterator tailBegin = end() - n2;
1548       store_.expand_noinit(n2);
1549       fbstring_detail::pod_copy(tailBegin, tailBegin + n2, end() - n2);
1550       std::copy(const_reverse_iterator(tailBegin), const_reverse_iterator(i),
1551                 reverse_iterator(tailBegin + n2));
1552       std::copy(s1, s2, begin() + pos);
1553     } else {
1554       FwdIterator t = s1;
1555       const size_type old_size = size();
1556       std::advance(t, old_size - pos);
1557       const size_t newElems = std::distance(t, s2);
1558       store_.expand_noinit(n2);
1559       std::copy(t, s2, begin() + old_size);
1560       fbstring_detail::pod_copy(data() + pos, data() + old_size,
1561                                  begin() + old_size + newElems);
1562       std::copy(s1, t, begin() + pos);
1563     }
1564     store_.writeTerminator();
1565     return begin() + pos;
1566   }
1567
1568   template <class InputIterator>
1569   iterator insertImpl(const_iterator i,
1570                       InputIterator b, InputIterator e,
1571                       std::input_iterator_tag) {
1572     const auto pos = i - begin();
1573     basic_fbstring temp(begin(), i);
1574     for (; b != e; ++b) {
1575       temp.push_back(*b);
1576     }
1577     temp.append(i, cend());
1578     swap(temp);
1579     return begin() + pos;
1580   }
1581
1582 public:
1583   template <class ItOrLength, class ItOrChar>
1584   iterator insert(const_iterator p, ItOrLength first_or_n, ItOrChar last_or_c) {
1585     Selector<std::numeric_limits<ItOrLength>::is_specialized> sel;
1586     return insertImplDiscr(p, first_or_n, last_or_c, sel);
1587   }
1588
1589   iterator insert(const_iterator p, std::initializer_list<value_type> il) {
1590     return insert(p, il.begin(), il.end());
1591   }
1592
1593   basic_fbstring& erase(size_type pos = 0, size_type n = npos) {
1594     Invariant checker(*this);
1595     (void) checker;
1596     enforce(pos <= length(), std::__throw_out_of_range, "");
1597     procrustes(n, length() - pos);
1598     std::copy(begin() + pos + n, end(), begin() + pos);
1599     resize(length() - n);
1600     return *this;
1601   }
1602
1603   iterator erase(iterator position) {
1604     const size_type pos(position - begin());
1605     enforce(pos <= size(), std::__throw_out_of_range, "");
1606     erase(pos, 1);
1607     return begin() + pos;
1608   }
1609
1610   iterator erase(iterator first, iterator last) {
1611     const size_type pos(first - begin());
1612     erase(pos, last - first);
1613     return begin() + pos;
1614   }
1615
1616   // Replaces at most n1 chars of *this, starting with pos1 with the
1617   // content of str
1618   basic_fbstring& replace(size_type pos1, size_type n1,
1619                           const basic_fbstring& str) {
1620     return replace(pos1, n1, str.data(), str.size());
1621   }
1622
1623   // Replaces at most n1 chars of *this, starting with pos1,
1624   // with at most n2 chars of str starting with pos2
1625   basic_fbstring& replace(size_type pos1, size_type n1,
1626                           const basic_fbstring& str,
1627                           size_type pos2, size_type n2) {
1628     enforce(pos2 <= str.length(), std::__throw_out_of_range, "");
1629     return replace(pos1, n1, str.data() + pos2,
1630                    std::min(n2, str.size() - pos2));
1631   }
1632
1633   // Replaces at most n1 chars of *this, starting with pos, with chars from s
1634   basic_fbstring& replace(size_type pos, size_type n1, const value_type* s) {
1635     return replace(pos, n1, s, traits_type::length(s));
1636   }
1637
1638   // Replaces at most n1 chars of *this, starting with pos, with n2
1639   // occurrences of c
1640   //
1641   // consolidated with
1642   //
1643   // Replaces at most n1 chars of *this, starting with pos, with at
1644   // most n2 chars of str.  str must have at least n2 chars.
1645   template <class StrOrLength, class NumOrChar>
1646   basic_fbstring& replace(size_type pos, size_type n1,
1647                           StrOrLength s_or_n2, NumOrChar n_or_c) {
1648     Invariant checker(*this);
1649     (void) checker;
1650     enforce(pos <= size(), std::__throw_out_of_range, "");
1651     procrustes(n1, length() - pos);
1652     const iterator b = begin() + pos;
1653     return replace(b, b + n1, s_or_n2, n_or_c);
1654   }
1655
1656   basic_fbstring& replace(iterator i1, iterator i2, const basic_fbstring& str) {
1657     return replace(i1, i2, str.data(), str.length());
1658   }
1659
1660   basic_fbstring& replace(iterator i1, iterator i2, const value_type* s) {
1661     return replace(i1, i2, s, traits_type::length(s));
1662   }
1663
1664 private:
1665   basic_fbstring& replaceImplDiscr(iterator i1, iterator i2,
1666                                    const value_type* s, size_type n,
1667                                    Selector<2>) {
1668     assert(i1 <= i2);
1669     assert(begin() <= i1 && i1 <= end());
1670     assert(begin() <= i2 && i2 <= end());
1671     return replace(i1, i2, s, s + n);
1672   }
1673
1674   basic_fbstring& replaceImplDiscr(iterator i1, iterator i2,
1675                                    size_type n2, value_type c, Selector<1>) {
1676     const size_type n1 = i2 - i1;
1677     if (n1 > n2) {
1678       std::fill(i1, i1 + n2, c);
1679       erase(i1 + n2, i2);
1680     } else {
1681       std::fill(i1, i2, c);
1682       insert(i2, n2 - n1, c);
1683     }
1684     assert(isSane());
1685     return *this;
1686   }
1687
1688   template <class InputIter>
1689   basic_fbstring& replaceImplDiscr(iterator i1, iterator i2,
1690                                    InputIter b, InputIter e,
1691                                    Selector<0>) {
1692     replaceImpl(i1, i2, b, e,
1693                 typename std::iterator_traits<InputIter>::iterator_category());
1694     return *this;
1695   }
1696
1697 private:
1698   template <class FwdIterator>
1699   bool replaceAliased(iterator i1, iterator i2,
1700                       FwdIterator s1, FwdIterator s2, std::false_type) {
1701     return false;
1702   }
1703
1704   template <class FwdIterator>
1705   bool replaceAliased(iterator i1, iterator i2,
1706                       FwdIterator s1, FwdIterator s2, std::true_type) {
1707     static const std::less_equal<const value_type*> le =
1708       std::less_equal<const value_type*>();
1709     const bool aliased = le(&*begin(), &*s1) && le(&*s1, &*end());
1710     if (!aliased) {
1711       return false;
1712     }
1713     // Aliased replace, copy to new string
1714     basic_fbstring temp;
1715     temp.reserve(size() - (i2 - i1) + std::distance(s1, s2));
1716     temp.append(begin(), i1).append(s1, s2).append(i2, end());
1717     swap(temp);
1718     return true;
1719   }
1720
1721   template <class FwdIterator>
1722   void replaceImpl(iterator i1, iterator i2,
1723                    FwdIterator s1, FwdIterator s2, std::forward_iterator_tag) {
1724     Invariant checker(*this);
1725     (void) checker;
1726
1727     // Handle aliased replace
1728     if (replaceAliased(i1, i2, s1, s2,
1729           std::integral_constant<bool,
1730             std::is_same<FwdIterator, iterator>::value ||
1731             std::is_same<FwdIterator, const_iterator>::value>())) {
1732       return;
1733     }
1734
1735     auto const n1 = i2 - i1;
1736     assert(n1 >= 0);
1737     auto const n2 = std::distance(s1, s2);
1738     assert(n2 >= 0);
1739
1740     if (n1 > n2) {
1741       // shrinks
1742       std::copy(s1, s2, i1);
1743       erase(i1 + n2, i2);
1744     } else {
1745       // grows
1746       fbstring_detail::copy_n(s1, n1, i1);
1747       std::advance(s1, n1);
1748       insert(i2, s1, s2);
1749     }
1750     assert(isSane());
1751   }
1752
1753   template <class InputIterator>
1754   void replaceImpl(iterator i1, iterator i2,
1755                    InputIterator b, InputIterator e, std::input_iterator_tag) {
1756     basic_fbstring temp(begin(), i1);
1757     temp.append(b, e).append(i2, end());
1758     swap(temp);
1759   }
1760
1761 public:
1762   template <class T1, class T2>
1763   basic_fbstring& replace(iterator i1, iterator i2,
1764                           T1 first_or_n_or_s, T2 last_or_c_or_n) {
1765     const bool
1766       num1 = std::numeric_limits<T1>::is_specialized,
1767       num2 = std::numeric_limits<T2>::is_specialized;
1768     return replaceImplDiscr(
1769       i1, i2, first_or_n_or_s, last_or_c_or_n,
1770       Selector<num1 ? (num2 ? 1 : -1) : (num2 ? 2 : 0)>());
1771   }
1772
1773   size_type copy(value_type* s, size_type n, size_type pos = 0) const {
1774     enforce(pos <= size(), std::__throw_out_of_range, "");
1775     procrustes(n, size() - pos);
1776
1777     fbstring_detail::pod_copy(
1778       data() + pos,
1779       data() + pos + n,
1780       s);
1781     return n;
1782   }
1783
1784   void swap(basic_fbstring& rhs) {
1785     store_.swap(rhs.store_);
1786   }
1787
1788   const value_type* c_str() const {
1789     return store_.c_str();
1790   }
1791
1792   const value_type* data() const { return c_str(); }
1793
1794   allocator_type get_allocator() const {
1795     return allocator_type();
1796   }
1797
1798   size_type find(const basic_fbstring& str, size_type pos = 0) const {
1799     return find(str.data(), pos, str.length());
1800   }
1801
1802   size_type find(const value_type* needle, const size_type pos,
1803                  const size_type nsize) const {
1804     if (!nsize) return pos;
1805     auto const size = this->size();
1806     // nsize + pos can overflow (eg pos == npos), guard against that by checking
1807     // that nsize + pos does not wrap around.
1808     if (nsize + pos > size || nsize + pos < pos) return npos;
1809     // Don't use std::search, use a Boyer-Moore-like trick by comparing
1810     // the last characters first
1811     auto const haystack = data();
1812     auto const nsize_1 = nsize - 1;
1813     auto const lastNeedle = needle[nsize_1];
1814
1815     // Boyer-Moore skip value for the last char in the needle. Zero is
1816     // not a valid value; skip will be computed the first time it's
1817     // needed.
1818     size_type skip = 0;
1819
1820     const E * i = haystack + pos;
1821     auto iEnd = haystack + size - nsize_1;
1822
1823     while (i < iEnd) {
1824       // Boyer-Moore: match the last element in the needle
1825       while (i[nsize_1] != lastNeedle) {
1826         if (++i == iEnd) {
1827           // not found
1828           return npos;
1829         }
1830       }
1831       // Here we know that the last char matches
1832       // Continue in pedestrian mode
1833       for (size_t j = 0; ; ) {
1834         assert(j < nsize);
1835         if (i[j] != needle[j]) {
1836           // Not found, we can skip
1837           // Compute the skip value lazily
1838           if (skip == 0) {
1839             skip = 1;
1840             while (skip <= nsize_1 && needle[nsize_1 - skip] != lastNeedle) {
1841               ++skip;
1842             }
1843           }
1844           i += skip;
1845           break;
1846         }
1847         // Check if done searching
1848         if (++j == nsize) {
1849           // Yay
1850           return i - haystack;
1851         }
1852       }
1853     }
1854     return npos;
1855   }
1856
1857   size_type find(const value_type* s, size_type pos = 0) const {
1858     return find(s, pos, traits_type::length(s));
1859   }
1860
1861   size_type find (value_type c, size_type pos = 0) const {
1862     return find(&c, pos, 1);
1863   }
1864
1865   size_type rfind(const basic_fbstring& str, size_type pos = npos) const {
1866     return rfind(str.data(), pos, str.length());
1867   }
1868
1869   size_type rfind(const value_type* s, size_type pos, size_type n) const {
1870     if (n > length()) return npos;
1871     pos = std::min(pos, length() - n);
1872     if (n == 0) return pos;
1873
1874     const_iterator i(begin() + pos);
1875     for (; ; --i) {
1876       if (traits_type::eq(*i, *s)
1877           && traits_type::compare(&*i, s, n) == 0) {
1878         return i - begin();
1879       }
1880       if (i == begin()) break;
1881     }
1882     return npos;
1883   }
1884
1885   size_type rfind(const value_type* s, size_type pos = npos) const {
1886     return rfind(s, pos, traits_type::length(s));
1887   }
1888
1889   size_type rfind(value_type c, size_type pos = npos) const {
1890     return rfind(&c, pos, 1);
1891   }
1892
1893   size_type find_first_of(const basic_fbstring& str, size_type pos = 0) const {
1894     return find_first_of(str.data(), pos, str.length());
1895   }
1896
1897   size_type find_first_of(const value_type* s,
1898                           size_type pos, size_type n) const {
1899     if (pos > length() || n == 0) return npos;
1900     const_iterator i(begin() + pos),
1901       finish(end());
1902     for (; i != finish; ++i) {
1903       if (traits_type::find(s, n, *i) != 0) {
1904         return i - begin();
1905       }
1906     }
1907     return npos;
1908   }
1909
1910   size_type find_first_of(const value_type* s, size_type pos = 0) const {
1911     return find_first_of(s, pos, traits_type::length(s));
1912   }
1913
1914   size_type find_first_of(value_type c, size_type pos = 0) const {
1915     return find_first_of(&c, pos, 1);
1916   }
1917
1918   size_type find_last_of (const basic_fbstring& str,
1919                           size_type pos = npos) const {
1920     return find_last_of(str.data(), pos, str.length());
1921   }
1922
1923   size_type find_last_of (const value_type* s, size_type pos,
1924                           size_type n) const {
1925     if (!empty() && n > 0) {
1926       pos = std::min(pos, length() - 1);
1927       const_iterator i(begin() + pos);
1928       for (;; --i) {
1929         if (traits_type::find(s, n, *i) != 0) {
1930           return i - begin();
1931         }
1932         if (i == begin()) break;
1933       }
1934     }
1935     return npos;
1936   }
1937
1938   size_type find_last_of (const value_type* s,
1939                           size_type pos = npos) const {
1940     return find_last_of(s, pos, traits_type::length(s));
1941   }
1942
1943   size_type find_last_of (value_type c, size_type pos = npos) const {
1944     return find_last_of(&c, pos, 1);
1945   }
1946
1947   size_type find_first_not_of(const basic_fbstring& str,
1948                               size_type pos = 0) const {
1949     return find_first_not_of(str.data(), pos, str.size());
1950   }
1951
1952   size_type find_first_not_of(const value_type* s, size_type pos,
1953                               size_type n) const {
1954     if (pos < length()) {
1955       const_iterator
1956         i(begin() + pos),
1957         finish(end());
1958       for (; i != finish; ++i) {
1959         if (traits_type::find(s, n, *i) == 0) {
1960           return i - begin();
1961         }
1962       }
1963     }
1964     return npos;
1965   }
1966
1967   size_type find_first_not_of(const value_type* s,
1968                               size_type pos = 0) const {
1969     return find_first_not_of(s, pos, traits_type::length(s));
1970   }
1971
1972   size_type find_first_not_of(value_type c, size_type pos = 0) const {
1973     return find_first_not_of(&c, pos, 1);
1974   }
1975
1976   size_type find_last_not_of(const basic_fbstring& str,
1977                              size_type pos = npos) const {
1978     return find_last_not_of(str.data(), pos, str.length());
1979   }
1980
1981   size_type find_last_not_of(const value_type* s, size_type pos,
1982                              size_type n) const {
1983     if (!this->empty()) {
1984       pos = std::min(pos, size() - 1);
1985       const_iterator i(begin() + pos);
1986       for (;; --i) {
1987         if (traits_type::find(s, n, *i) == 0) {
1988           return i - begin();
1989         }
1990         if (i == begin()) break;
1991       }
1992     }
1993     return npos;
1994   }
1995
1996   size_type find_last_not_of(const value_type* s,
1997                              size_type pos = npos) const {
1998     return find_last_not_of(s, pos, traits_type::length(s));
1999   }
2000
2001   size_type find_last_not_of (value_type c, size_type pos = npos) const {
2002     return find_last_not_of(&c, pos, 1);
2003   }
2004
2005   basic_fbstring substr(size_type pos = 0, size_type n = npos) const& {
2006     enforce(pos <= size(), std::__throw_out_of_range, "");
2007     return basic_fbstring(data() + pos, std::min(n, size() - pos));
2008   }
2009
2010   basic_fbstring substr(size_type pos = 0, size_type n = npos) && {
2011     enforce(pos <= size(), std::__throw_out_of_range, "");
2012     erase(0, pos);
2013     if (n < size()) resize(n);
2014     return std::move(*this);
2015   }
2016
2017   int compare(const basic_fbstring& str) const {
2018     // FIX due to Goncalo N M de Carvalho July 18, 2005
2019     return compare(0, size(), str);
2020   }
2021
2022   int compare(size_type pos1, size_type n1,
2023               const basic_fbstring& str) const {
2024     return compare(pos1, n1, str.data(), str.size());
2025   }
2026
2027   int compare(size_type pos1, size_type n1,
2028               const value_type* s) const {
2029     return compare(pos1, n1, s, traits_type::length(s));
2030   }
2031
2032   int compare(size_type pos1, size_type n1,
2033               const value_type* s, size_type n2) const {
2034     enforce(pos1 <= size(), std::__throw_out_of_range, "");
2035     procrustes(n1, size() - pos1);
2036     // The line below fixed by Jean-Francois Bastien, 04-23-2007. Thanks!
2037     const int r = traits_type::compare(pos1 + data(), s, std::min(n1, n2));
2038     return r != 0 ? r : n1 > n2 ? 1 : n1 < n2 ? -1 : 0;
2039   }
2040
2041   int compare(size_type pos1, size_type n1,
2042               const basic_fbstring& str,
2043               size_type pos2, size_type n2) const {
2044     enforce(pos2 <= str.size(), std::__throw_out_of_range, "");
2045     return compare(pos1, n1, str.data() + pos2,
2046                    std::min(n2, str.size() - pos2));
2047   }
2048
2049   // Code from Jean-Francois Bastien (03/26/2007)
2050   int compare(const value_type* s) const {
2051     // Could forward to compare(0, size(), s, traits_type::length(s))
2052     // but that does two extra checks
2053     const size_type n1(size()), n2(traits_type::length(s));
2054     const int r = traits_type::compare(data(), s, std::min(n1, n2));
2055     return r != 0 ? r : n1 > n2 ? 1 : n1 < n2 ? -1 : 0;
2056   }
2057
2058 private:
2059   // Data
2060   Storage store_;
2061 };
2062
2063 // non-member functions
2064 // C++11 21.4.8.1/1
2065 template <typename E, class T, class A, class S>
2066 inline
2067 basic_fbstring<E, T, A, S> operator+(const basic_fbstring<E, T, A, S>& lhs,
2068                                      const basic_fbstring<E, T, A, S>& rhs) {
2069
2070   basic_fbstring<E, T, A, S> result;
2071   result.reserve(lhs.size() + rhs.size());
2072   result.append(lhs).append(rhs);
2073   return std::move(result);
2074 }
2075
2076 // C++11 21.4.8.1/2
2077 template <typename E, class T, class A, class S>
2078 inline
2079 basic_fbstring<E, T, A, S> operator+(basic_fbstring<E, T, A, S>&& lhs,
2080                                      const basic_fbstring<E, T, A, S>& rhs) {
2081   return std::move(lhs.append(rhs));
2082 }
2083
2084 // C++11 21.4.8.1/3
2085 template <typename E, class T, class A, class S>
2086 inline
2087 basic_fbstring<E, T, A, S> operator+(const basic_fbstring<E, T, A, S>& lhs,
2088                                      basic_fbstring<E, T, A, S>&& rhs) {
2089   if (rhs.capacity() >= lhs.size() + rhs.size()) {
2090     // Good, at least we don't need to reallocate
2091     return std::move(rhs.insert(0, lhs));
2092   }
2093   // Meh, no go. Forward to operator+(const&, const&).
2094   auto const& rhsC = rhs;
2095   return lhs + rhsC;
2096 }
2097
2098 // C++11 21.4.8.1/4
2099 template <typename E, class T, class A, class S>
2100 inline
2101 basic_fbstring<E, T, A, S> operator+(basic_fbstring<E, T, A, S>&& lhs,
2102                                      basic_fbstring<E, T, A, S>&& rhs) {
2103   return std::move(lhs.append(rhs));
2104 }
2105
2106 // C++11 21.4.8.1/5
2107 template <typename E, class T, class A, class S>
2108 inline
2109 basic_fbstring<E, T, A, S> operator+(
2110   const E* lhs,
2111   const basic_fbstring<E, T, A, S>& rhs) {
2112   //
2113   basic_fbstring<E, T, A, S> result;
2114   const auto len = basic_fbstring<E, T, A, S>::traits_type::length(lhs);
2115   result.reserve(len + rhs.size());
2116   result.append(lhs, len).append(rhs);
2117   return result;
2118 }
2119
2120 // C++11 21.4.8.1/6
2121 template <typename E, class T, class A, class S>
2122 inline
2123 basic_fbstring<E, T, A, S> operator+(
2124   const E* lhs,
2125   basic_fbstring<E, T, A, S>&& rhs) {
2126   //
2127   const auto len = basic_fbstring<E, T, A, S>::traits_type::length(lhs);
2128   if (rhs.capacity() >= len + rhs.size()) {
2129     // Good, at least we don't need to reallocate
2130     return std::move(rhs.insert(rhs.begin(), lhs, lhs + len));
2131   }
2132   // Meh, no go. Do it by hand since we have len already.
2133   basic_fbstring<E, T, A, S> result;
2134   result.reserve(len + rhs.size());
2135   result.append(lhs, len).append(rhs);
2136   return result;
2137 }
2138
2139 // C++11 21.4.8.1/7
2140 template <typename E, class T, class A, class S>
2141 inline
2142 basic_fbstring<E, T, A, S> operator+(
2143   E lhs,
2144   const basic_fbstring<E, T, A, S>& rhs) {
2145
2146   basic_fbstring<E, T, A, S> result;
2147   result.reserve(1 + rhs.size());
2148   result.push_back(lhs);
2149   result.append(rhs);
2150   return result;
2151 }
2152
2153 // C++11 21.4.8.1/8
2154 template <typename E, class T, class A, class S>
2155 inline
2156 basic_fbstring<E, T, A, S> operator+(
2157   E lhs,
2158   basic_fbstring<E, T, A, S>&& rhs) {
2159   //
2160   if (rhs.capacity() > rhs.size()) {
2161     // Good, at least we don't need to reallocate
2162     return std::move(rhs.insert(rhs.begin(), lhs));
2163   }
2164   // Meh, no go. Forward to operator+(E, const&).
2165   auto const& rhsC = rhs;
2166   return lhs + rhsC;
2167 }
2168
2169 // C++11 21.4.8.1/9
2170 template <typename E, class T, class A, class S>
2171 inline
2172 basic_fbstring<E, T, A, S> operator+(
2173   const basic_fbstring<E, T, A, S>& lhs,
2174   const E* rhs) {
2175
2176   typedef typename basic_fbstring<E, T, A, S>::size_type size_type;
2177   typedef typename basic_fbstring<E, T, A, S>::traits_type traits_type;
2178
2179   basic_fbstring<E, T, A, S> result;
2180   const size_type len = traits_type::length(rhs);
2181   result.reserve(lhs.size() + len);
2182   result.append(lhs).append(rhs, len);
2183   return result;
2184 }
2185
2186 // C++11 21.4.8.1/10
2187 template <typename E, class T, class A, class S>
2188 inline
2189 basic_fbstring<E, T, A, S> operator+(
2190   basic_fbstring<E, T, A, S>&& lhs,
2191   const E* rhs) {
2192   //
2193   return std::move(lhs += rhs);
2194 }
2195
2196 // C++11 21.4.8.1/11
2197 template <typename E, class T, class A, class S>
2198 inline
2199 basic_fbstring<E, T, A, S> operator+(
2200   const basic_fbstring<E, T, A, S>& lhs,
2201   E rhs) {
2202
2203   basic_fbstring<E, T, A, S> result;
2204   result.reserve(lhs.size() + 1);
2205   result.append(lhs);
2206   result.push_back(rhs);
2207   return result;
2208 }
2209
2210 // C++11 21.4.8.1/12
2211 template <typename E, class T, class A, class S>
2212 inline
2213 basic_fbstring<E, T, A, S> operator+(
2214   basic_fbstring<E, T, A, S>&& lhs,
2215   E rhs) {
2216   //
2217   return std::move(lhs += rhs);
2218 }
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 basic_fbstring<E, T, A, S>& rhs) {
2224   return lhs.size() == rhs.size() && 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 == lhs; }
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 typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2236   return lhs.compare(rhs) == 0; }
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 basic_fbstring<E, T, A, S>& rhs) {
2242   return !(lhs == rhs); }
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 !(lhs == rhs); }
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 typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2254   return !(lhs == rhs); }
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 basic_fbstring<E, T, A, S>& rhs) {
2260   return lhs.compare(rhs) < 0; }
2261
2262 template <typename E, class T, class A, class S>
2263 inline
2264 bool operator<(const basic_fbstring<E, T, A, S>& lhs,
2265                const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2266   return lhs.compare(rhs) < 0; }
2267
2268 template <typename E, class T, class A, class S>
2269 inline
2270 bool operator<(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2271                const basic_fbstring<E, T, A, S>& rhs) {
2272   return rhs.compare(lhs) > 0; }
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 basic_fbstring<E, T, A, S>& rhs) {
2278   return rhs < lhs; }
2279
2280 template <typename E, class T, class A, class S>
2281 inline
2282 bool operator>(const basic_fbstring<E, T, A, S>& lhs,
2283                const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2284   return rhs < lhs; }
2285
2286 template <typename E, class T, class A, class S>
2287 inline
2288 bool operator>(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2289                const basic_fbstring<E, T, A, S>& rhs) {
2290   return rhs < lhs; }
2291
2292 template <typename E, class T, class A, class S>
2293 inline
2294 bool operator<=(const basic_fbstring<E, T, A, S>& lhs,
2295                 const basic_fbstring<E, T, A, S>& rhs) {
2296   return !(rhs < lhs); }
2297
2298 template <typename E, class T, class A, class S>
2299 inline
2300 bool operator<=(const basic_fbstring<E, T, A, S>& lhs,
2301                 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2302   return !(rhs < lhs); }
2303
2304 template <typename E, class T, class A, class S>
2305 inline
2306 bool operator<=(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2307                 const basic_fbstring<E, T, A, S>& rhs) {
2308   return !(rhs < lhs); }
2309
2310 template <typename E, class T, class A, class S>
2311 inline
2312 bool operator>=(const basic_fbstring<E, T, A, S>& lhs,
2313                 const basic_fbstring<E, T, A, S>& rhs) {
2314   return !(lhs < rhs); }
2315
2316 template <typename E, class T, class A, class S>
2317 inline
2318 bool operator>=(const basic_fbstring<E, T, A, S>& lhs,
2319                 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2320   return !(lhs < rhs); }
2321
2322 template <typename E, class T, class A, class S>
2323 inline
2324 bool operator>=(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2325                 const basic_fbstring<E, T, A, S>& rhs) {
2326  return !(lhs < rhs);
2327 }
2328
2329 // C++11 21.4.8.8
2330 template <typename E, class T, class A, class S>
2331 void swap(basic_fbstring<E, T, A, S>& lhs, basic_fbstring<E, T, A, S>& rhs) {
2332   lhs.swap(rhs);
2333 }
2334
2335 // TODO: make this faster.
2336 template <typename E, class T, class A, class S>
2337 inline
2338 std::basic_istream<
2339   typename basic_fbstring<E, T, A, S>::value_type,
2340   typename basic_fbstring<E, T, A, S>::traits_type>&
2341   operator>>(
2342     std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2343     typename basic_fbstring<E, T, A, S>::traits_type>& is,
2344     basic_fbstring<E, T, A, S>& str) {
2345   typename std::basic_istream<E, T>::sentry sentry(is);
2346   typedef std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2347                              typename basic_fbstring<E, T, A, S>::traits_type>
2348                         __istream_type;
2349   typedef typename __istream_type::ios_base __ios_base;
2350   size_t extracted = 0;
2351   auto err = __ios_base::goodbit;
2352   if (sentry) {
2353     auto n = is.width();
2354     if (n <= 0) {
2355       n = str.max_size();
2356     }
2357     str.erase();
2358     for (auto got = is.rdbuf()->sgetc(); extracted != size_t(n); ++extracted) {
2359       if (got == T::eof()) {
2360         err |= __ios_base::eofbit;
2361         is.width(0);
2362         break;
2363       }
2364       if (isspace(got)) break;
2365       str.push_back(got);
2366       got = is.rdbuf()->snextc();
2367     }
2368   }
2369   if (!extracted) {
2370     err |= __ios_base::failbit;
2371   }
2372   if (err) {
2373     is.setstate(err);
2374   }
2375   return is;
2376 }
2377
2378 template <typename E, class T, class A, class S>
2379 inline
2380 std::basic_ostream<typename basic_fbstring<E, T, A, S>::value_type,
2381                    typename basic_fbstring<E, T, A, S>::traits_type>&
2382 operator<<(
2383   std::basic_ostream<typename basic_fbstring<E, T, A, S>::value_type,
2384   typename basic_fbstring<E, T, A, S>::traits_type>& os,
2385     const basic_fbstring<E, T, A, S>& str) {
2386 #if _LIBCPP_VERSION
2387   typename std::basic_ostream<
2388     typename basic_fbstring<E, T, A, S>::value_type,
2389     typename basic_fbstring<E, T, A, S>::traits_type>::sentry __s(os);
2390   if (__s) {
2391     typedef std::ostreambuf_iterator<
2392       typename basic_fbstring<E, T, A, S>::value_type,
2393       typename basic_fbstring<E, T, A, S>::traits_type> _Ip;
2394     size_t __len = str.size();
2395     bool __left =
2396       (os.flags() & std::ios_base::adjustfield) == std::ios_base::left;
2397     if (__pad_and_output(_Ip(os),
2398                          str.data(),
2399                          __left ? str.data() + __len : str.data(),
2400                          str.data() + __len,
2401                          os,
2402                          os.fill()).failed()) {
2403       os.setstate(std::ios_base::badbit | std::ios_base::failbit);
2404     }
2405   }
2406 #elif defined(_MSC_VER)
2407   // MSVC doesn't define __ostream_insert
2408   os.write(str.data(), str.size());
2409 #else
2410   std::__ostream_insert(os, str.data(), str.size());
2411 #endif
2412   return os;
2413 }
2414
2415 #ifndef _LIBSTDCXX_FBSTRING
2416
2417 template <typename E, class T, class A, class S>
2418 inline
2419 std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2420                    typename basic_fbstring<E, T, A, S>::traits_type>&
2421 getline(
2422   std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2423   typename basic_fbstring<E, T, A, S>::traits_type>& is,
2424     basic_fbstring<E, T, A, S>& str,
2425   typename basic_fbstring<E, T, A, S>::value_type delim) {
2426   // Use the nonstandard getdelim()
2427   char * buf = nullptr;
2428   size_t size = 0;
2429   for (;;) {
2430     // This looks quadratic but it really depends on realloc
2431     auto const newSize = size + 128;
2432     buf = static_cast<char*>(checkedRealloc(buf, newSize));
2433     is.getline(buf + size, newSize - size, delim);
2434     if (is.bad() || is.eof() || !is.fail()) {
2435       // done by either failure, end of file, or normal read
2436       size += std::strlen(buf + size);
2437       break;
2438     }
2439     // Here we have failed due to too short a buffer
2440     // Minus one to discount the terminating '\0'
2441     size = newSize - 1;
2442     assert(buf[size] == 0);
2443     // Clear the error so we can continue reading
2444     is.clear();
2445   }
2446   basic_fbstring<E, T, A, S> result(buf, size, size + 1,
2447                                     AcquireMallocatedString());
2448   result.swap(str);
2449   return is;
2450 }
2451
2452 template <typename E, class T, class A, class S>
2453 inline
2454 std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2455                    typename basic_fbstring<E, T, A, S>::traits_type>&
2456 getline(
2457   std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2458   typename basic_fbstring<E, T, A, S>::traits_type>& is,
2459   basic_fbstring<E, T, A, S>& str) {
2460   // Just forward to the version with a delimiter
2461   return getline(is, str, '\n');
2462 }
2463
2464 #endif
2465
2466 template <typename E1, class T, class A, class S>
2467 const typename basic_fbstring<E1, T, A, S>::size_type
2468 basic_fbstring<E1, T, A, S>::npos =
2469               static_cast<typename basic_fbstring<E1, T, A, S>::size_type>(-1);
2470
2471 #ifndef _LIBSTDCXX_FBSTRING
2472 // basic_string compatibility routines
2473
2474 template <typename E, class T, class A, class S>
2475 inline
2476 bool operator==(const basic_fbstring<E, T, A, S>& lhs,
2477                 const std::string& rhs) {
2478   return lhs.compare(0, lhs.size(), rhs.data(), rhs.size()) == 0;
2479 }
2480
2481 template <typename E, class T, class A, class S>
2482 inline
2483 bool operator==(const std::string& lhs,
2484                 const basic_fbstring<E, T, A, S>& rhs) {
2485   return rhs == lhs;
2486 }
2487
2488 template <typename E, class T, class A, class S>
2489 inline
2490 bool operator!=(const basic_fbstring<E, T, A, S>& lhs,
2491                 const std::string& rhs) {
2492   return !(lhs == rhs);
2493 }
2494
2495 template <typename E, class T, class A, class S>
2496 inline
2497 bool operator!=(const std::string& lhs,
2498                 const basic_fbstring<E, T, A, S>& rhs) {
2499   return !(lhs == rhs);
2500 }
2501
2502 #if !defined(_LIBSTDCXX_FBSTRING)
2503 typedef basic_fbstring<char> fbstring;
2504 #endif
2505
2506 // fbstring is relocatable
2507 template <class T, class R, class A, class S>
2508 FOLLY_ASSUME_RELOCATABLE(basic_fbstring<T, R, A, S>);
2509
2510 #else
2511 _GLIBCXX_END_NAMESPACE_VERSION
2512 #endif
2513
2514 } // namespace folly
2515
2516 #ifndef _LIBSTDCXX_FBSTRING
2517
2518 // Hash functions to make fbstring usable with e.g. hash_map
2519 //
2520 // Handle interaction with different C++ standard libraries, which
2521 // expect these types to be in different namespaces.
2522
2523 #define FOLLY_FBSTRING_HASH1(T) \
2524   template <> \
2525   struct hash< ::folly::basic_fbstring<T> > { \
2526     size_t operator()(const ::folly::fbstring& s) const { \
2527       return ::folly::hash::fnv32_buf(s.data(), s.size()); \
2528     } \
2529   };
2530
2531 // The C++11 standard says that these four are defined
2532 #define FOLLY_FBSTRING_HASH \
2533   FOLLY_FBSTRING_HASH1(char) \
2534   FOLLY_FBSTRING_HASH1(char16_t) \
2535   FOLLY_FBSTRING_HASH1(char32_t) \
2536   FOLLY_FBSTRING_HASH1(wchar_t)
2537
2538 namespace std {
2539
2540 FOLLY_FBSTRING_HASH
2541
2542 }  // namespace std
2543
2544 #if FOLLY_HAVE_DEPRECATED_ASSOC
2545 #if defined(_GLIBCXX_SYMVER) && !defined(__BIONIC__)
2546 namespace __gnu_cxx {
2547
2548 FOLLY_FBSTRING_HASH
2549
2550 }  // namespace __gnu_cxx
2551 #endif // _GLIBCXX_SYMVER && !__BIONIC__
2552 #endif // FOLLY_HAVE_DEPRECATED_ASSOC
2553
2554 #undef FOLLY_FBSTRING_HASH
2555 #undef FOLLY_FBSTRING_HASH1
2556
2557 #endif // _LIBSTDCXX_FBSTRING
2558
2559 #pragma GCC diagnostic pop
2560
2561 #undef FBSTRING_DISABLE_ADDRESS_SANITIZER
2562 #undef throw
2563 #undef FBSTRING_LIKELY
2564 #undef FBSTRING_UNLIKELY
2565
2566 #endif // FOLLY_BASE_FBSTRING_H_