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