2 * Copyright 2015 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)
20 #ifndef FOLLY_BASE_FBSTRING_H_
21 #define FOLLY_BASE_FBSTRING_H_
25 #include <type_traits>
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
33 #pragma GCC system_header
35 // Handle the cases where the fbcode version (folly/Malloc.h) is included
36 // either before or after this inclusion.
37 #ifdef FOLLY_MALLOC_H_
38 #undef FOLLY_MALLOC_H_
39 #include "basic_fbstring_malloc.h" // nolint
41 #include "basic_fbstring_malloc.h" // nolint
42 #undef FOLLY_MALLOC_H_
45 #else // !_LIBSTDCXX_FBSTRING
47 #include <folly/Portability.h>
49 // libc++ doesn't provide this header, nor does msvc
50 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
51 #include <bits/c++config.h>
59 #include <folly/Traits.h>
60 #include <folly/Malloc.h>
61 #include <folly/Hash.h>
62 #include <folly/ScopeGuard.h>
64 #if FOLLY_HAVE_DEPRECATED_ASSOC
65 #ifdef _GLIBCXX_SYMVER
66 #include <ext/hash_set>
67 #include <ext/hash_map>
73 // We defined these here rather than including Likely.h to avoid
74 // redefinition errors when fbstring is imported into libstdc++.
75 #if defined(__GNUC__) && __GNUC__ >= 4
76 #define FBSTRING_LIKELY(x) (__builtin_expect((x), 1))
77 #define FBSTRING_UNLIKELY(x) (__builtin_expect((x), 0))
79 #define FBSTRING_LIKELY(x) (x)
80 #define FBSTRING_UNLIKELY(x) (x)
83 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
84 #pragma GCC diagnostic push
85 #pragma GCC diagnostic ignored "-Wshadow"
87 // FBString cannot use throw when replacing std::string, though it may still
90 #define throw FOLLY_FBSTRING_MAY_NOT_USE_THROW
92 #ifdef _LIBSTDCXX_FBSTRING
93 namespace std _GLIBCXX_VISIBILITY(default) {
94 _GLIBCXX_BEGIN_NAMESPACE_VERSION
99 // Different versions of gcc/clang support different versions of
100 // the address sanitizer attribute. Unfortunately, this attribute
101 // has issues when inlining is used, so disable that as well.
102 #if defined(__clang__)
103 # if __has_feature(address_sanitizer)
104 # if __has_attribute(__no_address_safety_analysis__)
105 # define FBSTRING_DISABLE_ADDRESS_SANITIZER \
106 __attribute__((__no_address_safety_analysis__, __noinline__))
107 # elif __has_attribute(__no_sanitize_address__)
108 # define FBSTRING_DISABLE_ADDRESS_SANITIZER \
109 __attribute__((__no_sanitize_address__, __noinline__))
112 #elif defined (__GNUC__) && \
114 (__GNUC_MINOR__ >= 8) && \
116 # define FBSTRING_DISABLE_ADDRESS_SANITIZER \
117 __attribute__((__no_address_safety_analysis__, __noinline__))
119 #ifndef FBSTRING_DISABLE_ADDRESS_SANITIZER
120 # define FBSTRING_DISABLE_ADDRESS_SANITIZER
123 namespace fbstring_detail {
125 template <class InIt, class OutIt>
128 typename std::iterator_traits<InIt>::difference_type n,
130 for (; n != 0; --n, ++b, ++d) {
136 template <class Pod, class T>
137 inline void pod_fill(Pod* b, Pod* e, T c) {
138 assert(b && e && b <= e);
139 /*static*/ if (sizeof(T) == 1) {
142 auto const ee = b + ((e - b) & ~7u);
143 for (; b != ee; b += 8) {
154 for (; b != e; ++b) {
161 * Lightly structured memcpy, simplifies copying PODs and introduces
162 * some asserts. Unfortunately using this function may cause
163 * measurable overhead (presumably because it adjusts from a begin/end
164 * convention to a pointer/size convention, so it does some extra
165 * arithmetic even though the caller might have done the inverse
166 * adaptation outside).
169 inline void pod_copy(const Pod* b, const Pod* e, Pod* d) {
171 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 pod_move(const Pod* b, const Pod* e, Pod* d) {
182 memmove(d, b, (e - b) * sizeof(*b));
185 } // namespace fbstring_detail
188 * Defines a special acquisition method for constructing fbstring
189 * objects. AcquireMallocatedString means that the user passes a
190 * pointer to a malloc-allocated string that the fbstring object will
193 enum class AcquireMallocatedString {};
196 * fbstring_core_model is a mock-up type that defines all required
197 * signatures of a fbstring core. The fbstring class itself uses such
198 * a core object to implement all of the numerous member functions
199 * required by the standard.
201 * If you want to define a new core, copy the definition below and
202 * implement the primitives. Then plug the core into basic_fbstring as
203 * a template argument.
205 template <class Char>
206 class fbstring_core_model {
208 fbstring_core_model();
209 fbstring_core_model(const fbstring_core_model &);
210 ~fbstring_core_model();
211 // Returns a pointer to string's buffer (currently only contiguous
212 // strings are supported). The pointer is guaranteed to be valid
213 // until the next call to a non-const member function.
214 const Char * data() const;
215 // Much like data(), except the string is prepared to support
216 // character-level changes. This call is a signal for
217 // e.g. reference-counted implementation to fork the data. The
218 // pointer is guaranteed to be valid until the next call to a
219 // non-const member function.
220 Char * mutable_data();
221 // Returns a pointer to string's buffer and guarantees that a
222 // readable '\0' lies right after the buffer. The pointer is
223 // guaranteed to be valid until the next call to a non-const member
225 const Char * c_str() const;
226 // Shrinks the string by delta characters. Asserts that delta <=
228 void shrink(size_t delta);
229 // Expands the string by delta characters (i.e. after this call
230 // size() will report the old size() plus delta) but without
231 // initializing the expanded region. Returns a pointer to the memory
232 // to be initialized (the beginning of the expanded portion). The
233 // caller is expected to fill the expanded area appropriately.
234 Char* expand_noinit(size_t delta);
235 // Expands the string by one character and sets the last character
237 void push_back(Char c);
238 // Returns the string's size.
240 // Returns the string's capacity, i.e. maximum size that the string
241 // can grow to without reallocation. Note that for reference counted
242 // strings that's technically a lie - even assigning characters
243 // within the existing size would cause a reallocation.
244 size_t capacity() const;
245 // Returns true if the data underlying the string is actually shared
246 // across multiple strings (in a refcounted fashion).
247 bool isShared() const;
248 // Makes sure that at least minCapacity characters are available for
249 // the string without reallocation. For reference-counted strings,
250 // it should fork the data even if minCapacity < size().
251 void reserve(size_t minCapacity);
254 fbstring_core_model& operator=(const fbstring_core_model &);
259 * This is the core of the string. The code should work on 32- and
260 * 64-bit and both big- and little-endianan architectures with any
263 * The storage is selected as follows (assuming we store one-byte
264 * characters on a 64-bit machine): (a) "small" strings between 0 and
265 * 23 chars are stored in-situ without allocation (the rightmost byte
266 * stores the size); (b) "medium" strings from 24 through 254 chars
267 * are stored in malloc-allocated memory that is copied eagerly; (c)
268 * "large" strings of 255 chars and above are stored in a similar
269 * structure as medium arrays, except that the string is
270 * reference-counted and copied lazily. the reference count is
271 * allocated right before the character array.
273 * The discriminator between these three strategies sits in two
274 * bits of the rightmost char of the storage. If neither is set, then the
275 * string is small (and its length sits in the lower-order bits on
276 * little-endian or the high-order bits on big-endian of that
277 * rightmost character). If the MSb is set, the string is medium width.
278 * If the second MSb is set, then the string is large. On little-endian,
279 * these 2 bits are the 2 MSbs of MediumLarge::capacity_, while on
280 * big-endian, these 2 bits are the 2 LSbs. This keeps both little-endian
281 * and big-endian fbstring_core equivalent with merely different ops used
282 * to extract capacity/category.
284 template <class Char> class fbstring_core {
286 fbstring_core() noexcept {
287 // Only initialize the tag, will set the MSBs (i.e. the small
288 // string size) to zero too
289 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
290 ml_.capacity_ = maxSmallSize << (8 * (sizeof(size_t) - sizeof(Char)));
291 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
292 ml_.capacity_ = maxSmallSize << 2;
294 #error Unable to identify target endianness
296 // or: setSmallSize(0);
298 assert(category() == Category::isSmall && size() == 0);
301 fbstring_core(const fbstring_core & rhs) {
302 assert(&rhs != this);
303 // Simplest case first: small strings are bitblitted
304 if (rhs.category() == Category::isSmall) {
305 static_assert(offsetof(MediumLarge, data_) == 0,
306 "fbstring layout failure");
307 static_assert(offsetof(MediumLarge, size_) == sizeof(ml_.data_),
308 "fbstring layout failure");
309 static_assert(offsetof(MediumLarge, capacity_) == 2 * sizeof(ml_.data_),
310 "fbstring layout failure");
311 const size_t size = rhs.smallSize();
313 ml_.capacity_ = rhs.ml_.capacity_;
316 // Just write the whole thing, don't look at details. In
317 // particular we need to copy capacity anyway because we want
318 // to set the size (don't forget that the last character,
319 // which stores a short string's length, is shared with the
320 // ml_.capacity field).
323 assert(category() == Category::isSmall && this->size() == rhs.size());
324 } else if (rhs.category() == Category::isLarge) {
325 // Large strings are just refcounted
327 RefCounted::incrementRefs(ml_.data_);
328 assert(category() == Category::isLarge && size() == rhs.size());
330 // Medium strings are copied eagerly. Don't forget to allocate
331 // one extra Char for the null terminator.
332 auto const allocSize =
333 goodMallocSize((1 + rhs.ml_.size_) * sizeof(Char));
334 ml_.data_ = static_cast<Char*>(checkedMalloc(allocSize));
335 fbstring_detail::pod_copy(rhs.ml_.data_,
337 rhs.ml_.data_ + rhs.ml_.size_ + 1,
339 // No need for writeTerminator() here, we copied one extra
340 // element just above.
341 ml_.size_ = rhs.ml_.size_;
342 ml_.setCapacity(allocSize / sizeof(Char) - 1, Category::isMedium);
343 assert(category() == Category::isMedium);
345 assert(size() == rhs.size());
346 assert(memcmp(data(), rhs.data(), size() * sizeof(Char)) == 0);
349 fbstring_core(fbstring_core&& goner) noexcept {
350 if (goner.category() == Category::isSmall) {
351 // Just copy, leave the goner in peace
352 new(this) fbstring_core(goner.small_, goner.smallSize());
356 // Clean goner's carcass
357 goner.setSmallSize(0);
361 // NOTE(agallagher): The word-aligned copy path copies bytes which are
362 // outside the range of the string, and makes address sanitizer unhappy,
363 // so just disable it on this function.
364 fbstring_core(const Char *const data, const size_t size)
365 FBSTRING_DISABLE_ADDRESS_SANITIZER {
367 #ifndef _LIBSTDCXX_FBSTRING
369 assert(this->size() == size);
370 assert(memcmp(this->data(), data, size * sizeof(Char)) == 0);
375 // Simplest case first: small strings are bitblitted
376 if (size <= maxSmallSize) {
377 // Layout is: Char* data_, size_t size_, size_t capacity_
378 static_assert(sizeof(*this) == sizeof(Char*) + 2 * sizeof(size_t),
379 "fbstring has unexpected size");
380 static_assert(sizeof(Char*) == sizeof(size_t),
381 "fbstring size assumption violation");
382 // sizeof(size_t) must be a power of 2
383 static_assert((sizeof(size_t) & (sizeof(size_t) - 1)) == 0,
384 "fbstring size assumption violation");
386 // If data is aligned, use fast word-wise copying. Otherwise,
387 // use conservative memcpy.
388 if (reinterpret_cast<size_t>(data) & (sizeof(size_t) - 1)) {
389 fbstring_detail::pod_copy(data, data + size, small_);
391 // Copy one word (64 bits) at a time
392 const size_t byteSize = size * sizeof(Char);
393 if (byteSize > 2 * sizeof(size_t)) {
395 ml_.capacity_ = reinterpret_cast<const size_t*>(data)[2];
397 ml_.size_ = reinterpret_cast<const size_t*>(data)[1];
399 ml_.data_ = *reinterpret_cast<Char**>(const_cast<Char*>(data));
400 } else if (byteSize > sizeof(size_t)) {
403 } else if (size > 0) {
410 } else if (size <= maxMediumSize) {
411 // Medium strings are allocated normally. Don't forget to
412 // allocate one extra Char for the terminating null.
413 auto const allocSize = goodMallocSize((1 + size) * sizeof(Char));
414 ml_.data_ = static_cast<Char*>(checkedMalloc(allocSize));
415 fbstring_detail::pod_copy(data, data + size, ml_.data_);
417 ml_.setCapacity(allocSize / sizeof(Char) - 1, Category::isMedium);
419 // Large strings are allocated differently
420 size_t effectiveCapacity = size;
421 auto const newRC = RefCounted::create(data, & effectiveCapacity);
422 ml_.data_ = newRC->data_;
424 ml_.setCapacity(effectiveCapacity, Category::isLarge);
429 ~fbstring_core() noexcept {
430 auto const c = category();
431 if (c == Category::isSmall) {
434 if (c == Category::isMedium) {
438 RefCounted::decrementRefs(ml_.data_);
441 // Snatches a previously mallocated string. The parameter "size"
442 // is the size of the string, and the parameter "allocatedSize"
443 // is the size of the mallocated block. The string must be
444 // \0-terminated, so allocatedSize >= size + 1 and data[size] == '\0'.
446 // So if you want a 2-character string, pass malloc(3) as "data",
447 // pass 2 as "size", and pass 3 as "allocatedSize".
448 fbstring_core(Char * const data,
450 const size_t allocatedSize,
451 AcquireMallocatedString) {
453 assert(allocatedSize >= size + 1);
454 assert(data[size] == '\0');
455 // Use the medium string storage
458 // Don't forget about null terminator
459 ml_.setCapacity(allocatedSize - 1, Category::isMedium);
461 // No need for the memory
467 // swap below doesn't test whether &rhs == this (and instead
468 // potentially does extra work) on the premise that the rarity of
469 // that situation actually makes the check more expensive than is
471 void swap(fbstring_core & rhs) {
477 // In C++11 data() and c_str() are 100% equivalent.
478 const Char * data() const {
482 Char * mutable_data() {
483 auto const c = category();
484 if (c == Category::isSmall) {
487 assert(c == Category::isMedium || c == Category::isLarge);
488 if (c == Category::isLarge && RefCounted::refs(ml_.data_) > 1) {
490 size_t effectiveCapacity = ml_.capacity();
491 auto const newRC = RefCounted::create(& effectiveCapacity);
492 // If this fails, someone placed the wrong capacity in an
494 assert(effectiveCapacity >= ml_.capacity());
495 fbstring_detail::pod_copy(ml_.data_, ml_.data_ + ml_.size_ + 1,
497 RefCounted::decrementRefs(ml_.data_);
498 ml_.data_ = newRC->data_;
499 // No need to call writeTerminator(), we have + 1 above.
504 const Char * c_str() const {
505 auto const c = category();
506 if (c == Category::isSmall) {
507 assert(small_[smallSize()] == '\0');
510 assert(c == Category::isMedium || c == Category::isLarge);
511 assert(ml_.data_[ml_.size_] == '\0');
515 void shrink(const size_t delta) {
516 if (category() == Category::isSmall) {
517 // Check for underflow
518 assert(delta <= smallSize());
519 setSmallSize(smallSize() - delta);
520 } else if (category() == Category::isMedium ||
521 RefCounted::refs(ml_.data_) == 1) {
522 // Medium strings and unique large strings need no special
524 assert(ml_.size_ >= delta);
528 assert(ml_.size_ >= delta);
529 // Shared large string, must make unique. This is because of the
530 // durn terminator must be written, which may trample the shared
533 fbstring_core(ml_.data_, ml_.size_ - delta).swap(*this);
535 // No need to write the terminator.
539 void reserve(size_t minCapacity) {
540 if (category() == Category::isLarge) {
542 if (RefCounted::refs(ml_.data_) > 1) {
543 // We must make it unique regardless; in-place reallocation is
544 // useless if the string is shared. In order to not surprise
545 // people, reserve the new block at current capacity or
546 // more. That way, a string's capacity never shrinks after a
548 minCapacity = std::max(minCapacity, ml_.capacity());
549 auto const newRC = RefCounted::create(& minCapacity);
550 fbstring_detail::pod_copy(ml_.data_, ml_.data_ + ml_.size_ + 1,
552 // Done with the old data. No need to call writeTerminator(),
553 // we have + 1 above.
554 RefCounted::decrementRefs(ml_.data_);
555 ml_.data_ = newRC->data_;
556 ml_.setCapacity(minCapacity, Category::isLarge);
557 // size remains unchanged
559 // String is not shared, so let's try to realloc (if needed)
560 if (minCapacity > ml_.capacity()) {
561 // Asking for more memory
563 RefCounted::reallocate(ml_.data_, ml_.size_,
564 ml_.capacity(), minCapacity);
565 ml_.data_ = newRC->data_;
566 ml_.setCapacity(minCapacity, Category::isLarge);
569 assert(capacity() >= minCapacity);
571 } else if (category() == Category::isMedium) {
572 // String is not shared
573 if (minCapacity <= ml_.capacity()) {
574 return; // nothing to do, there's enough room
576 if (minCapacity <= maxMediumSize) {
577 // Keep the string at medium size. Don't forget to allocate
578 // one extra Char for the terminating null.
579 size_t capacityBytes = goodMallocSize((1 + minCapacity) * sizeof(Char));
580 ml_.data_ = static_cast<Char *>(
583 ml_.size_ * sizeof(Char),
584 (ml_.capacity() + 1) * sizeof(Char),
587 ml_.setCapacity(capacityBytes / sizeof(Char) - 1, Category::isMedium);
589 // Conversion from medium to large string
590 fbstring_core nascent;
591 // Will recurse to another branch of this function
592 nascent.reserve(minCapacity);
593 nascent.ml_.size_ = ml_.size_;
594 fbstring_detail::pod_copy(ml_.data_, ml_.data_ + ml_.size_,
598 assert(capacity() >= minCapacity);
601 assert(category() == Category::isSmall);
602 if (minCapacity > maxMediumSize) {
604 auto const newRC = RefCounted::create(& minCapacity);
605 auto const size = smallSize();
606 fbstring_detail::pod_copy(small_, small_ + size + 1, newRC->data_);
607 // No need for writeTerminator(), we wrote it above with + 1.
608 ml_.data_ = newRC->data_;
610 ml_.setCapacity(minCapacity, Category::isLarge);
611 assert(capacity() >= minCapacity);
612 } else if (minCapacity > maxSmallSize) {
614 // Don't forget to allocate one extra Char for the terminating null
615 auto const allocSizeBytes =
616 goodMallocSize((1 + minCapacity) * sizeof(Char));
617 auto const data = static_cast<Char*>(checkedMalloc(allocSizeBytes));
618 auto const size = smallSize();
619 fbstring_detail::pod_copy(small_, small_ + size + 1, data);
620 // No need for writeTerminator(), we wrote it above with + 1.
623 ml_.setCapacity(allocSizeBytes / sizeof(Char) - 1, Category::isMedium);
626 // Nothing to do, everything stays put
629 assert(capacity() >= minCapacity);
632 Char * expand_noinit(const size_t delta) {
633 // Strategy is simple: make room, then change size
634 assert(capacity() >= size());
636 if (category() == Category::isSmall) {
639 if (newSz <= maxSmallSize) {
646 newSz = ml_.size_ + delta;
647 if (newSz > capacity()) {
651 assert(capacity() >= newSz);
652 // Category can't be small - we took care of that above
653 assert(category() == Category::isMedium || category() == Category::isLarge);
656 assert(size() == newSz);
657 return ml_.data_ + sz;
660 void push_back(Char c) {
661 assert(capacity() >= size());
663 if (category() == Category::isSmall) {
665 if (sz < maxSmallSize) {
667 setSmallSize(sz + 1);
670 reserve(maxSmallSize * 2);
673 if (sz == capacity()) { // always true for isShared()
674 reserve(1 + sz * 3 / 2); // ensures not shared
678 assert(capacity() >= sz + 1);
679 // Category can't be small - we took care of that above
680 assert(category() == Category::isMedium || category() == Category::isLarge);
686 size_t size() const {
687 return category() == Category::isSmall ? smallSize() : ml_.size_;
690 size_t capacity() const {
691 switch (category()) {
692 case Category::isSmall:
694 case Category::isLarge:
695 // For large-sized strings, a multi-referenced chunk has no
696 // available capacity. This is because any attempt to append
697 // data would trigger a new allocation.
698 if (RefCounted::refs(ml_.data_) > 1) return ml_.size_;
701 return ml_.capacity();
704 bool isShared() const {
705 return category() == Category::isLarge && RefCounted::refs(ml_.data_) > 1;
708 void writeTerminator() {
709 if (category() == Category::isSmall) {
710 const auto s = smallSize();
711 if (s != maxSmallSize) {
715 ml_.data_[ml_.size_] = '\0';
721 fbstring_core & operator=(const fbstring_core & rhs);
724 std::atomic<size_t> refCount_;
727 static RefCounted * fromData(Char * p) {
728 return static_cast<RefCounted*>(
730 static_cast<unsigned char*>(static_cast<void*>(p))
731 - sizeof(refCount_)));
734 static size_t refs(Char * p) {
735 return fromData(p)->refCount_.load(std::memory_order_acquire);
738 static void incrementRefs(Char * p) {
739 fromData(p)->refCount_.fetch_add(1, std::memory_order_acq_rel);
742 static void decrementRefs(Char * p) {
743 auto const dis = fromData(p);
744 size_t oldcnt = dis->refCount_.fetch_sub(1, std::memory_order_acq_rel);
751 static RefCounted * create(size_t * size) {
752 // Don't forget to allocate one extra Char for the terminating
753 // null. In this case, however, one Char is already part of the
755 const size_t allocSize = goodMallocSize(
756 sizeof(RefCounted) + *size * sizeof(Char));
757 auto result = static_cast<RefCounted*>(checkedMalloc(allocSize));
758 result->refCount_.store(1, std::memory_order_release);
759 *size = (allocSize - sizeof(RefCounted)) / sizeof(Char);
763 static RefCounted * create(const Char * data, size_t * size) {
764 const size_t effectiveSize = *size;
765 auto result = create(size);
766 fbstring_detail::pod_copy(data, data + effectiveSize, result->data_);
770 static RefCounted * reallocate(Char *const data,
771 const size_t currentSize,
772 const size_t currentCapacity,
773 const size_t newCapacity) {
774 assert(newCapacity > 0 && newCapacity > currentSize);
775 auto const dis = fromData(data);
776 assert(dis->refCount_.load(std::memory_order_acquire) == 1);
777 // Don't forget to allocate one extra Char for the terminating
778 // null. In this case, however, one Char is already part of the
780 auto result = static_cast<RefCounted*>(
782 sizeof(RefCounted) + currentSize * sizeof(Char),
783 sizeof(RefCounted) + currentCapacity * sizeof(Char),
784 sizeof(RefCounted) + newCapacity * sizeof(Char)));
785 assert(result->refCount_.load(std::memory_order_acquire) == 1);
790 typedef std::conditional<sizeof(size_t) == 4, uint32_t, uint64_t>::type
793 enum class Category : category_type {
795 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
796 isMedium = sizeof(size_t) == 4 ? 0x80000000 : 0x8000000000000000,
797 isLarge = sizeof(size_t) == 4 ? 0x40000000 : 0x4000000000000000,
798 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
802 #error Unable to identify target endianness
806 Category category() const {
807 // works for both big-endian and little-endian
808 return static_cast<Category>(ml_.capacity_ & categoryExtractMask);
816 size_t capacity() const {
817 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
818 return capacity_ & capacityExtractMask;
819 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
820 return capacity_ >> 2;
822 #error Unable to identify target endianness
826 void setCapacity(size_t cap, Category cat) {
827 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
828 capacity_ = cap | static_cast<category_type>(cat);
829 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
830 capacity_ = (cap << 2) | static_cast<category_type>(cat);
832 #error Unable to identify target endianness
838 Char small_[sizeof(MediumLarge) / sizeof(Char)];
843 lastChar = sizeof(MediumLarge) - 1,
844 maxSmallSize = lastChar / sizeof(Char),
845 maxMediumSize = 254 / sizeof(Char), // coincides with the small
846 // bin size in dlmalloc
847 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
848 categoryExtractMask = sizeof(size_t) == 4 ? 0xC0000000 : 0xC000000000000000,
849 capacityExtractMask = ~categoryExtractMask,
850 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
851 categoryExtractMask = 0x3,
853 #error Unable to identify target endianness
856 static_assert(!(sizeof(MediumLarge) % sizeof(Char)),
857 "Corrupt memory layout for fbstring.");
859 size_t smallSize() const {
860 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
861 assert(category() == Category::isSmall &&
862 static_cast<size_t>(small_[maxSmallSize])
863 <= static_cast<size_t>(maxSmallSize));
864 return static_cast<size_t>(maxSmallSize)
865 - static_cast<size_t>(small_[maxSmallSize]);
866 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
867 assert(category() == Category::isSmall &&
868 (static_cast<size_t>(small_[maxSmallSize]) >> 2)
869 <= static_cast<size_t>(maxSmallSize));
870 return static_cast<size_t>(maxSmallSize)
871 - (static_cast<size_t>(small_[maxSmallSize]) >> 2);
873 #error Unable to identify target endianness
877 void setSmallSize(size_t s) {
878 // Warning: this should work with uninitialized strings too,
879 // so don't assume anything about the previous value of
880 // small_[maxSmallSize].
881 assert(s <= maxSmallSize);
882 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
883 small_[maxSmallSize] = maxSmallSize - s;
884 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
885 small_[maxSmallSize] = (maxSmallSize - s) << 2;
887 #error Unable to identify target endianness
893 #ifndef _LIBSTDCXX_FBSTRING
895 * Dummy fbstring core that uses an actual std::string. This doesn't
896 * make any sense - it's just for testing purposes.
898 template <class Char>
899 class dummy_fbstring_core {
901 dummy_fbstring_core() {
903 dummy_fbstring_core(const dummy_fbstring_core& another)
904 : backend_(another.backend_) {
906 dummy_fbstring_core(const Char * s, size_t n)
909 void swap(dummy_fbstring_core & rhs) {
910 backend_.swap(rhs.backend_);
912 const Char * data() const {
913 return backend_.data();
915 Char * mutable_data() {
916 //assert(!backend_.empty());
917 return &*backend_.begin();
919 void shrink(size_t delta) {
920 assert(delta <= size());
921 backend_.resize(size() - delta);
923 Char * expand_noinit(size_t delta) {
924 auto const sz = size();
925 backend_.resize(size() + delta);
926 return backend_.data() + sz;
928 void push_back(Char c) {
929 backend_.push_back(c);
931 size_t size() const {
932 return backend_.size();
934 size_t capacity() const {
935 return backend_.capacity();
937 bool isShared() const {
940 void reserve(size_t minCapacity) {
941 backend_.reserve(minCapacity);
945 std::basic_string<Char> backend_;
947 #endif // !_LIBSTDCXX_FBSTRING
950 * This is the basic_string replacement. For conformity,
951 * basic_fbstring takes the same template parameters, plus the last
952 * one which is the core.
954 #ifdef _LIBSTDCXX_FBSTRING
955 template <typename E, class T, class A, class Storage>
957 template <typename E,
958 class T = std::char_traits<E>,
959 class A = std::allocator<E>,
960 class Storage = fbstring_core<E> >
962 class basic_fbstring {
966 void (*throw_exc)(const char*),
968 if (!condition) throw_exc(msg);
971 bool isSane() const {
974 empty() == (size() == 0) &&
975 empty() == (begin() == end()) &&
976 size() <= max_size() &&
977 capacity() <= max_size() &&
978 size() <= capacity() &&
979 begin()[size()] == '\0';
983 friend struct Invariant;
986 explicit Invariant(const basic_fbstring& s) : s_(s) {
993 const basic_fbstring& s_;
995 explicit Invariant(const basic_fbstring&) {}
997 Invariant& operator=(const Invariant&);
1002 typedef T traits_type;
1003 typedef typename traits_type::char_type value_type;
1004 typedef A allocator_type;
1005 typedef typename A::size_type size_type;
1006 typedef typename A::difference_type difference_type;
1008 typedef typename A::reference reference;
1009 typedef typename A::const_reference const_reference;
1010 typedef typename A::pointer pointer;
1011 typedef typename A::const_pointer const_pointer;
1013 typedef E* iterator;
1014 typedef const E* const_iterator;
1015 typedef std::reverse_iterator<iterator
1016 #ifdef NO_ITERATOR_TRAITS
1020 typedef std::reverse_iterator<const_iterator
1021 #ifdef NO_ITERATOR_TRAITS
1024 > const_reverse_iterator;
1026 static const size_type npos; // = size_type(-1)
1029 static void procrustes(size_type& n, size_type nmax) {
1030 if (n > nmax) n = nmax;
1034 // C++11 21.4.2 construct/copy/destroy
1035 explicit basic_fbstring(const A& /*a*/ = A()) noexcept {
1038 basic_fbstring(const basic_fbstring& str)
1039 : store_(str.store_) {
1043 basic_fbstring(basic_fbstring&& goner) noexcept
1044 : store_(std::move(goner.store_)) {
1047 #ifndef _LIBSTDCXX_FBSTRING
1048 // This is defined for compatibility with std::string
1049 /* implicit */ basic_fbstring(const std::string& str)
1050 : store_(str.data(), str.size()) {
1054 basic_fbstring(const basic_fbstring& str, size_type pos,
1055 size_type n = npos, const A& a = A()) {
1056 assign(str, pos, n);
1059 /* implicit */ basic_fbstring(const value_type* s, const A& /*a*/ = A())
1061 ? traits_type::length(s)
1062 : (std::__throw_logic_error(
1063 "basic_fbstring: null pointer initializer not valid"),
1067 basic_fbstring(const value_type* s, size_type n, const A& /*a*/ = A())
1071 basic_fbstring(size_type n, value_type c, const A& /*a*/ = A()) {
1072 auto const data = store_.expand_noinit(n);
1073 fbstring_detail::pod_fill(data, data + n, c);
1074 store_.writeTerminator();
1077 template <class InIt>
1078 basic_fbstring(InIt begin, InIt end,
1079 typename std::enable_if<
1080 !std::is_same<typename std::remove_const<InIt>::type,
1081 value_type*>::value, const A>::type & /*a*/ = A()) {
1085 // Specialization for const char*, const char*
1086 basic_fbstring(const value_type* b, const value_type* e)
1087 : store_(b, e - b) {
1090 // Nonstandard constructor
1091 basic_fbstring(value_type *s, size_type n, size_type c,
1092 AcquireMallocatedString a)
1093 : store_(s, n, c, a) {
1096 // Construction from initialization list
1097 basic_fbstring(std::initializer_list<value_type> il) {
1098 assign(il.begin(), il.end());
1101 ~basic_fbstring() noexcept {
1104 basic_fbstring& operator=(const basic_fbstring& lhs) {
1105 if (FBSTRING_UNLIKELY(&lhs == this)) {
1108 auto const oldSize = size();
1109 auto const srcSize = lhs.size();
1110 if (capacity() >= srcSize && !store_.isShared()) {
1111 // great, just copy the contents
1112 if (oldSize < srcSize)
1113 store_.expand_noinit(srcSize - oldSize);
1115 store_.shrink(oldSize - srcSize);
1116 assert(size() == srcSize);
1117 fbstring_detail::pod_copy(lhs.begin(), lhs.end(), begin());
1118 store_.writeTerminator();
1120 // need to reallocate, so we may as well create a brand new string
1121 basic_fbstring(lhs).swap(*this);
1127 basic_fbstring& operator=(basic_fbstring&& goner) noexcept {
1128 if (FBSTRING_UNLIKELY(&goner == this)) {
1129 // Compatibility with std::basic_string<>,
1130 // C++11 21.4.2 [string.cons] / 23 requires self-move-assignment support.
1133 // No need of this anymore
1134 this->~basic_fbstring();
1135 // Move the goner into this
1136 new(&store_) fbstring_core<E>(std::move(goner.store_));
1140 #ifndef _LIBSTDCXX_FBSTRING
1141 // Compatibility with std::string
1142 basic_fbstring & operator=(const std::string & rhs) {
1143 return assign(rhs.data(), rhs.size());
1146 // Compatibility with std::string
1147 std::string toStdString() const {
1148 return std::string(data(), size());
1151 // A lot of code in fbcode still uses this method, so keep it here for now.
1152 const basic_fbstring& toStdString() const {
1157 basic_fbstring& operator=(const value_type* s) {
1161 basic_fbstring& operator=(value_type c) {
1163 store_.expand_noinit(1);
1164 } else if (store_.isShared()) {
1165 basic_fbstring(1, c).swap(*this);
1168 store_.shrink(size() - 1);
1170 *store_.mutable_data() = c;
1171 store_.writeTerminator();
1175 basic_fbstring& operator=(std::initializer_list<value_type> il) {
1176 return assign(il.begin(), il.end());
1179 // C++11 21.4.3 iterators:
1180 iterator begin() { return store_.mutable_data(); }
1182 const_iterator begin() const { return store_.data(); }
1184 const_iterator cbegin() const { return begin(); }
1187 return store_.mutable_data() + store_.size();
1190 const_iterator end() const {
1191 return store_.data() + store_.size();
1194 const_iterator cend() const { return end(); }
1196 reverse_iterator rbegin() {
1197 return reverse_iterator(end());
1200 const_reverse_iterator rbegin() const {
1201 return const_reverse_iterator(end());
1204 const_reverse_iterator crbegin() const { return rbegin(); }
1206 reverse_iterator rend() {
1207 return reverse_iterator(begin());
1210 const_reverse_iterator rend() const {
1211 return const_reverse_iterator(begin());
1214 const_reverse_iterator crend() const { return rend(); }
1217 // C++11 21.4.5, element access:
1218 const value_type& front() const { return *begin(); }
1219 const value_type& back() const {
1221 // Should be begin()[size() - 1], but that branches twice
1222 return *(end() - 1);
1224 value_type& front() { return *begin(); }
1225 value_type& back() {
1227 // Should be begin()[size() - 1], but that branches twice
1228 return *(end() - 1);
1235 // C++11 21.4.4 capacity:
1236 size_type size() const { return store_.size(); }
1238 size_type length() const { return size(); }
1240 size_type max_size() const {
1241 return std::numeric_limits<size_type>::max();
1244 void resize(const size_type n, const value_type c = value_type()) {
1245 auto size = this->size();
1247 store_.shrink(size - n);
1249 // Do this in two steps to minimize slack memory copied (see
1251 auto const capacity = this->capacity();
1252 assert(capacity >= size);
1253 if (size < capacity) {
1254 auto delta = std::min(n, capacity) - size;
1255 store_.expand_noinit(delta);
1256 fbstring_detail::pod_fill(begin() + size, end(), c);
1259 store_.writeTerminator();
1264 auto const delta = n - size;
1265 store_.expand_noinit(delta);
1266 fbstring_detail::pod_fill(end() - delta, end(), c);
1267 store_.writeTerminator();
1269 assert(this->size() == n);
1272 size_type capacity() const { return store_.capacity(); }
1274 void reserve(size_type res_arg = 0) {
1275 enforce(res_arg <= max_size(), std::__throw_length_error, "");
1276 store_.reserve(res_arg);
1279 void shrink_to_fit() {
1280 // Shrink only if slack memory is sufficiently large
1281 if (capacity() < size() * 3 / 2) {
1284 basic_fbstring(cbegin(), cend()).swap(*this);
1287 void clear() { resize(0); }
1289 bool empty() const { return size() == 0; }
1291 // C++11 21.4.5 element access:
1292 const_reference operator[](size_type pos) const {
1293 return *(begin() + pos);
1296 reference operator[](size_type pos) {
1297 return *(begin() + pos);
1300 const_reference at(size_type n) const {
1301 enforce(n <= size(), std::__throw_out_of_range, "");
1305 reference at(size_type n) {
1306 enforce(n < size(), std::__throw_out_of_range, "");
1310 // C++11 21.4.6 modifiers:
1311 basic_fbstring& operator+=(const basic_fbstring& str) {
1315 basic_fbstring& operator+=(const value_type* s) {
1319 basic_fbstring& operator+=(const value_type c) {
1324 basic_fbstring& operator+=(std::initializer_list<value_type> il) {
1329 basic_fbstring& append(const basic_fbstring& str) {
1331 auto desiredSize = size() + str.size();
1333 append(str.data(), str.size());
1334 assert(size() == desiredSize);
1338 basic_fbstring& append(const basic_fbstring& str, const size_type pos,
1340 const size_type sz = str.size();
1341 enforce(pos <= sz, std::__throw_out_of_range, "");
1342 procrustes(n, sz - pos);
1343 return append(str.data() + pos, n);
1346 basic_fbstring& append(const value_type* s, size_type n) {
1348 Invariant checker(*this);
1351 if (FBSTRING_UNLIKELY(!n)) {
1352 // Unlikely but must be done
1355 auto const oldSize = size();
1356 auto const oldData = data();
1357 // Check for aliasing (rare). We could use "<=" here but in theory
1358 // those do not work for pointers unless the pointers point to
1359 // elements in the same array. For that reason we use
1360 // std::less_equal, which is guaranteed to offer a total order
1361 // over pointers. See discussion at http://goo.gl/Cy2ya for more
1363 std::less_equal<const value_type*> le;
1364 if (FBSTRING_UNLIKELY(le(oldData, s) && !le(oldData + oldSize, s))) {
1365 assert(le(s + n, oldData + oldSize));
1366 const size_type offset = s - oldData;
1367 store_.reserve(oldSize + n);
1368 // Restore the source
1369 s = data() + offset;
1371 // Warning! Repeated appends with short strings may actually incur
1372 // practically quadratic performance. Avoid that by pushing back
1373 // the first character (which ensures exponential growth) and then
1374 // appending the rest normally. Worst case the append may incur a
1375 // second allocation but that will be rare.
1378 memcpy(store_.expand_noinit(n), s, n * sizeof(value_type));
1379 assert(size() == oldSize + n + 1);
1383 basic_fbstring& append(const value_type* s) {
1384 return append(s, traits_type::length(s));
1387 basic_fbstring& append(size_type n, value_type c) {
1388 resize(size() + n, c);
1392 template<class InputIterator>
1393 basic_fbstring& append(InputIterator first, InputIterator last) {
1394 insert(end(), first, last);
1398 basic_fbstring& append(std::initializer_list<value_type> il) {
1399 return append(il.begin(), il.end());
1402 void push_back(const value_type c) { // primitive
1403 store_.push_back(c);
1406 basic_fbstring& assign(const basic_fbstring& str) {
1407 if (&str == this) return *this;
1408 return assign(str.data(), str.size());
1411 basic_fbstring& assign(basic_fbstring&& str) {
1412 return *this = std::move(str);
1415 basic_fbstring& assign(const basic_fbstring& str, const size_type pos,
1417 const size_type sz = str.size();
1418 enforce(pos <= sz, std::__throw_out_of_range, "");
1419 procrustes(n, sz - pos);
1420 return assign(str.data() + pos, n);
1423 basic_fbstring& assign(const value_type* s, const size_type n) {
1424 Invariant checker(*this);
1427 std::copy(s, s + n, begin());
1429 assert(size() == n);
1431 const value_type *const s2 = s + size();
1432 std::copy(s, s2, begin());
1433 append(s2, n - size());
1434 assert(size() == n);
1436 store_.writeTerminator();
1437 assert(size() == n);
1441 basic_fbstring& assign(const value_type* s) {
1442 return assign(s, traits_type::length(s));
1445 basic_fbstring& assign(std::initializer_list<value_type> il) {
1446 return assign(il.begin(), il.end());
1449 template <class ItOrLength, class ItOrChar>
1450 basic_fbstring& assign(ItOrLength first_or_n, ItOrChar last_or_c) {
1451 return replace(begin(), end(), first_or_n, last_or_c);
1454 basic_fbstring& insert(size_type pos1, const basic_fbstring& str) {
1455 return insert(pos1, str.data(), str.size());
1458 basic_fbstring& insert(size_type pos1, const basic_fbstring& str,
1459 size_type pos2, size_type n) {
1460 enforce(pos2 <= str.length(), std::__throw_out_of_range, "");
1461 procrustes(n, str.length() - pos2);
1462 return insert(pos1, str.data() + pos2, n);
1465 basic_fbstring& insert(size_type pos, const value_type* s, size_type n) {
1466 enforce(pos <= length(), std::__throw_out_of_range, "");
1467 insert(begin() + pos, s, s + n);
1471 basic_fbstring& insert(size_type pos, const value_type* s) {
1472 return insert(pos, s, traits_type::length(s));
1475 basic_fbstring& insert(size_type pos, size_type n, value_type c) {
1476 enforce(pos <= length(), std::__throw_out_of_range, "");
1477 insert(begin() + pos, n, c);
1481 iterator insert(const_iterator p, const value_type c) {
1482 const size_type pos = p - begin();
1484 return begin() + pos;
1488 template <int i> class Selector {};
1490 iterator insertImplDiscr(const_iterator p,
1491 size_type n, value_type c, Selector<1>) {
1492 Invariant checker(*this);
1494 auto const pos = p - begin();
1495 assert(p >= begin() && p <= end());
1496 if (capacity() - size() < n) {
1497 const size_type sz = p - begin();
1498 reserve(size() + n);
1501 const iterator oldEnd = end();
1502 if (n < size_type(oldEnd - p)) {
1503 append(oldEnd - n, oldEnd);
1505 // reverse_iterator(oldEnd - n),
1506 // reverse_iterator(p),
1507 // reverse_iterator(oldEnd));
1508 fbstring_detail::pod_move(&*p, &*oldEnd - n,
1510 std::fill(begin() + pos, begin() + pos + n, c);
1512 append(n - (end() - p), c);
1513 append(iterator(p), oldEnd);
1514 std::fill(iterator(p), oldEnd, c);
1516 store_.writeTerminator();
1517 return begin() + pos;
1520 template<class InputIter>
1521 iterator insertImplDiscr(const_iterator i,
1522 InputIter b, InputIter e, Selector<0>) {
1523 return insertImpl(i, b, e,
1524 typename std::iterator_traits<InputIter>::iterator_category());
1527 template <class FwdIterator>
1528 iterator insertImpl(const_iterator i,
1529 FwdIterator s1, FwdIterator s2, std::forward_iterator_tag) {
1530 Invariant checker(*this);
1532 const size_type pos = i - begin();
1533 const typename std::iterator_traits<FwdIterator>::difference_type n2 =
1534 std::distance(s1, s2);
1536 using namespace fbstring_detail;
1537 assert(pos <= size());
1539 const typename std::iterator_traits<FwdIterator>::difference_type maxn2 =
1540 capacity() - size();
1542 // realloc the string
1543 reserve(size() + n2);
1546 if (pos + n2 <= size()) {
1547 const iterator tailBegin = end() - n2;
1548 store_.expand_noinit(n2);
1549 fbstring_detail::pod_copy(tailBegin, tailBegin + n2, end() - n2);
1550 std::copy(const_reverse_iterator(tailBegin), const_reverse_iterator(i),
1551 reverse_iterator(tailBegin + n2));
1552 std::copy(s1, s2, begin() + pos);
1555 const size_type old_size = size();
1556 std::advance(t, old_size - pos);
1557 const size_t newElems = std::distance(t, s2);
1558 store_.expand_noinit(n2);
1559 std::copy(t, s2, begin() + old_size);
1560 fbstring_detail::pod_copy(data() + pos, data() + old_size,
1561 begin() + old_size + newElems);
1562 std::copy(s1, t, begin() + pos);
1564 store_.writeTerminator();
1565 return begin() + pos;
1568 template <class InputIterator>
1569 iterator insertImpl(const_iterator i,
1570 InputIterator b, InputIterator e,
1571 std::input_iterator_tag) {
1572 const auto pos = i - begin();
1573 basic_fbstring temp(begin(), i);
1574 for (; b != e; ++b) {
1577 temp.append(i, cend());
1579 return begin() + pos;
1583 template <class ItOrLength, class ItOrChar>
1584 iterator insert(const_iterator p, ItOrLength first_or_n, ItOrChar last_or_c) {
1585 Selector<std::numeric_limits<ItOrLength>::is_specialized> sel;
1586 return insertImplDiscr(p, first_or_n, last_or_c, sel);
1589 iterator insert(const_iterator p, std::initializer_list<value_type> il) {
1590 return insert(p, il.begin(), il.end());
1593 basic_fbstring& erase(size_type pos = 0, size_type n = npos) {
1594 Invariant checker(*this);
1596 enforce(pos <= length(), std::__throw_out_of_range, "");
1597 procrustes(n, length() - pos);
1598 std::copy(begin() + pos + n, end(), begin() + pos);
1599 resize(length() - n);
1603 iterator erase(iterator position) {
1604 const size_type pos(position - begin());
1605 enforce(pos <= size(), std::__throw_out_of_range, "");
1607 return begin() + pos;
1610 iterator erase(iterator first, iterator last) {
1611 const size_type pos(first - begin());
1612 erase(pos, last - first);
1613 return begin() + pos;
1616 // Replaces at most n1 chars of *this, starting with pos1 with the
1618 basic_fbstring& replace(size_type pos1, size_type n1,
1619 const basic_fbstring& str) {
1620 return replace(pos1, n1, str.data(), str.size());
1623 // Replaces at most n1 chars of *this, starting with pos1,
1624 // with at most n2 chars of str starting with pos2
1625 basic_fbstring& replace(size_type pos1, size_type n1,
1626 const basic_fbstring& str,
1627 size_type pos2, size_type n2) {
1628 enforce(pos2 <= str.length(), std::__throw_out_of_range, "");
1629 return replace(pos1, n1, str.data() + pos2,
1630 std::min(n2, str.size() - pos2));
1633 // Replaces at most n1 chars of *this, starting with pos, with chars from s
1634 basic_fbstring& replace(size_type pos, size_type n1, const value_type* s) {
1635 return replace(pos, n1, s, traits_type::length(s));
1638 // Replaces at most n1 chars of *this, starting with pos, with n2
1641 // consolidated with
1643 // Replaces at most n1 chars of *this, starting with pos, with at
1644 // most n2 chars of str. str must have at least n2 chars.
1645 template <class StrOrLength, class NumOrChar>
1646 basic_fbstring& replace(size_type pos, size_type n1,
1647 StrOrLength s_or_n2, NumOrChar n_or_c) {
1648 Invariant checker(*this);
1650 enforce(pos <= size(), std::__throw_out_of_range, "");
1651 procrustes(n1, length() - pos);
1652 const iterator b = begin() + pos;
1653 return replace(b, b + n1, s_or_n2, n_or_c);
1656 basic_fbstring& replace(iterator i1, iterator i2, const basic_fbstring& str) {
1657 return replace(i1, i2, str.data(), str.length());
1660 basic_fbstring& replace(iterator i1, iterator i2, const value_type* s) {
1661 return replace(i1, i2, s, traits_type::length(s));
1665 basic_fbstring& replaceImplDiscr(iterator i1, iterator i2,
1666 const value_type* s, size_type n,
1669 assert(begin() <= i1 && i1 <= end());
1670 assert(begin() <= i2 && i2 <= end());
1671 return replace(i1, i2, s, s + n);
1674 basic_fbstring& replaceImplDiscr(iterator i1, iterator i2,
1675 size_type n2, value_type c, Selector<1>) {
1676 const size_type n1 = i2 - i1;
1678 std::fill(i1, i1 + n2, c);
1681 std::fill(i1, i2, c);
1682 insert(i2, n2 - n1, c);
1688 template <class InputIter>
1689 basic_fbstring& replaceImplDiscr(iterator i1, iterator i2,
1690 InputIter b, InputIter e,
1692 replaceImpl(i1, i2, b, e,
1693 typename std::iterator_traits<InputIter>::iterator_category());
1698 template <class FwdIterator>
1699 bool replaceAliased(iterator i1, iterator i2,
1700 FwdIterator s1, FwdIterator s2, std::false_type) {
1704 template <class FwdIterator>
1705 bool replaceAliased(iterator i1, iterator i2,
1706 FwdIterator s1, FwdIterator s2, std::true_type) {
1707 static const std::less_equal<const value_type*> le =
1708 std::less_equal<const value_type*>();
1709 const bool aliased = le(&*begin(), &*s1) && le(&*s1, &*end());
1713 // Aliased replace, copy to new string
1714 basic_fbstring temp;
1715 temp.reserve(size() - (i2 - i1) + std::distance(s1, s2));
1716 temp.append(begin(), i1).append(s1, s2).append(i2, end());
1721 template <class FwdIterator>
1722 void replaceImpl(iterator i1, iterator i2,
1723 FwdIterator s1, FwdIterator s2, std::forward_iterator_tag) {
1724 Invariant checker(*this);
1727 // Handle aliased replace
1728 if (replaceAliased(i1, i2, s1, s2,
1729 std::integral_constant<bool,
1730 std::is_same<FwdIterator, iterator>::value ||
1731 std::is_same<FwdIterator, const_iterator>::value>())) {
1735 auto const n1 = i2 - i1;
1737 auto const n2 = std::distance(s1, s2);
1742 std::copy(s1, s2, i1);
1746 fbstring_detail::copy_n(s1, n1, i1);
1747 std::advance(s1, n1);
1753 template <class InputIterator>
1754 void replaceImpl(iterator i1, iterator i2,
1755 InputIterator b, InputIterator e, std::input_iterator_tag) {
1756 basic_fbstring temp(begin(), i1);
1757 temp.append(b, e).append(i2, end());
1762 template <class T1, class T2>
1763 basic_fbstring& replace(iterator i1, iterator i2,
1764 T1 first_or_n_or_s, T2 last_or_c_or_n) {
1766 num1 = std::numeric_limits<T1>::is_specialized,
1767 num2 = std::numeric_limits<T2>::is_specialized;
1768 return replaceImplDiscr(
1769 i1, i2, first_or_n_or_s, last_or_c_or_n,
1770 Selector<num1 ? (num2 ? 1 : -1) : (num2 ? 2 : 0)>());
1773 size_type copy(value_type* s, size_type n, size_type pos = 0) const {
1774 enforce(pos <= size(), std::__throw_out_of_range, "");
1775 procrustes(n, size() - pos);
1777 fbstring_detail::pod_copy(
1784 void swap(basic_fbstring& rhs) {
1785 store_.swap(rhs.store_);
1788 const value_type* c_str() const {
1789 return store_.c_str();
1792 const value_type* data() const { return c_str(); }
1794 allocator_type get_allocator() const {
1795 return allocator_type();
1798 size_type find(const basic_fbstring& str, size_type pos = 0) const {
1799 return find(str.data(), pos, str.length());
1802 size_type find(const value_type* needle, const size_type pos,
1803 const size_type nsize) const {
1804 if (!nsize) return pos;
1805 auto const size = this->size();
1806 // nsize + pos can overflow (eg pos == npos), guard against that by checking
1807 // that nsize + pos does not wrap around.
1808 if (nsize + pos > size || nsize + pos < pos) return npos;
1809 // Don't use std::search, use a Boyer-Moore-like trick by comparing
1810 // the last characters first
1811 auto const haystack = data();
1812 auto const nsize_1 = nsize - 1;
1813 auto const lastNeedle = needle[nsize_1];
1815 // Boyer-Moore skip value for the last char in the needle. Zero is
1816 // not a valid value; skip will be computed the first time it's
1820 const E * i = haystack + pos;
1821 auto iEnd = haystack + size - nsize_1;
1824 // Boyer-Moore: match the last element in the needle
1825 while (i[nsize_1] != lastNeedle) {
1831 // Here we know that the last char matches
1832 // Continue in pedestrian mode
1833 for (size_t j = 0; ; ) {
1835 if (i[j] != needle[j]) {
1836 // Not found, we can skip
1837 // Compute the skip value lazily
1840 while (skip <= nsize_1 && needle[nsize_1 - skip] != lastNeedle) {
1847 // Check if done searching
1850 return i - haystack;
1857 size_type find(const value_type* s, size_type pos = 0) const {
1858 return find(s, pos, traits_type::length(s));
1861 size_type find (value_type c, size_type pos = 0) const {
1862 return find(&c, pos, 1);
1865 size_type rfind(const basic_fbstring& str, size_type pos = npos) const {
1866 return rfind(str.data(), pos, str.length());
1869 size_type rfind(const value_type* s, size_type pos, size_type n) const {
1870 if (n > length()) return npos;
1871 pos = std::min(pos, length() - n);
1872 if (n == 0) return pos;
1874 const_iterator i(begin() + pos);
1876 if (traits_type::eq(*i, *s)
1877 && traits_type::compare(&*i, s, n) == 0) {
1880 if (i == begin()) break;
1885 size_type rfind(const value_type* s, size_type pos = npos) const {
1886 return rfind(s, pos, traits_type::length(s));
1889 size_type rfind(value_type c, size_type pos = npos) const {
1890 return rfind(&c, pos, 1);
1893 size_type find_first_of(const basic_fbstring& str, size_type pos = 0) const {
1894 return find_first_of(str.data(), pos, str.length());
1897 size_type find_first_of(const value_type* s,
1898 size_type pos, size_type n) const {
1899 if (pos > length() || n == 0) return npos;
1900 const_iterator i(begin() + pos),
1902 for (; i != finish; ++i) {
1903 if (traits_type::find(s, n, *i) != 0) {
1910 size_type find_first_of(const value_type* s, size_type pos = 0) const {
1911 return find_first_of(s, pos, traits_type::length(s));
1914 size_type find_first_of(value_type c, size_type pos = 0) const {
1915 return find_first_of(&c, pos, 1);
1918 size_type find_last_of (const basic_fbstring& str,
1919 size_type pos = npos) const {
1920 return find_last_of(str.data(), pos, str.length());
1923 size_type find_last_of (const value_type* s, size_type pos,
1924 size_type n) const {
1925 if (!empty() && n > 0) {
1926 pos = std::min(pos, length() - 1);
1927 const_iterator i(begin() + pos);
1929 if (traits_type::find(s, n, *i) != 0) {
1932 if (i == begin()) break;
1938 size_type find_last_of (const value_type* s,
1939 size_type pos = npos) const {
1940 return find_last_of(s, pos, traits_type::length(s));
1943 size_type find_last_of (value_type c, size_type pos = npos) const {
1944 return find_last_of(&c, pos, 1);
1947 size_type find_first_not_of(const basic_fbstring& str,
1948 size_type pos = 0) const {
1949 return find_first_not_of(str.data(), pos, str.size());
1952 size_type find_first_not_of(const value_type* s, size_type pos,
1953 size_type n) const {
1954 if (pos < length()) {
1958 for (; i != finish; ++i) {
1959 if (traits_type::find(s, n, *i) == 0) {
1967 size_type find_first_not_of(const value_type* s,
1968 size_type pos = 0) const {
1969 return find_first_not_of(s, pos, traits_type::length(s));
1972 size_type find_first_not_of(value_type c, size_type pos = 0) const {
1973 return find_first_not_of(&c, pos, 1);
1976 size_type find_last_not_of(const basic_fbstring& str,
1977 size_type pos = npos) const {
1978 return find_last_not_of(str.data(), pos, str.length());
1981 size_type find_last_not_of(const value_type* s, size_type pos,
1982 size_type n) const {
1983 if (!this->empty()) {
1984 pos = std::min(pos, size() - 1);
1985 const_iterator i(begin() + pos);
1987 if (traits_type::find(s, n, *i) == 0) {
1990 if (i == begin()) break;
1996 size_type find_last_not_of(const value_type* s,
1997 size_type pos = npos) const {
1998 return find_last_not_of(s, pos, traits_type::length(s));
2001 size_type find_last_not_of (value_type c, size_type pos = npos) const {
2002 return find_last_not_of(&c, pos, 1);
2005 basic_fbstring substr(size_type pos = 0, size_type n = npos) const& {
2006 enforce(pos <= size(), std::__throw_out_of_range, "");
2007 return basic_fbstring(data() + pos, std::min(n, size() - pos));
2010 basic_fbstring substr(size_type pos = 0, size_type n = npos) && {
2011 enforce(pos <= size(), std::__throw_out_of_range, "");
2013 if (n < size()) resize(n);
2014 return std::move(*this);
2017 int compare(const basic_fbstring& str) const {
2018 // FIX due to Goncalo N M de Carvalho July 18, 2005
2019 return compare(0, size(), str);
2022 int compare(size_type pos1, size_type n1,
2023 const basic_fbstring& str) const {
2024 return compare(pos1, n1, str.data(), str.size());
2027 int compare(size_type pos1, size_type n1,
2028 const value_type* s) const {
2029 return compare(pos1, n1, s, traits_type::length(s));
2032 int compare(size_type pos1, size_type n1,
2033 const value_type* s, size_type n2) const {
2034 enforce(pos1 <= size(), std::__throw_out_of_range, "");
2035 procrustes(n1, size() - pos1);
2036 // The line below fixed by Jean-Francois Bastien, 04-23-2007. Thanks!
2037 const int r = traits_type::compare(pos1 + data(), s, std::min(n1, n2));
2038 return r != 0 ? r : n1 > n2 ? 1 : n1 < n2 ? -1 : 0;
2041 int compare(size_type pos1, size_type n1,
2042 const basic_fbstring& str,
2043 size_type pos2, size_type n2) const {
2044 enforce(pos2 <= str.size(), std::__throw_out_of_range, "");
2045 return compare(pos1, n1, str.data() + pos2,
2046 std::min(n2, str.size() - pos2));
2049 // Code from Jean-Francois Bastien (03/26/2007)
2050 int compare(const value_type* s) const {
2051 // Could forward to compare(0, size(), s, traits_type::length(s))
2052 // but that does two extra checks
2053 const size_type n1(size()), n2(traits_type::length(s));
2054 const int r = traits_type::compare(data(), s, std::min(n1, n2));
2055 return r != 0 ? r : n1 > n2 ? 1 : n1 < n2 ? -1 : 0;
2063 // non-member functions
2065 template <typename E, class T, class A, class S>
2067 basic_fbstring<E, T, A, S> operator+(const basic_fbstring<E, T, A, S>& lhs,
2068 const basic_fbstring<E, T, A, S>& rhs) {
2070 basic_fbstring<E, T, A, S> result;
2071 result.reserve(lhs.size() + rhs.size());
2072 result.append(lhs).append(rhs);
2073 return std::move(result);
2077 template <typename E, class T, class A, class S>
2079 basic_fbstring<E, T, A, S> operator+(basic_fbstring<E, T, A, S>&& lhs,
2080 const basic_fbstring<E, T, A, S>& rhs) {
2081 return std::move(lhs.append(rhs));
2085 template <typename E, class T, class A, class S>
2087 basic_fbstring<E, T, A, S> operator+(const basic_fbstring<E, T, A, S>& lhs,
2088 basic_fbstring<E, T, A, S>&& rhs) {
2089 if (rhs.capacity() >= lhs.size() + rhs.size()) {
2090 // Good, at least we don't need to reallocate
2091 return std::move(rhs.insert(0, lhs));
2093 // Meh, no go. Forward to operator+(const&, const&).
2094 auto const& rhsC = rhs;
2099 template <typename E, class T, class A, class S>
2101 basic_fbstring<E, T, A, S> operator+(basic_fbstring<E, T, A, S>&& lhs,
2102 basic_fbstring<E, T, A, S>&& rhs) {
2103 return std::move(lhs.append(rhs));
2107 template <typename E, class T, class A, class S>
2109 basic_fbstring<E, T, A, S> operator+(
2111 const basic_fbstring<E, T, A, S>& rhs) {
2113 basic_fbstring<E, T, A, S> result;
2114 const auto len = basic_fbstring<E, T, A, S>::traits_type::length(lhs);
2115 result.reserve(len + rhs.size());
2116 result.append(lhs, len).append(rhs);
2121 template <typename E, class T, class A, class S>
2123 basic_fbstring<E, T, A, S> operator+(
2125 basic_fbstring<E, T, A, S>&& rhs) {
2127 const auto len = basic_fbstring<E, T, A, S>::traits_type::length(lhs);
2128 if (rhs.capacity() >= len + rhs.size()) {
2129 // Good, at least we don't need to reallocate
2130 return std::move(rhs.insert(rhs.begin(), lhs, lhs + len));
2132 // Meh, no go. Do it by hand since we have len already.
2133 basic_fbstring<E, T, A, S> result;
2134 result.reserve(len + rhs.size());
2135 result.append(lhs, len).append(rhs);
2140 template <typename E, class T, class A, class S>
2142 basic_fbstring<E, T, A, S> operator+(
2144 const basic_fbstring<E, T, A, S>& rhs) {
2146 basic_fbstring<E, T, A, S> result;
2147 result.reserve(1 + rhs.size());
2148 result.push_back(lhs);
2154 template <typename E, class T, class A, class S>
2156 basic_fbstring<E, T, A, S> operator+(
2158 basic_fbstring<E, T, A, S>&& rhs) {
2160 if (rhs.capacity() > rhs.size()) {
2161 // Good, at least we don't need to reallocate
2162 return std::move(rhs.insert(rhs.begin(), lhs));
2164 // Meh, no go. Forward to operator+(E, const&).
2165 auto const& rhsC = rhs;
2170 template <typename E, class T, class A, class S>
2172 basic_fbstring<E, T, A, S> operator+(
2173 const basic_fbstring<E, T, A, S>& lhs,
2176 typedef typename basic_fbstring<E, T, A, S>::size_type size_type;
2177 typedef typename basic_fbstring<E, T, A, S>::traits_type traits_type;
2179 basic_fbstring<E, T, A, S> result;
2180 const size_type len = traits_type::length(rhs);
2181 result.reserve(lhs.size() + len);
2182 result.append(lhs).append(rhs, len);
2186 // C++11 21.4.8.1/10
2187 template <typename E, class T, class A, class S>
2189 basic_fbstring<E, T, A, S> operator+(
2190 basic_fbstring<E, T, A, S>&& lhs,
2193 return std::move(lhs += rhs);
2196 // C++11 21.4.8.1/11
2197 template <typename E, class T, class A, class S>
2199 basic_fbstring<E, T, A, S> operator+(
2200 const basic_fbstring<E, T, A, S>& lhs,
2203 basic_fbstring<E, T, A, S> result;
2204 result.reserve(lhs.size() + 1);
2206 result.push_back(rhs);
2210 // C++11 21.4.8.1/12
2211 template <typename E, class T, class A, class S>
2213 basic_fbstring<E, T, A, S> operator+(
2214 basic_fbstring<E, T, A, S>&& lhs,
2217 return std::move(lhs += rhs);
2220 template <typename E, class T, class A, class S>
2222 bool operator==(const basic_fbstring<E, T, A, S>& lhs,
2223 const basic_fbstring<E, T, A, S>& rhs) {
2224 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0; }
2226 template <typename E, class T, class A, class S>
2228 bool operator==(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2229 const basic_fbstring<E, T, A, S>& rhs) {
2230 return rhs == lhs; }
2232 template <typename E, class T, class A, class S>
2234 bool operator==(const basic_fbstring<E, T, A, S>& lhs,
2235 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2236 return lhs.compare(rhs) == 0; }
2238 template <typename E, class T, class A, class S>
2240 bool operator!=(const basic_fbstring<E, T, A, S>& lhs,
2241 const basic_fbstring<E, T, A, S>& rhs) {
2242 return !(lhs == rhs); }
2244 template <typename E, class T, class A, class S>
2246 bool operator!=(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2247 const basic_fbstring<E, T, A, S>& rhs) {
2248 return !(lhs == rhs); }
2250 template <typename E, class T, class A, class S>
2252 bool operator!=(const basic_fbstring<E, T, A, S>& lhs,
2253 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2254 return !(lhs == rhs); }
2256 template <typename E, class T, class A, class S>
2258 bool operator<(const basic_fbstring<E, T, A, S>& lhs,
2259 const basic_fbstring<E, T, A, S>& rhs) {
2260 return lhs.compare(rhs) < 0; }
2262 template <typename E, class T, class A, class S>
2264 bool operator<(const basic_fbstring<E, T, A, S>& lhs,
2265 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2266 return lhs.compare(rhs) < 0; }
2268 template <typename E, class T, class A, class S>
2270 bool operator<(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2271 const basic_fbstring<E, T, A, S>& rhs) {
2272 return rhs.compare(lhs) > 0; }
2274 template <typename E, class T, class A, class S>
2276 bool operator>(const basic_fbstring<E, T, A, S>& lhs,
2277 const basic_fbstring<E, T, A, S>& rhs) {
2280 template <typename E, class T, class A, class S>
2282 bool operator>(const basic_fbstring<E, T, A, S>& lhs,
2283 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2286 template <typename E, class T, class A, class S>
2288 bool operator>(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2289 const basic_fbstring<E, T, A, S>& rhs) {
2292 template <typename E, class T, class A, class S>
2294 bool operator<=(const basic_fbstring<E, T, A, S>& lhs,
2295 const basic_fbstring<E, T, A, S>& rhs) {
2296 return !(rhs < lhs); }
2298 template <typename E, class T, class A, class S>
2300 bool operator<=(const basic_fbstring<E, T, A, S>& lhs,
2301 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2302 return !(rhs < lhs); }
2304 template <typename E, class T, class A, class S>
2306 bool operator<=(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2307 const basic_fbstring<E, T, A, S>& rhs) {
2308 return !(rhs < lhs); }
2310 template <typename E, class T, class A, class S>
2312 bool operator>=(const basic_fbstring<E, T, A, S>& lhs,
2313 const basic_fbstring<E, T, A, S>& rhs) {
2314 return !(lhs < rhs); }
2316 template <typename E, class T, class A, class S>
2318 bool operator>=(const basic_fbstring<E, T, A, S>& lhs,
2319 const typename basic_fbstring<E, T, A, S>::value_type* rhs) {
2320 return !(lhs < rhs); }
2322 template <typename E, class T, class A, class S>
2324 bool operator>=(const typename basic_fbstring<E, T, A, S>::value_type* lhs,
2325 const basic_fbstring<E, T, A, S>& rhs) {
2326 return !(lhs < rhs);
2330 template <typename E, class T, class A, class S>
2331 void swap(basic_fbstring<E, T, A, S>& lhs, basic_fbstring<E, T, A, S>& rhs) {
2335 // TODO: make this faster.
2336 template <typename E, class T, class A, class S>
2339 typename basic_fbstring<E, T, A, S>::value_type,
2340 typename basic_fbstring<E, T, A, S>::traits_type>&
2342 std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2343 typename basic_fbstring<E, T, A, S>::traits_type>& is,
2344 basic_fbstring<E, T, A, S>& str) {
2345 typename std::basic_istream<E, T>::sentry sentry(is);
2346 typedef std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2347 typename basic_fbstring<E, T, A, S>::traits_type>
2349 typedef typename __istream_type::ios_base __ios_base;
2350 size_t extracted = 0;
2351 auto err = __ios_base::goodbit;
2353 auto n = is.width();
2358 for (auto got = is.rdbuf()->sgetc(); extracted != size_t(n); ++extracted) {
2359 if (got == T::eof()) {
2360 err |= __ios_base::eofbit;
2364 if (isspace(got)) break;
2366 got = is.rdbuf()->snextc();
2370 err |= __ios_base::failbit;
2378 template <typename E, class T, class A, class S>
2380 std::basic_ostream<typename basic_fbstring<E, T, A, S>::value_type,
2381 typename basic_fbstring<E, T, A, S>::traits_type>&
2383 std::basic_ostream<typename basic_fbstring<E, T, A, S>::value_type,
2384 typename basic_fbstring<E, T, A, S>::traits_type>& os,
2385 const basic_fbstring<E, T, A, S>& str) {
2387 typename std::basic_ostream<
2388 typename basic_fbstring<E, T, A, S>::value_type,
2389 typename basic_fbstring<E, T, A, S>::traits_type>::sentry __s(os);
2391 typedef std::ostreambuf_iterator<
2392 typename basic_fbstring<E, T, A, S>::value_type,
2393 typename basic_fbstring<E, T, A, S>::traits_type> _Ip;
2394 size_t __len = str.size();
2396 (os.flags() & std::ios_base::adjustfield) == std::ios_base::left;
2397 if (__pad_and_output(_Ip(os),
2399 __left ? str.data() + __len : str.data(),
2402 os.fill()).failed()) {
2403 os.setstate(std::ios_base::badbit | std::ios_base::failbit);
2406 #elif defined(_MSC_VER)
2407 // MSVC doesn't define __ostream_insert
2408 os.write(str.data(), str.size());
2410 std::__ostream_insert(os, str.data(), str.size());
2415 #ifndef _LIBSTDCXX_FBSTRING
2417 template <typename E, class T, class A, class S>
2419 std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2420 typename basic_fbstring<E, T, A, S>::traits_type>&
2422 std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2423 typename basic_fbstring<E, T, A, S>::traits_type>& is,
2424 basic_fbstring<E, T, A, S>& str,
2425 typename basic_fbstring<E, T, A, S>::value_type delim) {
2426 // Use the nonstandard getdelim()
2427 char * buf = nullptr;
2430 // This looks quadratic but it really depends on realloc
2431 auto const newSize = size + 128;
2432 buf = static_cast<char*>(checkedRealloc(buf, newSize));
2433 is.getline(buf + size, newSize - size, delim);
2434 if (is.bad() || is.eof() || !is.fail()) {
2435 // done by either failure, end of file, or normal read
2436 size += std::strlen(buf + size);
2439 // Here we have failed due to too short a buffer
2440 // Minus one to discount the terminating '\0'
2442 assert(buf[size] == 0);
2443 // Clear the error so we can continue reading
2446 basic_fbstring<E, T, A, S> result(buf, size, size + 1,
2447 AcquireMallocatedString());
2452 template <typename E, class T, class A, class S>
2454 std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2455 typename basic_fbstring<E, T, A, S>::traits_type>&
2457 std::basic_istream<typename basic_fbstring<E, T, A, S>::value_type,
2458 typename basic_fbstring<E, T, A, S>::traits_type>& is,
2459 basic_fbstring<E, T, A, S>& str) {
2460 // Just forward to the version with a delimiter
2461 return getline(is, str, '\n');
2466 template <typename E1, class T, class A, class S>
2467 const typename basic_fbstring<E1, T, A, S>::size_type
2468 basic_fbstring<E1, T, A, S>::npos =
2469 static_cast<typename basic_fbstring<E1, T, A, S>::size_type>(-1);
2471 #ifndef _LIBSTDCXX_FBSTRING
2472 // basic_string compatibility routines
2474 template <typename E, class T, class A, class S>
2476 bool operator==(const basic_fbstring<E, T, A, S>& lhs,
2477 const std::string& rhs) {
2478 return lhs.compare(0, lhs.size(), rhs.data(), rhs.size()) == 0;
2481 template <typename E, class T, class A, class S>
2483 bool operator==(const std::string& lhs,
2484 const basic_fbstring<E, T, A, S>& rhs) {
2488 template <typename E, class T, class A, class S>
2490 bool operator!=(const basic_fbstring<E, T, A, S>& lhs,
2491 const std::string& rhs) {
2492 return !(lhs == rhs);
2495 template <typename E, class T, class A, class S>
2497 bool operator!=(const std::string& lhs,
2498 const basic_fbstring<E, T, A, S>& rhs) {
2499 return !(lhs == rhs);
2502 #if !defined(_LIBSTDCXX_FBSTRING)
2503 typedef basic_fbstring<char> fbstring;
2506 // fbstring is relocatable
2507 template <class T, class R, class A, class S>
2508 FOLLY_ASSUME_RELOCATABLE(basic_fbstring<T, R, A, S>);
2511 _GLIBCXX_END_NAMESPACE_VERSION
2514 } // namespace folly
2516 #ifndef _LIBSTDCXX_FBSTRING
2518 // Hash functions to make fbstring usable with e.g. hash_map
2520 // Handle interaction with different C++ standard libraries, which
2521 // expect these types to be in different namespaces.
2523 #define FOLLY_FBSTRING_HASH1(T) \
2525 struct hash< ::folly::basic_fbstring<T> > { \
2526 size_t operator()(const ::folly::fbstring& s) const { \
2527 return ::folly::hash::fnv32_buf(s.data(), s.size()); \
2531 // The C++11 standard says that these four are defined
2532 #define FOLLY_FBSTRING_HASH \
2533 FOLLY_FBSTRING_HASH1(char) \
2534 FOLLY_FBSTRING_HASH1(char16_t) \
2535 FOLLY_FBSTRING_HASH1(char32_t) \
2536 FOLLY_FBSTRING_HASH1(wchar_t)
2544 #if FOLLY_HAVE_DEPRECATED_ASSOC
2545 #if defined(_GLIBCXX_SYMVER) && !defined(__BIONIC__)
2546 namespace __gnu_cxx {
2550 } // namespace __gnu_cxx
2551 #endif // _GLIBCXX_SYMVER && !__BIONIC__
2552 #endif // FOLLY_HAVE_DEPRECATED_ASSOC
2554 #undef FOLLY_FBSTRING_HASH
2555 #undef FOLLY_FBSTRING_HASH1
2557 #endif // _LIBSTDCXX_FBSTRING
2559 #pragma GCC diagnostic pop
2561 #undef FBSTRING_DISABLE_ADDRESS_SANITIZER
2563 #undef FBSTRING_LIKELY
2564 #undef FBSTRING_UNLIKELY
2566 #endif // FOLLY_BASE_FBSTRING_H_