2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 // @author: Andrei Alexandrescu (aalexandre)
26 #include <type_traits>
28 // This file appears in two locations: inside fbcode and in the
29 // libstdc++ source code (when embedding fbstring as std::string).
30 // To aid in this schizophrenic use, _LIBSTDCXX_FBSTRING is defined in
31 // libstdc++'s c++config.h, to gate use inside fbcode v. libstdc++.
32 #ifdef _LIBSTDCXX_FBSTRING
34 #pragma GCC system_header
36 #include "basic_fbstring_malloc.h"
38 // When used as std::string replacement always disable assertions.
39 #define FBSTRING_ASSERT(expr) /* empty */
41 #else // !_LIBSTDCXX_FBSTRING
43 #include <folly/CppAttributes.h>
44 #include <folly/Portability.h>
46 // libc++ doesn't provide this header, nor does msvc
47 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
48 #include <bits/c++config.h>
57 #include <folly/Hash.h>
58 #include <folly/Malloc.h>
59 #include <folly/Traits.h>
60 #include <folly/portability/BitsFunctexcept.h>
62 // When used in folly, assertions are not disabled.
63 #define FBSTRING_ASSERT(expr) assert(expr)
67 // We defined these here rather than including Likely.h to avoid
68 // redefinition errors when fbstring is imported into libstdc++.
69 #if defined(__GNUC__) && __GNUC__ >= 4
70 #define FBSTRING_LIKELY(x) (__builtin_expect((x), 1))
71 #define FBSTRING_UNLIKELY(x) (__builtin_expect((x), 0))
73 #define FBSTRING_LIKELY(x) (x)
74 #define FBSTRING_UNLIKELY(x) (x)
78 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
79 FOLLY_GCC_DISABLE_WARNING("-Wshadow")
80 // GCC 4.9 has a false positive in setSmallSize (probably
81 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59124), disable
82 // compile-time array bound checking.
83 FOLLY_GCC_DISABLE_WARNING("-Warray-bounds")
85 // FBString cannot use throw when replacing std::string, though it may still
88 #define throw FOLLY_FBSTRING_MAY_NOT_USE_THROW
90 #ifdef _LIBSTDCXX_FBSTRING
91 namespace std _GLIBCXX_VISIBILITY(default) {
92 _GLIBCXX_BEGIN_NAMESPACE_VERSION
97 #if defined(__clang__)
98 # if __has_feature(address_sanitizer)
99 # define FBSTRING_SANITIZE_ADDRESS
101 #elif defined (__GNUC__) && \
102 (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ >= 5)) && \
104 # define FBSTRING_SANITIZE_ADDRESS
107 // When compiling with ASan, always heap-allocate the string even if
108 // it would fit in-situ, so that ASan can detect access to the string
109 // buffer after it has been invalidated (destroyed, resized, etc.).
110 // Note that this flag doesn't remove support for in-situ strings, as
111 // that would break ABI-compatibility and wouldn't allow linking code
112 // compiled with this flag with code compiled without.
113 #ifdef FBSTRING_SANITIZE_ADDRESS
114 # define FBSTRING_DISABLE_SSO true
116 # define FBSTRING_DISABLE_SSO false
119 namespace fbstring_detail {
121 template <class InIt, class OutIt>
122 inline std::pair<InIt, OutIt> copy_n(
124 typename std::iterator_traits<InIt>::difference_type n,
126 for (; n != 0; --n, ++b, ++d) {
129 return std::make_pair(b, d);
132 template <class Pod, class T>
133 inline void podFill(Pod* b, Pod* e, T c) {
134 FBSTRING_ASSERT(b && e && b <= e);
135 constexpr auto kUseMemset = sizeof(T) == 1;
136 /* static */ if (kUseMemset) {
137 memset(b, c, size_t(e - b));
139 auto const ee = b + ((e - b) & ~7u);
140 for (; b != ee; b += 8) {
151 for (; b != e; ++b) {
158 * Lightly structured memcpy, simplifies copying PODs and introduces
159 * some asserts. Unfortunately using this function may cause
160 * measurable overhead (presumably because it adjusts from a begin/end
161 * convention to a pointer/size convention, so it does some extra
162 * arithmetic even though the caller might have done the inverse
163 * adaptation outside).
166 inline void podCopy(const Pod* b, const Pod* e, Pod* d) {
167 FBSTRING_ASSERT(b != nullptr);
168 FBSTRING_ASSERT(e != nullptr);
169 FBSTRING_ASSERT(d != nullptr);
170 FBSTRING_ASSERT(e >= b);
171 FBSTRING_ASSERT(d >= e || d + (e - b) <= b);
172 memcpy(d, b, (e - b) * sizeof(Pod));
176 * Lightly structured memmove, simplifies copying PODs and introduces
180 inline void podMove(const Pod* b, const Pod* e, Pod* d) {
181 FBSTRING_ASSERT(e >= b);
182 memmove(d, b, (e - b) * sizeof(*b));
186 #if defined(__GNUC__) // Clang also defines __GNUC__
187 # define FBSTRING_ALWAYS_INLINE inline __attribute__((__always_inline__))
188 #elif defined(_MSC_VER)
189 # define FBSTRING_ALWAYS_INLINE __forceinline
191 # define FBSTRING_ALWAYS_INLINE inline
194 [[noreturn]] FBSTRING_ALWAYS_INLINE void assume_unreachable() {
195 #if defined(__GNUC__) // Clang also defines __GNUC__
196 __builtin_unreachable();
197 #elif defined(_MSC_VER)
200 // Well, it's better than nothing.
205 } // namespace fbstring_detail
208 * Defines a special acquisition method for constructing fbstring
209 * objects. AcquireMallocatedString means that the user passes a
210 * pointer to a malloc-allocated string that the fbstring object will
213 enum class AcquireMallocatedString {};
216 * fbstring_core_model is a mock-up type that defines all required
217 * signatures of a fbstring core. The fbstring class itself uses such
218 * a core object to implement all of the numerous member functions
219 * required by the standard.
221 * If you want to define a new core, copy the definition below and
222 * implement the primitives. Then plug the core into basic_fbstring as
223 * a template argument.
225 template <class Char>
226 class fbstring_core_model {
228 fbstring_core_model();
229 fbstring_core_model(const fbstring_core_model &);
230 ~fbstring_core_model();
231 // Returns a pointer to string's buffer (currently only contiguous
232 // strings are supported). The pointer is guaranteed to be valid
233 // until the next call to a non-const member function.
234 const Char * data() const;
235 // Much like data(), except the string is prepared to support
236 // character-level changes. This call is a signal for
237 // e.g. reference-counted implementation to fork the data. The
238 // pointer is guaranteed to be valid until the next call to a
239 // non-const member function.
241 // Returns a pointer to string's buffer and guarantees that a
242 // readable '\0' lies right after the buffer. The pointer is
243 // guaranteed to be valid until the next call to a non-const member
245 const Char * c_str() const;
246 // Shrinks the string by delta characters. Asserts that delta <=
248 void shrink(size_t delta);
249 // Expands the string by delta characters (i.e. after this call
250 // size() will report the old size() plus delta) but without
251 // initializing the expanded region. The expanded region is
252 // zero-terminated. Returns a pointer to the memory to be
253 // initialized (the beginning of the expanded portion). The caller
254 // is expected to fill the expanded area appropriately.
255 // If expGrowth is true, exponential growth is guaranteed.
256 // It is not guaranteed not to reallocate even if size() + delta <
257 // capacity(), so all references to the buffer are invalidated.
258 Char* expandNoinit(size_t delta, bool expGrowth);
259 // Expands the string by one character and sets the last character
261 void push_back(Char c);
262 // Returns the string's size.
264 // Returns the string's capacity, i.e. maximum size that the string
265 // can grow to without reallocation. Note that for reference counted
266 // strings that's technically a lie - even assigning characters
267 // within the existing size would cause a reallocation.
268 size_t capacity() const;
269 // Returns true if the data underlying the string is actually shared
270 // across multiple strings (in a refcounted fashion).
271 bool isShared() const;
272 // Makes sure that at least minCapacity characters are available for
273 // the string without reallocation. For reference-counted strings,
274 // it should fork the data even if minCapacity < size().
275 void reserve(size_t minCapacity);
278 fbstring_core_model& operator=(const fbstring_core_model &);
283 * This is the core of the string. The code should work on 32- and
284 * 64-bit and both big- and little-endianan architectures with any
287 * The storage is selected as follows (assuming we store one-byte
288 * characters on a 64-bit machine): (a) "small" strings between 0 and
289 * 23 chars are stored in-situ without allocation (the rightmost byte
290 * stores the size); (b) "medium" strings from 24 through 254 chars
291 * are stored in malloc-allocated memory that is copied eagerly; (c)
292 * "large" strings of 255 chars and above are stored in a similar
293 * structure as medium arrays, except that the string is
294 * reference-counted and copied lazily. the reference count is
295 * allocated right before the character array.
297 * The discriminator between these three strategies sits in two
298 * bits of the rightmost char of the storage. If neither is set, then the
299 * string is small (and its length sits in the lower-order bits on
300 * little-endian or the high-order bits on big-endian of that
301 * rightmost character). If the MSb is set, the string is medium width.
302 * If the second MSb is set, then the string is large. On little-endian,
303 * these 2 bits are the 2 MSbs of MediumLarge::capacity_, while on
304 * big-endian, these 2 bits are the 2 LSbs. This keeps both little-endian
305 * and big-endian fbstring_core equivalent with merely different ops used
306 * to extract capacity/category.
308 template <class Char> class fbstring_core {
310 // It's MSVC, so we just have to guess ... and allow an override
312 # ifdef FOLLY_ENDIAN_BE
313 static constexpr auto kIsLittleEndian = false;
315 static constexpr auto kIsLittleEndian = true;
318 static constexpr auto kIsLittleEndian =
319 __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__;
322 fbstring_core() noexcept { reset(); }
324 fbstring_core(const fbstring_core & rhs) {
325 FBSTRING_ASSERT(&rhs != this);
326 switch (rhs.category()) {
327 case Category::isSmall:
330 case Category::isMedium:
333 case Category::isLarge:
337 fbstring_detail::assume_unreachable();
339 FBSTRING_ASSERT(size() == rhs.size());
340 FBSTRING_ASSERT(memcmp(data(), rhs.data(), size() * sizeof(Char)) == 0);
343 fbstring_core(fbstring_core&& goner) noexcept {
346 // Clean goner's carcass
350 fbstring_core(const Char *const data,
352 bool disableSSO = FBSTRING_DISABLE_SSO) {
353 if (!disableSSO && size <= maxSmallSize) {
354 initSmall(data, size);
355 } else if (size <= maxMediumSize) {
356 initMedium(data, size);
358 initLarge(data, size);
360 FBSTRING_ASSERT(this->size() == size);
362 size == 0 || memcmp(this->data(), data, size * sizeof(Char)) == 0);
365 ~fbstring_core() noexcept {
366 if (category() == Category::isSmall) {
369 destroyMediumLarge();
372 // Snatches a previously mallocated string. The parameter "size"
373 // is the size of the string, and the parameter "allocatedSize"
374 // is the size of the mallocated block. The string must be
375 // \0-terminated, so allocatedSize >= size + 1 and data[size] == '\0'.
377 // So if you want a 2-character string, pass malloc(3) as "data",
378 // pass 2 as "size", and pass 3 as "allocatedSize".
379 fbstring_core(Char * const data,
381 const size_t allocatedSize,
382 AcquireMallocatedString) {
384 FBSTRING_ASSERT(allocatedSize >= size + 1);
385 FBSTRING_ASSERT(data[size] == '\0');
386 // Use the medium string storage
389 // Don't forget about null terminator
390 ml_.setCapacity(allocatedSize - 1, Category::isMedium);
392 // No need for the memory
398 // swap below doesn't test whether &rhs == this (and instead
399 // potentially does extra work) on the premise that the rarity of
400 // that situation actually makes the check more expensive than is
402 void swap(fbstring_core & rhs) {
408 // In C++11 data() and c_str() are 100% equivalent.
409 const Char * data() const {
413 Char* mutableData() {
414 switch (category()) {
415 case Category::isSmall:
417 case Category::isMedium:
419 case Category::isLarge:
420 return mutableDataLarge();
422 fbstring_detail::assume_unreachable();
425 const Char* c_str() const {
426 const Char* ptr = ml_.data_;
427 // With this syntax, GCC and Clang generate a CMOV instead of a branch.
428 ptr = (category() == Category::isSmall) ? small_ : ptr;
432 void shrink(const size_t delta) {
433 if (category() == Category::isSmall) {
435 } else if (category() == Category::isMedium ||
436 RefCounted::refs(ml_.data_) == 1) {
443 FOLLY_MALLOC_NOINLINE
444 void reserve(size_t minCapacity, bool disableSSO = FBSTRING_DISABLE_SSO) {
445 switch (category()) {
446 case Category::isSmall:
447 reserveSmall(minCapacity, disableSSO);
449 case Category::isMedium:
450 reserveMedium(minCapacity);
452 case Category::isLarge:
453 reserveLarge(minCapacity);
456 fbstring_detail::assume_unreachable();
458 FBSTRING_ASSERT(capacity() >= minCapacity);
463 bool expGrowth = false,
464 bool disableSSO = FBSTRING_DISABLE_SSO);
466 void push_back(Char c) {
467 *expandNoinit(1, /* expGrowth = */ true) = c;
470 size_t size() const {
471 size_t ret = ml_.size_;
472 /* static */ if (kIsLittleEndian) {
473 // We can save a couple instructions, because the category is
474 // small iff the last char, as unsigned, is <= maxSmallSize.
475 typedef typename std::make_unsigned<Char>::type UChar;
476 auto maybeSmallSize = size_t(maxSmallSize) -
477 size_t(static_cast<UChar>(small_[maxSmallSize]));
478 // With this syntax, GCC and Clang generate a CMOV instead of a branch.
479 ret = (static_cast<ssize_t>(maybeSmallSize) >= 0) ? maybeSmallSize : ret;
481 ret = (category() == Category::isSmall) ? smallSize() : ret;
486 size_t capacity() const {
487 switch (category()) {
488 case Category::isSmall:
490 case Category::isLarge:
491 // For large-sized strings, a multi-referenced chunk has no
492 // available capacity. This is because any attempt to append
493 // data would trigger a new allocation.
494 if (RefCounted::refs(ml_.data_) > 1) {
501 return ml_.capacity();
504 bool isShared() const {
505 return category() == Category::isLarge && RefCounted::refs(ml_.data_) > 1;
510 fbstring_core & operator=(const fbstring_core & rhs);
516 FOLLY_MALLOC_NOINLINE void destroyMediumLarge() noexcept {
517 auto const c = category();
518 FBSTRING_ASSERT(c != Category::isSmall);
519 if (c == Category::isMedium) {
522 RefCounted::decrementRefs(ml_.data_);
527 std::atomic<size_t> refCount_;
530 constexpr static size_t getDataOffset() {
531 return offsetof(RefCounted, data_);
534 static RefCounted * fromData(Char * p) {
535 return static_cast<RefCounted*>(static_cast<void*>(
536 static_cast<unsigned char*>(static_cast<void*>(p)) -
540 static size_t refs(Char * p) {
541 return fromData(p)->refCount_.load(std::memory_order_acquire);
544 static void incrementRefs(Char * p) {
545 fromData(p)->refCount_.fetch_add(1, std::memory_order_acq_rel);
548 static void decrementRefs(Char * p) {
549 auto const dis = fromData(p);
550 size_t oldcnt = dis->refCount_.fetch_sub(1, std::memory_order_acq_rel);
551 FBSTRING_ASSERT(oldcnt > 0);
557 static RefCounted * create(size_t * size) {
558 const size_t allocSize =
559 goodMallocSize(getDataOffset() + (*size + 1) * sizeof(Char));
560 auto result = static_cast<RefCounted*>(checkedMalloc(allocSize));
561 result->refCount_.store(1, std::memory_order_release);
562 *size = (allocSize - getDataOffset()) / sizeof(Char) - 1;
566 static RefCounted * create(const Char * data, size_t * size) {
567 const size_t effectiveSize = *size;
568 auto result = create(size);
569 if (FBSTRING_LIKELY(effectiveSize > 0)) {
570 fbstring_detail::podCopy(data, data + effectiveSize, result->data_);
575 static RefCounted * reallocate(Char *const data,
576 const size_t currentSize,
577 const size_t currentCapacity,
578 size_t * newCapacity) {
579 FBSTRING_ASSERT(*newCapacity > 0 && *newCapacity > currentSize);
580 const size_t allocNewCapacity =
581 goodMallocSize(getDataOffset() + (*newCapacity + 1) * sizeof(Char));
582 auto const dis = fromData(data);
583 FBSTRING_ASSERT(dis->refCount_.load(std::memory_order_acquire) == 1);
584 auto result = static_cast<RefCounted*>(smartRealloc(
586 getDataOffset() + (currentSize + 1) * sizeof(Char),
587 getDataOffset() + (currentCapacity + 1) * sizeof(Char),
589 FBSTRING_ASSERT(result->refCount_.load(std::memory_order_acquire) == 1);
590 *newCapacity = (allocNewCapacity - getDataOffset()) / sizeof(Char) - 1;
595 typedef uint8_t category_type;
597 enum class Category : category_type {
599 isMedium = kIsLittleEndian ? 0x80 : 0x2,
600 isLarge = kIsLittleEndian ? 0x40 : 0x1,
603 Category category() const {
604 // works for both big-endian and little-endian
605 return static_cast<Category>(bytes_[lastChar] & categoryExtractMask);
613 size_t capacity() const {
614 return kIsLittleEndian
615 ? capacity_ & capacityExtractMask
619 void setCapacity(size_t cap, Category cat) {
620 capacity_ = kIsLittleEndian
621 ? cap | (static_cast<size_t>(cat) << kCategoryShift)
622 : (cap << 2) | static_cast<size_t>(cat);
627 uint8_t bytes_[sizeof(MediumLarge)]; // For accessing the last byte.
628 Char small_[sizeof(MediumLarge) / sizeof(Char)];
632 constexpr static size_t lastChar = sizeof(MediumLarge) - 1;
633 constexpr static size_t maxSmallSize = lastChar / sizeof(Char);
634 constexpr static size_t maxMediumSize = 254 / sizeof(Char);
635 constexpr static uint8_t categoryExtractMask = kIsLittleEndian ? 0xC0 : 0x3;
636 constexpr static size_t kCategoryShift = (sizeof(size_t) - 1) * 8;
637 constexpr static size_t capacityExtractMask = kIsLittleEndian
638 ? ~(size_t(categoryExtractMask) << kCategoryShift)
641 static_assert(!(sizeof(MediumLarge) % sizeof(Char)),
642 "Corrupt memory layout for fbstring.");
644 size_t smallSize() const {
645 FBSTRING_ASSERT(category() == Category::isSmall);
646 constexpr auto shift = kIsLittleEndian ? 0 : 2;
647 auto smallShifted = static_cast<size_t>(small_[maxSmallSize]) >> shift;
648 FBSTRING_ASSERT(static_cast<size_t>(maxSmallSize) >= smallShifted);
649 return static_cast<size_t>(maxSmallSize) - smallShifted;
652 void setSmallSize(size_t s) {
653 // Warning: this should work with uninitialized strings too,
654 // so don't assume anything about the previous value of
655 // small_[maxSmallSize].
656 FBSTRING_ASSERT(s <= maxSmallSize);
657 constexpr auto shift = kIsLittleEndian ? 0 : 2;
658 small_[maxSmallSize] = char((maxSmallSize - s) << shift);
660 FBSTRING_ASSERT(category() == Category::isSmall && size() == s);
663 void copySmall(const fbstring_core&);
664 void copyMedium(const fbstring_core&);
665 void copyLarge(const fbstring_core&);
667 void initSmall(const Char* data, size_t size);
668 void initMedium(const Char* data, size_t size);
669 void initLarge(const Char* data, size_t size);
671 void reserveSmall(size_t minCapacity, bool disableSSO);
672 void reserveMedium(size_t minCapacity);
673 void reserveLarge(size_t minCapacity);
675 void shrinkSmall(size_t delta);
676 void shrinkMedium(size_t delta);
677 void shrinkLarge(size_t delta);
679 void unshare(size_t minCapacity = 0);
680 Char* mutableDataLarge();
683 template <class Char>
684 inline void fbstring_core<Char>::copySmall(const fbstring_core& rhs) {
685 static_assert(offsetof(MediumLarge, data_) == 0, "fbstring layout failure");
687 offsetof(MediumLarge, size_) == sizeof(ml_.data_),
688 "fbstring layout failure");
690 offsetof(MediumLarge, capacity_) == 2 * sizeof(ml_.data_),
691 "fbstring layout failure");
692 // Just write the whole thing, don't look at details. In
693 // particular we need to copy capacity anyway because we want
694 // to set the size (don't forget that the last character,
695 // which stores a short string's length, is shared with the
696 // ml_.capacity field).
699 category() == Category::isSmall && this->size() == rhs.size());
702 template <class Char>
703 FOLLY_MALLOC_NOINLINE inline void fbstring_core<Char>::copyMedium(
704 const fbstring_core& rhs) {
705 // Medium strings are copied eagerly. Don't forget to allocate
706 // one extra Char for the null terminator.
707 auto const allocSize = goodMallocSize((1 + rhs.ml_.size_) * sizeof(Char));
708 ml_.data_ = static_cast<Char*>(checkedMalloc(allocSize));
709 // Also copies terminator.
710 fbstring_detail::podCopy(
711 rhs.ml_.data_, rhs.ml_.data_ + rhs.ml_.size_ + 1, ml_.data_);
712 ml_.size_ = rhs.ml_.size_;
713 ml_.setCapacity(allocSize / sizeof(Char) - 1, Category::isMedium);
714 FBSTRING_ASSERT(category() == Category::isMedium);
717 template <class Char>
718 FOLLY_MALLOC_NOINLINE inline void fbstring_core<Char>::copyLarge(
719 const fbstring_core& rhs) {
720 // Large strings are just refcounted
722 RefCounted::incrementRefs(ml_.data_);
723 FBSTRING_ASSERT(category() == Category::isLarge && size() == rhs.size());
726 // Small strings are bitblitted
727 template <class Char>
728 inline void fbstring_core<Char>::initSmall(
729 const Char* const data, const size_t size) {
730 // Layout is: Char* data_, size_t size_, size_t capacity_
732 sizeof(*this) == sizeof(Char*) + 2 * sizeof(size_t),
733 "fbstring has unexpected size");
735 sizeof(Char*) == sizeof(size_t), "fbstring size assumption violation");
736 // sizeof(size_t) must be a power of 2
738 (sizeof(size_t) & (sizeof(size_t) - 1)) == 0,
739 "fbstring size assumption violation");
741 // If data is aligned, use fast word-wise copying. Otherwise,
742 // use conservative memcpy.
743 // The word-wise path reads bytes which are outside the range of
744 // the string, and makes ASan unhappy, so we disable it when
745 // compiling with ASan.
746 #ifndef FBSTRING_SANITIZE_ADDRESS
747 if ((reinterpret_cast<size_t>(data) & (sizeof(size_t) - 1)) == 0) {
748 const size_t byteSize = size * sizeof(Char);
749 constexpr size_t wordWidth = sizeof(size_t);
750 switch ((byteSize + wordWidth - 1) / wordWidth) { // Number of words.
752 ml_.capacity_ = reinterpret_cast<const size_t*>(data)[2];
755 ml_.size_ = reinterpret_cast<const size_t*>(data)[1];
758 ml_.data_ = *reinterpret_cast<Char**>(const_cast<Char*>(data));
767 fbstring_detail::podCopy(data, data + size, small_);
773 template <class Char>
774 FOLLY_MALLOC_NOINLINE inline void fbstring_core<Char>::initMedium(
775 const Char* const data, const size_t size) {
776 // Medium strings are allocated normally. Don't forget to
777 // allocate one extra Char for the terminating null.
778 auto const allocSize = goodMallocSize((1 + size) * sizeof(Char));
779 ml_.data_ = static_cast<Char*>(checkedMalloc(allocSize));
780 if (FBSTRING_LIKELY(size > 0)) {
781 fbstring_detail::podCopy(data, data + size, ml_.data_);
784 ml_.setCapacity(allocSize / sizeof(Char) - 1, Category::isMedium);
785 ml_.data_[size] = '\0';
788 template <class Char>
789 FOLLY_MALLOC_NOINLINE inline void fbstring_core<Char>::initLarge(
790 const Char* const data, const size_t size) {
791 // Large strings are allocated differently
792 size_t effectiveCapacity = size;
793 auto const newRC = RefCounted::create(data, &effectiveCapacity);
794 ml_.data_ = newRC->data_;
796 ml_.setCapacity(effectiveCapacity, Category::isLarge);
797 ml_.data_[size] = '\0';
800 template <class Char>
801 FOLLY_MALLOC_NOINLINE inline void fbstring_core<Char>::unshare(
802 size_t minCapacity) {
803 FBSTRING_ASSERT(category() == Category::isLarge);
804 size_t effectiveCapacity = std::max(minCapacity, ml_.capacity());
805 auto const newRC = RefCounted::create(&effectiveCapacity);
806 // If this fails, someone placed the wrong capacity in an
808 FBSTRING_ASSERT(effectiveCapacity >= ml_.capacity());
809 // Also copies terminator.
810 fbstring_detail::podCopy(ml_.data_, ml_.data_ + ml_.size_ + 1, newRC->data_);
811 RefCounted::decrementRefs(ml_.data_);
812 ml_.data_ = newRC->data_;
813 ml_.setCapacity(effectiveCapacity, Category::isLarge);
814 // size_ remains unchanged.
817 template <class Char>
818 inline Char* fbstring_core<Char>::mutableDataLarge() {
819 FBSTRING_ASSERT(category() == Category::isLarge);
820 if (RefCounted::refs(ml_.data_) > 1) { // Ensure unique.
826 template <class Char>
827 FOLLY_MALLOC_NOINLINE inline void fbstring_core<Char>::reserveLarge(
828 size_t minCapacity) {
829 FBSTRING_ASSERT(category() == Category::isLarge);
830 if (RefCounted::refs(ml_.data_) > 1) { // Ensure unique
831 // We must make it unique regardless; in-place reallocation is
832 // useless if the string is shared. In order to not surprise
833 // people, reserve the new block at current capacity or
834 // more. That way, a string's capacity never shrinks after a
836 unshare(minCapacity);
838 // String is not shared, so let's try to realloc (if needed)
839 if (minCapacity > ml_.capacity()) {
840 // Asking for more memory
841 auto const newRC = RefCounted::reallocate(
842 ml_.data_, ml_.size_, ml_.capacity(), &minCapacity);
843 ml_.data_ = newRC->data_;
844 ml_.setCapacity(minCapacity, Category::isLarge);
846 FBSTRING_ASSERT(capacity() >= minCapacity);
850 template <class Char>
851 FOLLY_MALLOC_NOINLINE inline void fbstring_core<Char>::reserveMedium(
852 const size_t minCapacity) {
853 FBSTRING_ASSERT(category() == Category::isMedium);
854 // String is not shared
855 if (minCapacity <= ml_.capacity()) {
856 return; // nothing to do, there's enough room
858 if (minCapacity <= maxMediumSize) {
859 // Keep the string at medium size. Don't forget to allocate
860 // one extra Char for the terminating null.
861 size_t capacityBytes = goodMallocSize((1 + minCapacity) * sizeof(Char));
862 // Also copies terminator.
863 ml_.data_ = static_cast<Char*>(smartRealloc(
865 (ml_.size_ + 1) * sizeof(Char),
866 (ml_.capacity() + 1) * sizeof(Char),
868 ml_.setCapacity(capacityBytes / sizeof(Char) - 1, Category::isMedium);
870 // Conversion from medium to large string
871 fbstring_core nascent;
872 // Will recurse to another branch of this function
873 nascent.reserve(minCapacity);
874 nascent.ml_.size_ = ml_.size_;
875 // Also copies terminator.
876 fbstring_detail::podCopy(
877 ml_.data_, ml_.data_ + ml_.size_ + 1, nascent.ml_.data_);
879 FBSTRING_ASSERT(capacity() >= minCapacity);
883 template <class Char>
884 FOLLY_MALLOC_NOINLINE inline void fbstring_core<Char>::reserveSmall(
885 size_t minCapacity, const bool disableSSO) {
886 FBSTRING_ASSERT(category() == Category::isSmall);
887 if (!disableSSO && minCapacity <= maxSmallSize) {
889 // Nothing to do, everything stays put
890 } else if (minCapacity <= maxMediumSize) {
892 // Don't forget to allocate one extra Char for the terminating null
893 auto const allocSizeBytes =
894 goodMallocSize((1 + minCapacity) * sizeof(Char));
895 auto const pData = static_cast<Char*>(checkedMalloc(allocSizeBytes));
896 auto const size = smallSize();
897 // Also copies terminator.
898 fbstring_detail::podCopy(small_, small_ + size + 1, pData);
901 ml_.setCapacity(allocSizeBytes / sizeof(Char) - 1, Category::isMedium);
904 auto const newRC = RefCounted::create(&minCapacity);
905 auto const size = smallSize();
906 // Also copies terminator.
907 fbstring_detail::podCopy(small_, small_ + size + 1, newRC->data_);
908 ml_.data_ = newRC->data_;
910 ml_.setCapacity(minCapacity, Category::isLarge);
911 FBSTRING_ASSERT(capacity() >= minCapacity);
915 template <class Char>
916 inline Char* fbstring_core<Char>::expandNoinit(
918 bool expGrowth, /* = false */
919 bool disableSSO /* = FBSTRING_DISABLE_SSO */) {
920 // Strategy is simple: make room, then change size
921 FBSTRING_ASSERT(capacity() >= size());
923 if (category() == Category::isSmall) {
926 if (!disableSSO && FBSTRING_LIKELY(newSz <= maxSmallSize)) {
931 expGrowth ? std::max(newSz, 2 * maxSmallSize) : newSz, disableSSO);
935 if (FBSTRING_UNLIKELY(newSz > capacity())) {
936 // ensures not shared
937 reserve(expGrowth ? std::max(newSz, 1 + capacity() * 3 / 2) : newSz);
940 FBSTRING_ASSERT(capacity() >= newSz);
941 // Category can't be small - we took care of that above
943 category() == Category::isMedium || category() == Category::isLarge);
945 ml_.data_[newSz] = '\0';
946 FBSTRING_ASSERT(size() == newSz);
947 return ml_.data_ + sz;
950 template <class Char>
951 inline void fbstring_core<Char>::shrinkSmall(const size_t delta) {
952 // Check for underflow
953 FBSTRING_ASSERT(delta <= smallSize());
954 setSmallSize(smallSize() - delta);
957 template <class Char>
958 inline void fbstring_core<Char>::shrinkMedium(const size_t delta) {
959 // Medium strings and unique large strings need no special
961 FBSTRING_ASSERT(ml_.size_ >= delta);
963 ml_.data_[ml_.size_] = '\0';
966 template <class Char>
967 inline void fbstring_core<Char>::shrinkLarge(const size_t delta) {
968 FBSTRING_ASSERT(ml_.size_ >= delta);
969 // Shared large string, must make unique. This is because of the
970 // durn terminator must be written, which may trample the shared
973 fbstring_core(ml_.data_, ml_.size_ - delta).swap(*this);
975 // No need to write the terminator.
978 #ifndef _LIBSTDCXX_FBSTRING
980 * Dummy fbstring core that uses an actual std::string. This doesn't
981 * make any sense - it's just for testing purposes.
983 template <class Char>
984 class dummy_fbstring_core {
986 dummy_fbstring_core() {
988 dummy_fbstring_core(const dummy_fbstring_core& another)
989 : backend_(another.backend_) {
991 dummy_fbstring_core(const Char * s, size_t n)
994 void swap(dummy_fbstring_core & rhs) {
995 backend_.swap(rhs.backend_);
997 const Char * data() const {
998 return backend_.data();
1000 Char* mutableData() {
1001 return const_cast<Char*>(backend_.data());
1003 void shrink(size_t delta) {
1004 FBSTRING_ASSERT(delta <= size());
1005 backend_.resize(size() - delta);
1007 Char* expandNoinit(size_t delta) {
1008 auto const sz = size();
1009 backend_.resize(size() + delta);
1010 return backend_.data() + sz;
1012 void push_back(Char c) {
1013 backend_.push_back(c);
1015 size_t size() const {
1016 return backend_.size();
1018 size_t capacity() const {
1019 return backend_.capacity();
1021 bool isShared() const {
1024 void reserve(size_t minCapacity) {
1025 backend_.reserve(minCapacity);
1029 std::basic_string<Char> backend_;
1031 #endif // !_LIBSTDCXX_FBSTRING
1034 * This is the basic_string replacement. For conformity,
1035 * basic_fbstring takes the same template parameters, plus the last
1036 * one which is the core.
1038 #ifdef _LIBSTDCXX_FBSTRING
1039 template <typename E, class T, class A, class Storage>
1041 template <typename E,
1042 class T = std::char_traits<E>,
1043 class A = std::allocator<E>,
1044 class Storage = fbstring_core<E> >
1046 class basic_fbstring {
1047 static void enforce(
1049 void (*throw_exc)(const char*),
1056 bool isSane() const {
1059 empty() == (size() == 0) &&
1060 empty() == (begin() == end()) &&
1061 size() <= max_size() &&
1062 capacity() <= max_size() &&
1063 size() <= capacity() &&
1064 begin()[size()] == '\0';
1068 Invariant& operator=(const Invariant&) = delete;
1069 explicit Invariant(const basic_fbstring& s) noexcept : s_(s) {
1070 FBSTRING_ASSERT(s_.isSane());
1072 ~Invariant() noexcept {
1073 FBSTRING_ASSERT(s_.isSane());
1077 const basic_fbstring& s_;
1082 typedef T traits_type;
1083 typedef typename traits_type::char_type value_type;
1084 typedef A allocator_type;
1085 typedef typename A::size_type size_type;
1086 typedef typename A::difference_type difference_type;
1088 typedef typename A::reference reference;
1089 typedef typename A::const_reference const_reference;
1090 typedef typename A::pointer pointer;
1091 typedef typename A::const_pointer const_pointer;
1093 typedef E* iterator;
1094 typedef const E* const_iterator;
1095 typedef std::reverse_iterator<iterator
1096 #ifdef NO_ITERATOR_TRAITS
1100 typedef std::reverse_iterator<const_iterator
1101 #ifdef NO_ITERATOR_TRAITS
1104 > const_reverse_iterator;
1106 static constexpr size_type npos = size_type(-1);
1107 typedef std::true_type IsRelocatable;
1110 static void procrustes(size_type& n, size_type nmax) {
1116 static size_type traitsLength(const value_type* s);
1119 // C++11 21.4.2 construct/copy/destroy
1121 // Note: while the following two constructors can be (and previously were)
1122 // collapsed into one constructor written this way:
1124 // explicit basic_fbstring(const A& a = A()) noexcept { }
1126 // This can cause Clang (at least version 3.7) to fail with the error:
1127 // "chosen constructor is explicit in copy-initialization ...
1128 // in implicit initialization of field '(x)' with omitted initializer"
1130 // if used in a struct which is default-initialized. Hence the split into
1131 // these two separate constructors.
1133 basic_fbstring() noexcept : basic_fbstring(A()) {
1136 explicit basic_fbstring(const A&) noexcept {
1139 basic_fbstring(const basic_fbstring& str)
1140 : store_(str.store_) {
1144 basic_fbstring(basic_fbstring&& goner) noexcept
1145 : store_(std::move(goner.store_)) {
1148 #ifndef _LIBSTDCXX_FBSTRING
1149 // This is defined for compatibility with std::string
1150 template <typename A2>
1151 /* implicit */ basic_fbstring(const std::basic_string<E, T, A2>& str)
1152 : store_(str.data(), str.size()) {}
1155 basic_fbstring(const basic_fbstring& str,
1158 const A& /* a */ = A()) {
1159 assign(str, pos, n);
1162 FOLLY_MALLOC_NOINLINE
1163 /* implicit */ basic_fbstring(const value_type* s, const A& /*a*/ = A())
1164 : store_(s, traitsLength(s)) {}
1166 FOLLY_MALLOC_NOINLINE
1167 basic_fbstring(const value_type* s, size_type n, const A& /*a*/ = A())
1171 FOLLY_MALLOC_NOINLINE
1172 basic_fbstring(size_type n, value_type c, const A& /*a*/ = A()) {
1173 auto const pData = store_.expandNoinit(n);
1174 fbstring_detail::podFill(pData, pData + n, c);
1177 template <class InIt>
1178 FOLLY_MALLOC_NOINLINE basic_fbstring(
1181 typename std::enable_if<
1182 !std::is_same<InIt, value_type*>::value,
1183 const A>::type& /*a*/ = A()) {
1187 // Specialization for const char*, const char*
1188 FOLLY_MALLOC_NOINLINE
1189 basic_fbstring(const value_type* b, const value_type* e, const A& /*a*/ = A())
1190 : store_(b, size_type(e - b)) {
1193 // Nonstandard constructor
1194 basic_fbstring(value_type *s, size_type n, size_type c,
1195 AcquireMallocatedString a)
1196 : store_(s, n, c, a) {
1199 // Construction from initialization list
1200 FOLLY_MALLOC_NOINLINE
1201 basic_fbstring(std::initializer_list<value_type> il) {
1202 assign(il.begin(), il.end());
1205 ~basic_fbstring() noexcept {}
1207 basic_fbstring& operator=(const basic_fbstring& lhs);
1210 basic_fbstring& operator=(basic_fbstring&& goner) noexcept;
1212 #ifndef _LIBSTDCXX_FBSTRING
1213 // Compatibility with std::string
1214 template <typename A2>
1215 basic_fbstring& operator=(const std::basic_string<E, T, A2>& rhs) {
1216 return assign(rhs.data(), rhs.size());
1219 // Compatibility with std::string
1220 std::basic_string<E, T, A> toStdString() const {
1221 return std::basic_string<E, T, A>(data(), size());
1224 // A lot of code in fbcode still uses this method, so keep it here for now.
1225 const basic_fbstring& toStdString() const {
1230 basic_fbstring& operator=(const value_type* s) {
1234 // This actually goes directly against the C++ spec, but the
1235 // value_type overload is dangerous, so we're explicitly deleting
1236 // any overloads of operator= that could implicitly convert to
1238 // Note that we do need to explicitly specify the template types because
1239 // otherwise MSVC 2017 will aggressively pre-resolve value_type to
1240 // traits_type::char_type, which won't compare as equal when determining
1241 // which overload the implementation is referring to.
1242 // Also note that MSVC 2015 Update 3 requires us to explicitly specify the
1243 // namespace in-which to search for basic_fbstring, otherwise it tries to
1244 // look for basic_fbstring::basic_fbstring, which is just plain wrong.
1245 template <typename TP>
1246 typename std::enable_if<
1248 typename std::decay<TP>::type,
1249 typename folly::basic_fbstring<E, T, A, Storage>::value_type>::value,
1250 basic_fbstring<E, T, A, Storage>&>::type
1253 basic_fbstring& operator=(std::initializer_list<value_type> il) {
1254 return assign(il.begin(), il.end());
1257 // C++11 21.4.3 iterators:
1259 return store_.mutableData();
1262 const_iterator begin() const {
1263 return store_.data();
1266 const_iterator cbegin() const {
1271 return store_.mutableData() + store_.size();
1274 const_iterator end() const {
1275 return store_.data() + store_.size();
1278 const_iterator cend() const { return end(); }
1280 reverse_iterator rbegin() {
1281 return reverse_iterator(end());
1284 const_reverse_iterator rbegin() const {
1285 return const_reverse_iterator(end());
1288 const_reverse_iterator crbegin() const { return rbegin(); }
1290 reverse_iterator rend() {
1291 return reverse_iterator(begin());
1294 const_reverse_iterator rend() const {
1295 return const_reverse_iterator(begin());
1298 const_reverse_iterator crend() const { return rend(); }
1301 // C++11 21.4.5, element access:
1302 const value_type& front() const { return *begin(); }
1303 const value_type& back() const {
1304 FBSTRING_ASSERT(!empty());
1305 // Should be begin()[size() - 1], but that branches twice
1306 return *(end() - 1);
1308 value_type& front() { return *begin(); }
1309 value_type& back() {
1310 FBSTRING_ASSERT(!empty());
1311 // Should be begin()[size() - 1], but that branches twice
1312 return *(end() - 1);
1315 FBSTRING_ASSERT(!empty());
1319 // C++11 21.4.4 capacity:
1320 size_type size() const { return store_.size(); }
1322 size_type length() const { return size(); }
1324 size_type max_size() const {
1325 return std::numeric_limits<size_type>::max();
1328 void resize(size_type n, value_type c = value_type());
1330 size_type capacity() const { return store_.capacity(); }
1332 void reserve(size_type res_arg = 0) {
1333 enforce(res_arg <= max_size(), std::__throw_length_error, "");
1334 store_.reserve(res_arg);
1337 void shrink_to_fit() {
1338 // Shrink only if slack memory is sufficiently large
1339 if (capacity() < size() * 3 / 2) {
1342 basic_fbstring(cbegin(), cend()).swap(*this);
1345 void clear() { resize(0); }
1347 bool empty() const { return size() == 0; }
1349 // C++11 21.4.5 element access:
1350 const_reference operator[](size_type pos) const {
1351 return *(begin() + pos);
1354 reference operator[](size_type pos) {
1355 return *(begin() + pos);
1358 const_reference at(size_type n) const {
1359 enforce(n <= size(), std::__throw_out_of_range, "");
1363 reference at(size_type n) {
1364 enforce(n < size(), std::__throw_out_of_range, "");
1368 // C++11 21.4.6 modifiers:
1369 basic_fbstring& operator+=(const basic_fbstring& str) {
1373 basic_fbstring& operator+=(const value_type* s) {
1377 basic_fbstring& operator+=(const value_type c) {
1382 basic_fbstring& operator+=(std::initializer_list<value_type> il) {
1387 basic_fbstring& append(const basic_fbstring& str);
1390 append(const basic_fbstring& str, const size_type pos, size_type n);
1392 basic_fbstring& append(const value_type* s, size_type n);
1394 basic_fbstring& append(const value_type* s) {
1395 return append(s, traitsLength(s));
1398 basic_fbstring& append(size_type n, value_type c);
1400 template<class InputIterator>
1401 basic_fbstring& append(InputIterator first, InputIterator last) {
1402 insert(end(), first, last);
1406 basic_fbstring& append(std::initializer_list<value_type> il) {
1407 return append(il.begin(), il.end());
1410 void push_back(const value_type c) { // primitive
1411 store_.push_back(c);
1414 basic_fbstring& assign(const basic_fbstring& str) {
1415 if (&str == this) return *this;
1416 return assign(str.data(), str.size());
1419 basic_fbstring& assign(basic_fbstring&& str) {
1420 return *this = std::move(str);
1424 assign(const basic_fbstring& str, const size_type pos, size_type n);
1426 basic_fbstring& assign(const value_type* s, const size_type n);
1428 basic_fbstring& assign(const value_type* s) {
1429 return assign(s, traitsLength(s));
1432 basic_fbstring& assign(std::initializer_list<value_type> il) {
1433 return assign(il.begin(), il.end());
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);
1441 basic_fbstring& insert(size_type pos1, const basic_fbstring& str) {
1442 return insert(pos1, str.data(), str.size());
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);
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);
1458 basic_fbstring& insert(size_type pos, const value_type* s) {
1459 return insert(pos, s, traitsLength(s));
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);
1468 iterator insert(const_iterator p, const value_type c) {
1469 const size_type pos = p - cbegin();
1471 return begin() + pos;
1474 #ifndef _LIBSTDCXX_FBSTRING
1476 typedef std::basic_istream<value_type, traits_type> istream_type;
1477 istream_type& getlineImpl(istream_type& is, value_type delim);
1480 friend inline istream_type& getline(istream_type& is,
1481 basic_fbstring& str,
1483 return str.getlineImpl(is, delim);
1486 friend inline istream_type& getline(istream_type& is, basic_fbstring& str) {
1487 return getline(is, str, '\n');
1493 insertImplDiscr(const_iterator i, size_type n, value_type c, std::true_type);
1495 template <class InputIter>
1497 insertImplDiscr(const_iterator i, InputIter b, InputIter e, std::false_type);
1499 template <class FwdIterator>
1500 iterator insertImpl(
1504 std::forward_iterator_tag);
1506 template <class InputIterator>
1507 iterator insertImpl(
1511 std::input_iterator_tag);
1514 template <class ItOrLength, class ItOrChar>
1515 iterator insert(const_iterator p, ItOrLength first_or_n, ItOrChar last_or_c) {
1516 using Sel = std::integral_constant<
1518 std::numeric_limits<ItOrLength>::is_specialized>;
1519 return insertImplDiscr(p, first_or_n, last_or_c, Sel());
1522 iterator insert(const_iterator p, std::initializer_list<value_type> il) {
1523 return insert(p, il.begin(), il.end());
1526 basic_fbstring& erase(size_type pos = 0, size_type n = npos) {
1527 Invariant checker(*this);
1529 enforce(pos <= length(), std::__throw_out_of_range, "");
1530 procrustes(n, length() - pos);
1531 std::copy(begin() + pos + n, end(), begin() + pos);
1532 resize(length() - n);
1536 iterator erase(iterator position) {
1537 const size_type pos(position - begin());
1538 enforce(pos <= size(), std::__throw_out_of_range, "");
1540 return begin() + pos;
1543 iterator erase(iterator first, iterator last) {
1544 const size_type pos(first - begin());
1545 erase(pos, last - first);
1546 return begin() + pos;
1549 // Replaces at most n1 chars of *this, starting with pos1 with the
1551 basic_fbstring& replace(size_type pos1, size_type n1,
1552 const basic_fbstring& str) {
1553 return replace(pos1, n1, str.data(), str.size());
1556 // Replaces at most n1 chars of *this, starting with pos1,
1557 // with at most n2 chars of str starting with pos2
1558 basic_fbstring& replace(size_type pos1, size_type n1,
1559 const basic_fbstring& str,
1560 size_type pos2, size_type n2) {
1561 enforce(pos2 <= str.length(), std::__throw_out_of_range, "");
1562 return replace(pos1, n1, str.data() + pos2,
1563 std::min(n2, str.size() - pos2));
1566 // Replaces at most n1 chars of *this, starting with pos, with chars from s
1567 basic_fbstring& replace(size_type pos, size_type n1, const value_type* s) {
1568 return replace(pos, n1, s, traitsLength(s));
1571 // Replaces at most n1 chars of *this, starting with pos, with n2
1574 // consolidated with
1576 // Replaces at most n1 chars of *this, starting with pos, with at
1577 // most n2 chars of str. str must have at least n2 chars.
1578 template <class StrOrLength, class NumOrChar>
1579 basic_fbstring& replace(size_type pos, size_type n1,
1580 StrOrLength s_or_n2, NumOrChar n_or_c) {
1581 Invariant checker(*this);
1583 enforce(pos <= size(), std::__throw_out_of_range, "");
1584 procrustes(n1, length() - pos);
1585 const iterator b = begin() + pos;
1586 return replace(b, b + n1, s_or_n2, n_or_c);
1589 basic_fbstring& replace(iterator i1, iterator i2, const basic_fbstring& str) {
1590 return replace(i1, i2, str.data(), str.length());
1593 basic_fbstring& replace(iterator i1, iterator i2, const value_type* s) {
1594 return replace(i1, i2, s, traitsLength(s));
1598 basic_fbstring& replaceImplDiscr(
1601 const value_type* s,
1603 std::integral_constant<int, 2>);
1605 basic_fbstring& replaceImplDiscr(
1610 std::integral_constant<int, 1>);
1612 template <class InputIter>
1613 basic_fbstring& replaceImplDiscr(
1618 std::integral_constant<int, 0>);
1621 template <class FwdIterator>
1622 bool replaceAliased(iterator /* i1 */,
1624 FwdIterator /* s1 */,
1625 FwdIterator /* s2 */,
1630 template <class FwdIterator>
1631 bool replaceAliased(
1638 template <class FwdIterator>
1644 std::forward_iterator_tag);
1646 template <class InputIterator>
1652 std::input_iterator_tag);
1655 template <class T1, class T2>
1656 basic_fbstring& replace(iterator i1, iterator i2,
1657 T1 first_or_n_or_s, T2 last_or_c_or_n) {
1658 constexpr bool num1 = std::numeric_limits<T1>::is_specialized,
1659 num2 = std::numeric_limits<T2>::is_specialized;
1661 std::integral_constant<int, num1 ? (num2 ? 1 : -1) : (num2 ? 2 : 0)>;
1662 return replaceImplDiscr(i1, i2, first_or_n_or_s, last_or_c_or_n, Sel());
1665 size_type copy(value_type* s, size_type n, size_type pos = 0) const {
1666 enforce(pos <= size(), std::__throw_out_of_range, "");
1667 procrustes(n, size() - pos);
1670 fbstring_detail::podCopy(data() + pos, data() + pos + n, s);
1675 void swap(basic_fbstring& rhs) {
1676 store_.swap(rhs.store_);
1679 const value_type* c_str() const {
1680 return store_.c_str();
1683 const value_type* data() const { return c_str(); }
1685 allocator_type get_allocator() const {
1686 return allocator_type();
1689 size_type find(const basic_fbstring& str, size_type pos = 0) const {
1690 return find(str.data(), pos, str.length());
1693 size_type find(const value_type* needle, size_type pos, size_type nsize)
1696 size_type find(const value_type* s, size_type pos = 0) const {
1697 return find(s, pos, traitsLength(s));
1700 size_type find (value_type c, size_type pos = 0) const {
1701 return find(&c, pos, 1);
1704 size_type rfind(const basic_fbstring& str, size_type pos = npos) const {
1705 return rfind(str.data(), pos, str.length());
1708 size_type rfind(const value_type* s, size_type pos, size_type n) const;
1710 size_type rfind(const value_type* s, size_type pos = npos) const {
1711 return rfind(s, pos, traitsLength(s));
1714 size_type rfind(value_type c, size_type pos = npos) const {
1715 return rfind(&c, pos, 1);
1718 size_type find_first_of(const basic_fbstring& str, size_type pos = 0) const {
1719 return find_first_of(str.data(), pos, str.length());
1722 size_type find_first_of(const value_type* s, size_type pos, size_type n)
1725 size_type find_first_of(const value_type* s, size_type pos = 0) const {
1726 return find_first_of(s, pos, traitsLength(s));
1729 size_type find_first_of(value_type c, size_type pos = 0) const {
1730 return find_first_of(&c, pos, 1);
1733 size_type find_last_of(const basic_fbstring& str, size_type pos = npos)
1735 return find_last_of(str.data(), pos, str.length());
1738 size_type find_last_of(const value_type* s, size_type pos, size_type n) const;
1740 size_type find_last_of (const value_type* s,
1741 size_type pos = npos) const {
1742 return find_last_of(s, pos, traitsLength(s));
1745 size_type find_last_of (value_type c, size_type pos = npos) const {
1746 return find_last_of(&c, pos, 1);
1749 size_type find_first_not_of(const basic_fbstring& str,
1750 size_type pos = 0) const {
1751 return find_first_not_of(str.data(), pos, str.size());
1754 size_type find_first_not_of(const value_type* s, size_type pos, size_type n)
1757 size_type find_first_not_of(const value_type* s,
1758 size_type pos = 0) const {
1759 return find_first_not_of(s, pos, traitsLength(s));
1762 size_type find_first_not_of(value_type c, size_type pos = 0) const {
1763 return find_first_not_of(&c, pos, 1);
1766 size_type find_last_not_of(const basic_fbstring& str,
1767 size_type pos = npos) const {
1768 return find_last_not_of(str.data(), pos, str.length());
1771 size_type find_last_not_of(const value_type* s, size_type pos, size_type n)
1774 size_type find_last_not_of(const value_type* s,
1775 size_type pos = npos) const {
1776 return find_last_not_of(s, pos, traitsLength(s));
1779 size_type find_last_not_of (value_type c, size_type pos = npos) const {
1780 return find_last_not_of(&c, pos, 1);
1783 basic_fbstring substr(size_type pos = 0, size_type n = npos) const& {
1784 enforce(pos <= size(), std::__throw_out_of_range, "");
1785 return basic_fbstring(data() + pos, std::min(n, size() - pos));
1788 basic_fbstring substr(size_type pos = 0, size_type n = npos) && {
1789 enforce(pos <= size(), std::__throw_out_of_range, "");
1794 return std::move(*this);
1797 int compare(const basic_fbstring& str) const {
1798 // FIX due to Goncalo N M de Carvalho July 18, 2005
1799 return compare(0, size(), str);
1802 int compare(size_type pos1, size_type n1,
1803 const basic_fbstring& str) const {
1804 return compare(pos1, n1, str.data(), str.size());
1807 int compare(size_type pos1, size_type n1,
1808 const value_type* s) const {
1809 return compare(pos1, n1, s, traitsLength(s));
1812 int compare(size_type pos1, size_type n1,
1813 const value_type* s, size_type n2) const {
1814 enforce(pos1 <= size(), std::__throw_out_of_range, "");
1815 procrustes(n1, size() - pos1);
1816 // The line below fixed by Jean-Francois Bastien, 04-23-2007. Thanks!
1817 const int r = traits_type::compare(pos1 + data(), s, std::min(n1, n2));
1818 return r != 0 ? r : n1 > n2 ? 1 : n1 < n2 ? -1 : 0;
1821 int compare(size_type pos1, size_type n1,
1822 const basic_fbstring& str,
1823 size_type pos2, size_type n2) const {
1824 enforce(pos2 <= str.size(), std::__throw_out_of_range, "");
1825 return compare(pos1, n1, str.data() + pos2,
1826 std::min(n2, str.size() - pos2));
1829 // Code from Jean-Francois Bastien (03/26/2007)
1830 int compare(const value_type* s) const {
1831 // Could forward to compare(0, size(), s, traitsLength(s))
1832 // but that does two extra checks
1833 const size_type n1(size()), n2(traitsLength(s));
1834 const int r = traits_type::compare(data(), s, std::min(n1, n2));
1835 return r != 0 ? r : n1 > n2 ? 1 : n1 < n2 ? -1 : 0;
1843 template <typename E, class T, class A, class S>
1844 FOLLY_MALLOC_NOINLINE inline typename basic_fbstring<E, T, A, S>::size_type
1845 basic_fbstring<E, T, A, S>::traitsLength(const value_type* s) {
1846 return s ? traits_type::length(s)
1847 : (std::__throw_logic_error(
1848 "basic_fbstring: null pointer initializer not valid"),
1852 template <typename E, class T, class A, class S>
1853 inline basic_fbstring<E, T, A, S>& basic_fbstring<E, T, A, S>::operator=(
1854 const basic_fbstring& lhs) {
1855 Invariant checker(*this);
1857 if (FBSTRING_UNLIKELY(&lhs == this)) {
1861 return assign(lhs.data(), lhs.size());
1865 template <typename E, class T, class A, class S>
1866 inline basic_fbstring<E, T, A, S>& basic_fbstring<E, T, A, S>::operator=(
1867 basic_fbstring&& goner) noexcept {
1868 if (FBSTRING_UNLIKELY(&goner == this)) {
1869 // Compatibility with std::basic_string<>,
1870 // C++11 21.4.2 [string.cons] / 23 requires self-move-assignment support.
1873 // No need of this anymore
1874 this->~basic_fbstring();
1875 // Move the goner into this
1876 new (&store_) S(std::move(goner.store_));
1880 template <typename E, class T, class A, class S>
1881 template <typename TP>
1882 inline typename std::enable_if<
1884 typename std::decay<TP>::type,
1885 typename basic_fbstring<E, T, A, S>::value_type>::value,
1886 basic_fbstring<E, T, A, S>&>::type
1887 basic_fbstring<E, T, A, S>::operator=(TP c) {
1888 Invariant checker(*this);
1891 store_.expandNoinit(1);
1892 } else if (store_.isShared()) {
1893 basic_fbstring(1, c).swap(*this);
1896 store_.shrink(size() - 1);
1902 template <typename E, class T, class A, class S>
1903 inline void basic_fbstring<E, T, A, S>::resize(
1904 const size_type n, const value_type c /*= value_type()*/) {
1905 Invariant checker(*this);
1907 auto size = this->size();
1909 store_.shrink(size - n);
1911 auto const delta = n - size;
1912 auto pData = store_.expandNoinit(delta);
1913 fbstring_detail::podFill(pData, pData + delta, c);
1915 FBSTRING_ASSERT(this->size() == n);
1918 template <typename E, class T, class A, class S>
1919 inline basic_fbstring<E, T, A, S>& basic_fbstring<E, T, A, S>::append(
1920 const basic_fbstring& str) {
1922 auto desiredSize = size() + str.size();
1924 append(str.data(), str.size());
1925 FBSTRING_ASSERT(size() == desiredSize);
1929 template <typename E, class T, class A, class S>
1930 inline basic_fbstring<E, T, A, S>& basic_fbstring<E, T, A, S>::append(
1931 const basic_fbstring& str, const size_type pos, size_type n) {
1932 const size_type sz = str.size();
1933 enforce(pos <= sz, std::__throw_out_of_range, "");
1934 procrustes(n, sz - pos);
1935 return append(str.data() + pos, n);
1938 template <typename E, class T, class A, class S>
1939 FOLLY_MALLOC_NOINLINE inline basic_fbstring<E, T, A, S>&
1940 basic_fbstring<E, T, A, S>::append(const value_type* s, size_type n) {
1941 Invariant checker(*this);
1943 if (FBSTRING_UNLIKELY(!n)) {
1944 // Unlikely but must be done
1947 auto const oldSize = size();
1948 auto const oldData = data();
1949 auto pData = store_.expandNoinit(n, /* expGrowth = */ true);
1951 // Check for aliasing (rare). We could use "<=" here but in theory
1952 // those do not work for pointers unless the pointers point to
1953 // elements in the same array. For that reason we use
1954 // std::less_equal, which is guaranteed to offer a total order
1955 // over pointers. See discussion at http://goo.gl/Cy2ya for more
1957 std::less_equal<const value_type*> le;
1958 if (FBSTRING_UNLIKELY(le(oldData, s) && !le(oldData + oldSize, s))) {
1959 FBSTRING_ASSERT(le(s + n, oldData + oldSize));
1960 // expandNoinit() could have moved the storage, restore the source.
1961 s = data() + (s - oldData);
1962 fbstring_detail::podMove(s, s + n, pData);
1964 fbstring_detail::podCopy(s, s + n, pData);
1967 FBSTRING_ASSERT(size() == oldSize + n);
1971 template <typename E, class T, class A, class S>
1972 inline basic_fbstring<E, T, A, S>& basic_fbstring<E, T, A, S>::append(
1973 size_type n, value_type c) {
1974 Invariant checker(*this);
1975 auto pData = store_.expandNoinit(n, /* expGrowth = */ true);
1976 fbstring_detail::podFill(pData, pData + n, c);
1980 template <typename E, class T, class A, class S>
1981 inline basic_fbstring<E, T, A, S>& basic_fbstring<E, T, A, S>::assign(
1982 const basic_fbstring& str, const size_type pos, size_type n) {
1983 const size_type sz = str.size();
1984 enforce(pos <= sz, std::__throw_out_of_range, "");
1985 procrustes(n, sz - pos);
1986 return assign(str.data() + pos, n);
1989 template <typename E, class T, class A, class S>
1990 FOLLY_MALLOC_NOINLINE inline basic_fbstring<E, T, A, S>&
1991 basic_fbstring<E, T, A, S>::assign(const value_type* s, const size_type n) {
1992 Invariant checker(*this);
1996 } else if (size() >= n) {
1997 // s can alias this, we need to use podMove.
1998 fbstring_detail::podMove(s, s + n, store_.mutableData());
1999 store_.shrink(size() - n);
2000 FBSTRING_ASSERT(size() == n);
2002 // If n is larger than size(), s cannot alias this string's
2005 // Do not use exponential growth here: assign() should be tight,
2006 // to mirror the behavior of the equivalent constructor.
2007 fbstring_detail::podCopy(s, s + n, store_.expandNoinit(n));
2010 FBSTRING_ASSERT(size() == n);
2014 #ifndef _LIBSTDCXX_FBSTRING
2015 template <typename E, class T, class A, class S>
2016 inline typename basic_fbstring<E, T, A, S>::istream_type&
2017 basic_fbstring<E, T, A, S>::getlineImpl(istream_type & is, value_type delim) {
2018 Invariant checker(*this);
2023 size_t avail = capacity() - size;
2024 // fbstring has 1 byte extra capacity for the null terminator,
2025 // and getline null-terminates the read string.
2026 is.getline(store_.expandNoinit(avail), avail + 1, delim);
2027 size += is.gcount();
2029 if (is.bad() || is.eof() || !is.fail()) {
2030 // Done by either failure, end of file, or normal read.
2031 if (!is.bad() && !is.eof()) {
2032 --size; // gcount() also accounts for the delimiter.
2038 FBSTRING_ASSERT(size == this->size());
2039 FBSTRING_ASSERT(size == capacity());
2040 // Start at minimum allocation 63 + terminator = 64.
2041 reserve(std::max<size_t>(63, 3 * size / 2));
2042 // Clear the error so we can continue reading.
2049 template <typename E, class T, class A, class S>
2050 inline typename basic_fbstring<E, T, A, S>::size_type
2051 basic_fbstring<E, T, A, S>::find(
2052 const value_type* needle, const size_type pos, const size_type nsize)
2054 auto const size = this->size();
2055 // nsize + pos can overflow (eg pos == npos), guard against that by checking
2056 // that nsize + pos does not wrap around.
2057 if (nsize + pos > size || nsize + pos < pos) {
2064 // Don't use std::search, use a Boyer-Moore-like trick by comparing
2065 // the last characters first
2066 auto const haystack = data();
2067 auto const nsize_1 = nsize - 1;
2068 auto const lastNeedle = needle[nsize_1];
2070 // Boyer-Moore skip value for the last char in the needle. Zero is
2071 // not a valid value; skip will be computed the first time it's
2075 const E* i = haystack + pos;
2076 auto iEnd = haystack + size - nsize_1;
2079 // Boyer-Moore: match the last element in the needle
2080 while (i[nsize_1] != lastNeedle) {
2086 // Here we know that the last char matches
2087 // Continue in pedestrian mode
2088 for (size_t j = 0;;) {
2089 FBSTRING_ASSERT(j < nsize);
2090 if (i[j] != needle[j]) {
2091 // Not found, we can skip
2092 // Compute the skip value lazily
2095 while (skip <= nsize_1 && needle[nsize_1 - skip] != lastNeedle) {
2102 // Check if done searching
2105 return i - haystack;
2112 template <typename E, class T, class A, class S>
2113 inline typename basic_fbstring<E, T, A, S>::iterator
2114 basic_fbstring<E, T, A, S>::insertImplDiscr(
2115 const_iterator i, size_type n, value_type c, std::true_type) {
2116 Invariant checker(*this);
2118 FBSTRING_ASSERT(i >= cbegin() && i <= cend());
2119 const size_type pos = i - cbegin();
2121 auto oldSize = size();
2122 store_.expandNoinit(n, /* expGrowth = */ true);
2124 fbstring_detail::podMove(b + pos, b + oldSize, b + pos + n);
2125 fbstring_detail::podFill(b + pos, b + pos + n, c);
2130 template <typename E, class T, class A, class S>
2131 template <class InputIter>
2132 inline typename basic_fbstring<E, T, A, S>::iterator
2133 basic_fbstring<E, T, A, S>::insertImplDiscr(
2134 const_iterator i, InputIter b, InputIter e, std::false_type) {
2136 i, b, e, typename std::iterator_traits<InputIter>::iterator_category());
2139 template <typename E, class T, class A, class S>
2140 template <class FwdIterator>
2141 inline typename basic_fbstring<E, T, A, S>::iterator
2142 basic_fbstring<E, T, A, S>::insertImpl(
2146 std::forward_iterator_tag) {
2147 Invariant checker(*this);
2149 FBSTRING_ASSERT(i >= cbegin() && i <= cend());
2150 const size_type pos = i - cbegin();
2151 auto n = std::distance(s1, s2);
2152 FBSTRING_ASSERT(n >= 0);
2154 auto oldSize = size();
2155 store_.expandNoinit(n, /* expGrowth = */ true);
2157 fbstring_detail::podMove(b + pos, b + oldSize, b + pos + n);
2158 std::copy(s1, s2, b + pos);
2163 template <typename E, class T, class A, class S>
2164 template <class InputIterator>
2165 inline typename basic_fbstring<E, T, A, S>::iterator
2166 basic_fbstring<E, T, A, S>::insertImpl(
2170 std::input_iterator_tag) {
2171 const auto pos = i - cbegin();
2172 basic_fbstring temp(cbegin(), i);
2173 for (; b != e; ++b) {
2176 temp.append(i, cend());
2178 return begin() + pos;
2181 template <typename E, class T, class A, class S>
2182 inline basic_fbstring<E, T, A, S>& basic_fbstring<E, T, A, S>::replaceImplDiscr(
2185 const value_type* s,
2187 std::integral_constant<int, 2>) {
2188 FBSTRING_ASSERT(i1 <= i2);
2189 FBSTRING_ASSERT(begin() <= i1 && i1 <= end());
2190 FBSTRING_ASSERT(begin() <= i2 && i2 <= end());
2191 return replace(i1, i2, s, s + n);
2194 template <typename E, class T, class A, class S>
2195 inline basic_fbstring<E, T, A, S>& basic_fbstring<E, T, A, S>::replaceImplDiscr(
2200 std::integral_constant<int, 1>) {
2201 const size_type n1 = i2 - i1;
2203 std::fill(i1, i1 + n2, c);
2206 std::fill(i1, i2, c);
2207 insert(i2, n2 - n1, c);
2209 FBSTRING_ASSERT(isSane());
2213 template <typename E, class T, class A, class S>
2214 template <class InputIter>
2215 inline basic_fbstring<E, T, A, S>& basic_fbstring<E, T, A, S>::replaceImplDiscr(
2220 std::integral_constant<int, 0>) {
2221 using Cat = typename std::iterator_traits<InputIter>::iterator_category;
2222 replaceImpl(i1, i2, b, e, Cat());
2226 template <typename E, class T, class A, class S>
2227 template <class FwdIterator>
2228 inline bool basic_fbstring<E, T, A, S>::replaceAliased(
2229 iterator i1, iterator i2, FwdIterator s1, FwdIterator s2, std::true_type) {
2230 std::less_equal<const value_type*> le{};
2231 const bool aliased = le(&*begin(), &*s1) && le(&*s1, &*end());
2235 // Aliased replace, copy to new string
2236 basic_fbstring temp;
2237 temp.reserve(size() - (i2 - i1) + std::distance(s1, s2));
2238 temp.append(begin(), i1).append(s1, s2).append(i2, end());
2243 template <typename E, class T, class A, class S>
2244 template <class FwdIterator>
2245 inline void basic_fbstring<E, T, A, S>::replaceImpl(
2250 std::forward_iterator_tag) {
2251 Invariant checker(*this);
2253 // Handle aliased replace
2254 using Sel = std::integral_constant<
2256 std::is_same<FwdIterator, iterator>::value ||
2257 std::is_same<FwdIterator, const_iterator>::value>;
2258 if (replaceAliased(i1, i2, s1, s2, Sel())) {
2262 auto const n1 = i2 - i1;
2263 FBSTRING_ASSERT(n1 >= 0);
2264 auto const n2 = std::distance(s1, s2);
2265 FBSTRING_ASSERT(n2 >= 0);
2269 std::copy(s1, s2, i1);
2273 s1 = fbstring_detail::copy_n(s1, n1, i1).first;
2276 FBSTRING_ASSERT(isSane());
2279 template <typename E, class T, class A, class S>
2280 template <class InputIterator>
2281 inline void basic_fbstring<E, T, A, S>::replaceImpl(
2286 std::input_iterator_tag) {
2287 basic_fbstring temp(begin(), i1);
2288 temp.append(b, e).append(i2, end());
2292 template <typename E, class T, class A, class S>
2293 inline typename basic_fbstring<E, T, A, S>::size_type
2294 basic_fbstring<E, T, A, S>::rfind(
2295 const value_type* s, size_type pos, size_type n) const {
2299 pos = std::min(pos, length() - n);
2304 const_iterator i(begin() + pos);
2306 if (traits_type::eq(*i, *s) && traits_type::compare(&*i, s, n) == 0) {
2316 template <typename E, class T, class A, class S>
2317 inline typename basic_fbstring<E, T, A, S>::size_type
2318 basic_fbstring<E, T, A, S>::find_first_of(
2319 const value_type* s, size_type pos, size_type n) const {
2320 if (pos > length() || n == 0) {
2323 const_iterator i(begin() + pos), finish(end());
2324 for (; i != finish; ++i) {
2325 if (traits_type::find(s, n, *i) != 0) {
2332 template <typename E, class T, class A, class S>
2333 inline typename basic_fbstring<E, T, A, S>::size_type
2334 basic_fbstring<E, T, A, S>::find_last_of(
2335 const value_type* s, size_type pos, size_type n) const {
2336 if (!empty() && n > 0) {
2337 pos = std::min(pos, length() - 1);
2338 const_iterator i(begin() + pos);
2340 if (traits_type::find(s, n, *i) != 0) {
2351 template <typename E, class T, class A, class S>
2352 inline typename basic_fbstring<E, T, A, S>::size_type
2353 basic_fbstring<E, T, A, S>::find_first_not_of(
2354 const value_type* s, size_type pos, size_type n) const {
2355 if (pos < length()) {
2356 const_iterator i(begin() + pos), finish(end());
2357 for (; i != finish; ++i) {
2358 if (traits_type::find(s, n, *i) == 0) {
2366 template <typename E, class T, class A, class S>
2367 inline typename basic_fbstring<E, T, A, S>::size_type
2368 basic_fbstring<E, T, A, S>::find_last_not_of(
2369 const value_type* s, size_type pos, size_type n) const {
2370 if (!this->empty()) {
2371 pos = std::min(pos, size() - 1);
2372 const_iterator i(begin() + pos);
2374 if (traits_type::find(s, n, *i) == 0) {
2385 // non-member functions
2387 template <typename E, class T, class A, class S>
2389 basic_fbstring<E, T, A, S> operator+(const basic_fbstring<E, T, A, S>& lhs,
2390 const basic_fbstring<E, T, A, S>& rhs) {
2392 basic_fbstring<E, T, A, S> result;
2393 result.reserve(lhs.size() + rhs.size());
2394 result.append(lhs).append(rhs);
2395 return std::move(result);
2399 template <typename E, class T, class A, class S>
2401 basic_fbstring<E, T, A, S> operator+(basic_fbstring<E, T, A, S>&& lhs,
2402 const basic_fbstring<E, T, A, S>& rhs) {
2403 return std::move(lhs.append(rhs));
2407 template <typename E, class T, class A, class S>
2409 basic_fbstring<E, T, A, S> operator+(const basic_fbstring<E, T, A, S>& lhs,
2410 basic_fbstring<E, T, A, S>&& rhs) {
2411 if (rhs.capacity() >= lhs.size() + rhs.size()) {
2412 // Good, at least we don't need to reallocate
2413 return std::move(rhs.insert(0, lhs));
2415 // Meh, no go. Forward to operator+(const&, const&).
2416 auto const& rhsC = rhs;
2421 template <typename E, class T, class A, class S>
2423 basic_fbstring<E, T, A, S> operator+(basic_fbstring<E, T, A, S>&& lhs,
2424 basic_fbstring<E, T, A, S>&& rhs) {
2425 return std::move(lhs.append(rhs));
2429 template <typename E, class T, class A, class S>
2431 basic_fbstring<E, T, A, S> operator+(
2433 const basic_fbstring<E, T, A, S>& rhs) {
2435 basic_fbstring<E, T, A, S> result;
2436 const auto len = basic_fbstring<E, T, A, S>::traits_type::length(lhs);
2437 result.reserve(len + rhs.size());
2438 result.append(lhs, len).append(rhs);
2443 template <typename E, class T, class A, class S>
2445 basic_fbstring<E, T, A, S> operator+(
2447 basic_fbstring<E, T, A, S>&& rhs) {
2449 const auto len = basic_fbstring<E, T, A, S>::traits_type::length(lhs);
2450 if (rhs.capacity() >= len + rhs.size()) {
2451 // Good, at least we don't need to reallocate
2452 rhs.insert(rhs.begin(), lhs, lhs + len);
2455 // Meh, no go. Do it by hand since we have len already.
2456 basic_fbstring<E, T, A, S> result;
2457 result.reserve(len + rhs.size());
2458 result.append(lhs, len).append(rhs);
2463 template <typename E, class T, class A, class S>
2465 basic_fbstring<E, T, A, S> operator+(
2467 const basic_fbstring<E, T, A, S>& rhs) {
2469 basic_fbstring<E, T, A, S> result;
2470 result.reserve(1 + rhs.size());
2471 result.push_back(lhs);
2477 template <typename E, class T, class A, class S>
2479 basic_fbstring<E, T, A, S> operator+(
2481 basic_fbstring<E, T, A, S>&& rhs) {
2483 if (rhs.capacity() > rhs.size()) {
2484 // Good, at least we don't need to reallocate
2485 rhs.insert(rhs.begin(), lhs);
2488 // Meh, no go. Forward to operator+(E, const&).
2489 auto const& rhsC = rhs;
2494 template <typename E, class T, class A, class S>
2496 basic_fbstring<E, T, A, S> operator+(
2497 const basic_fbstring<E, T, A, S>& lhs,
2500 typedef typename basic_fbstring<E, T, A, S>::size_type size_type;
2501 typedef typename basic_fbstring<E, T, A, S>::traits_type traits_type;
2503 basic_fbstring<E, T, A, S> result;
2504 const size_type len = traits_type::length(rhs);
2505 result.reserve(lhs.size() + len);
2506 result.append(lhs).append(rhs, len);
2510 // C++11 21.4.8.1/10
2511 template <typename E, class T, class A, class S>
2513 basic_fbstring<E, T, A, S> operator+(
2514 basic_fbstring<E, T, A, S>&& lhs,
2517 return std::move(lhs += rhs);
2520 // C++11 21.4.8.1/11
2521 template <typename E, class T, class A, class S>
2523 basic_fbstring<E, T, A, S> operator+(
2524 const basic_fbstring<E, T, A, S>& lhs,
2527 basic_fbstring<E, T, A, S> result;
2528 result.reserve(lhs.size() + 1);
2530 result.push_back(rhs);
2534 // C++11 21.4.8.1/12
2535 template <typename E, class T, class A, class S>
2537 basic_fbstring<E, T, A, S> operator+(
2538 basic_fbstring<E, T, A, S>&& lhs,
2541 return std::move(lhs += rhs);
2544 template <typename E, class T, class A, class S>
2546 bool operator==(const basic_fbstring<E, T, A, S>& lhs,
2547 const basic_fbstring<E, T, A, S>& rhs) {
2548 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0; }
2550 template <typename E, class T, class A, class S>
2552 bool operator==(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2553 const basic_fbstring<E, T, A, S>& rhs) {
2554 return rhs == lhs; }
2556 template <typename E, class T, class A, class S>
2558 bool operator==(const basic_fbstring<E, T, A, S>& lhs,
2559 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2560 return lhs.compare(rhs) == 0; }
2562 template <typename E, class T, class A, class S>
2564 bool operator!=(const basic_fbstring<E, T, A, S>& lhs,
2565 const basic_fbstring<E, T, A, S>& rhs) {
2566 return !(lhs == rhs); }
2568 template <typename E, class T, class A, class S>
2570 bool operator!=(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2571 const basic_fbstring<E, T, A, S>& rhs) {
2572 return !(lhs == rhs); }
2574 template <typename E, class T, class A, class S>
2576 bool operator!=(const basic_fbstring<E, T, A, S>& lhs,
2577 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2578 return !(lhs == rhs); }
2580 template <typename E, class T, class A, class S>
2582 bool operator<(const basic_fbstring<E, T, A, S>& lhs,
2583 const basic_fbstring<E, T, A, S>& rhs) {
2584 return lhs.compare(rhs) < 0; }
2586 template <typename E, class T, class A, class S>
2588 bool operator<(const basic_fbstring<E, T, A, S>& lhs,
2589 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2590 return lhs.compare(rhs) < 0; }
2592 template <typename E, class T, class A, class S>
2594 bool operator<(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2595 const basic_fbstring<E, T, A, S>& rhs) {
2596 return rhs.compare(lhs) > 0; }
2598 template <typename E, class T, class A, class S>
2600 bool operator>(const basic_fbstring<E, T, A, S>& lhs,
2601 const basic_fbstring<E, T, A, S>& rhs) {
2604 template <typename E, class T, class A, class S>
2606 bool operator>(const basic_fbstring<E, T, A, S>& lhs,
2607 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2610 template <typename E, class T, class A, class S>
2612 bool operator>(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2613 const basic_fbstring<E, T, A, S>& rhs) {
2616 template <typename E, class T, class A, class S>
2618 bool operator<=(const basic_fbstring<E, T, A, S>& lhs,
2619 const basic_fbstring<E, T, A, S>& rhs) {
2620 return !(rhs < lhs); }
2622 template <typename E, class T, class A, class S>
2624 bool operator<=(const basic_fbstring<E, T, A, S>& lhs,
2625 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2626 return !(rhs < lhs); }
2628 template <typename E, class T, class A, class S>
2630 bool operator<=(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2631 const basic_fbstring<E, T, A, S>& rhs) {
2632 return !(rhs < lhs); }
2634 template <typename E, class T, class A, class S>
2636 bool operator>=(const basic_fbstring<E, T, A, S>& lhs,
2637 const basic_fbstring<E, T, A, S>& rhs) {
2638 return !(lhs < rhs); }
2640 template <typename E, class T, class A, class S>
2642 bool operator>=(const basic_fbstring<E, T, A, S>& lhs,
2643 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2644 return !(lhs < rhs); }
2646 template <typename E, class T, class A, class S>
2648 bool operator>=(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2649 const basic_fbstring<E, T, A, S>& rhs) {
2650 return !(lhs < rhs);
2654 template <typename E, class T, class A, class S>
2655 void swap(basic_fbstring<E, T, A, S>& lhs, basic_fbstring<E, T, A, S>& rhs) {
2659 // TODO: make this faster.
2660 template <typename E, class T, class A, class S>
2663 typename basic_fbstring<E, T, A, S>::value_type,
2664 typename basic_fbstring<E, T, A, S>::traits_type>&
2666 std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2667 typename basic_fbstring<E, T, A, S>::traits_type>& is,
2668 basic_fbstring<E, T, A, S>& str) {
2669 typedef std::basic_istream<
2670 typename basic_fbstring<E, T, A, S>::value_type,
2671 typename basic_fbstring<E, T, A, S>::traits_type>
2673 typename _istream_type::sentry sentry(is);
2674 size_t extracted = 0;
2675 auto err = _istream_type::goodbit;
2677 auto n = is.width();
2682 for (auto got = is.rdbuf()->sgetc(); extracted != size_t(n); ++extracted) {
2683 if (got == T::eof()) {
2684 err |= _istream_type::eofbit;
2692 got = is.rdbuf()->snextc();
2696 err |= _istream_type::failbit;
2704 template <typename E, class T, class A, class S>
2706 std::basic_ostream<typename basic_fbstring<E, T, A, S>::value_type,
2707 typename basic_fbstring<E, T, A, S>::traits_type>&
2709 std::basic_ostream<typename basic_fbstring<E, T, A, S>::value_type,
2710 typename basic_fbstring<E, T, A, S>::traits_type>& os,
2711 const basic_fbstring<E, T, A, S>& str) {
2713 typedef std::basic_ostream<
2714 typename basic_fbstring<E, T, A, S>::value_type,
2715 typename basic_fbstring<E, T, A, S>::traits_type>
2717 typename _ostream_type::sentry _s(os);
2719 typedef std::ostreambuf_iterator<
2720 typename basic_fbstring<E, T, A, S>::value_type,
2721 typename basic_fbstring<E, T, A, S>::traits_type> _Ip;
2722 size_t __len = str.size();
2724 (os.flags() & _ostream_type::adjustfield) == _ostream_type::left;
2725 if (__pad_and_output(_Ip(os),
2727 __left ? str.data() + __len : str.data(),
2730 os.fill()).failed()) {
2731 os.setstate(_ostream_type::badbit | _ostream_type::failbit);
2734 #elif defined(_MSC_VER)
2735 typedef decltype(os.precision()) streamsize;
2736 // MSVC doesn't define __ostream_insert
2737 os.write(str.data(), static_cast<streamsize>(str.size()));
2739 std::__ostream_insert(os, str.data(), str.size());
2744 template <typename E1, class T, class A, class S>
2745 constexpr typename basic_fbstring<E1, T, A, S>::size_type
2746 basic_fbstring<E1, T, A, S>::npos;
2748 #ifndef _LIBSTDCXX_FBSTRING
2749 // basic_string compatibility routines
2751 template <typename E, class T, class A, class S, class A2>
2752 inline bool operator==(
2753 const basic_fbstring<E, T, A, S>& lhs,
2754 const std::basic_string<E, T, A2>& rhs) {
2755 return lhs.compare(0, lhs.size(), rhs.data(), rhs.size()) == 0;
2758 template <typename E, class T, class A, class S, class A2>
2759 inline bool operator==(
2760 const std::basic_string<E, T, A2>& lhs,
2761 const basic_fbstring<E, T, A, S>& rhs) {
2765 template <typename E, class T, class A, class S, class A2>
2766 inline bool operator!=(
2767 const basic_fbstring<E, T, A, S>& lhs,
2768 const std::basic_string<E, T, A2>& rhs) {
2769 return !(lhs == rhs);
2772 template <typename E, class T, class A, class S, class A2>
2773 inline bool operator!=(
2774 const std::basic_string<E, T, A2>& lhs,
2775 const basic_fbstring<E, T, A, S>& rhs) {
2776 return !(lhs == rhs);
2779 template <typename E, class T, class A, class S, class A2>
2780 inline bool operator<(
2781 const basic_fbstring<E, T, A, S>& lhs,
2782 const std::basic_string<E, T, A2>& rhs) {
2783 return lhs.compare(0, lhs.size(), rhs.data(), rhs.size()) < 0;
2786 template <typename E, class T, class A, class S, class A2>
2787 inline bool operator>(
2788 const basic_fbstring<E, T, A, S>& lhs,
2789 const std::basic_string<E, T, A2>& rhs) {
2790 return lhs.compare(0, lhs.size(), rhs.data(), rhs.size()) > 0;
2793 template <typename E, class T, class A, class S, class A2>
2794 inline bool operator<(
2795 const std::basic_string<E, T, A2>& lhs,
2796 const basic_fbstring<E, T, A, S>& rhs) {
2800 template <typename E, class T, class A, class S, class A2>
2801 inline bool operator>(
2802 const std::basic_string<E, T, A2>& lhs,
2803 const basic_fbstring<E, T, A, S>& rhs) {
2807 template <typename E, class T, class A, class S, class A2>
2808 inline bool operator<=(
2809 const basic_fbstring<E, T, A, S>& lhs,
2810 const std::basic_string<E, T, A2>& rhs) {
2811 return !(lhs > rhs);
2814 template <typename E, class T, class A, class S, class A2>
2815 inline bool operator>=(
2816 const basic_fbstring<E, T, A, S>& lhs,
2817 const std::basic_string<E, T, A2>& rhs) {
2818 return !(lhs < rhs);
2821 template <typename E, class T, class A, class S, class A2>
2822 inline bool operator<=(
2823 const std::basic_string<E, T, A2>& lhs,
2824 const basic_fbstring<E, T, A, S>& rhs) {
2825 return !(lhs > rhs);
2828 template <typename E, class T, class A, class S, class A2>
2829 inline bool operator>=(
2830 const std::basic_string<E, T, A2>& lhs,
2831 const basic_fbstring<E, T, A, S>& rhs) {
2832 return !(lhs < rhs);
2835 #if !defined(_LIBSTDCXX_FBSTRING)
2836 typedef basic_fbstring<char> fbstring;
2839 // fbstring is relocatable
2840 template <class T, class R, class A, class S>
2841 FOLLY_ASSUME_RELOCATABLE(basic_fbstring<T, R, A, S>);
2844 _GLIBCXX_END_NAMESPACE_VERSION
2847 } // namespace folly
2849 #ifndef _LIBSTDCXX_FBSTRING
2851 // Hash functions to make fbstring usable with e.g. hash_map
2853 // Handle interaction with different C++ standard libraries, which
2854 // expect these types to be in different namespaces.
2856 #define FOLLY_FBSTRING_HASH1(T) \
2858 struct hash< ::folly::basic_fbstring<T>> { \
2859 size_t operator()(const ::folly::basic_fbstring<T>& s) const { \
2860 return ::folly::hash::fnv32_buf(s.data(), s.size() * sizeof(T)); \
2864 // The C++11 standard says that these four are defined
2865 #define FOLLY_FBSTRING_HASH \
2866 FOLLY_FBSTRING_HASH1(char) \
2867 FOLLY_FBSTRING_HASH1(char16_t) \
2868 FOLLY_FBSTRING_HASH1(char32_t) \
2869 FOLLY_FBSTRING_HASH1(wchar_t)
2877 #undef FOLLY_FBSTRING_HASH
2878 #undef FOLLY_FBSTRING_HASH1
2880 #endif // _LIBSTDCXX_FBSTRING
2884 #undef FBSTRING_DISABLE_SSO
2885 #undef FBSTRING_SANITIZE_ADDRESS
2887 #undef FBSTRING_LIKELY
2888 #undef FBSTRING_UNLIKELY
2889 #undef FBSTRING_ASSERT