Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-06-30 08:06:44

0001 // Copyright 2020 The Abseil Authors.
0002 //
0003 // Licensed under the Apache License, Version 2.0 (the "License");
0004 // you may not use this file except in compliance with the License.
0005 // You may obtain a copy of the License at
0006 //
0007 //      https://www.apache.org/licenses/LICENSE-2.0
0008 //
0009 // Unless required by applicable law or agreed to in writing, software
0010 // distributed under the License is distributed on an "AS IS" BASIS,
0011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0012 // See the License for the specific language governing permissions and
0013 // limitations under the License.
0014 //
0015 // -----------------------------------------------------------------------------
0016 // File: cord.h
0017 // -----------------------------------------------------------------------------
0018 //
0019 // This file defines the `absl::Cord` data structure and operations on that data
0020 // structure. A Cord is a string-like sequence of characters optimized for
0021 // specific use cases. Unlike a `std::string`, which stores an array of
0022 // contiguous characters, Cord data is stored in a structure consisting of
0023 // separate, reference-counted "chunks."
0024 //
0025 // Because a Cord consists of these chunks, data can be added to or removed from
0026 // a Cord during its lifetime. Chunks may also be shared between Cords. Unlike a
0027 // `std::string`, a Cord can therefore accommodate data that changes over its
0028 // lifetime, though it's not quite "mutable"; it can change only in the
0029 // attachment, detachment, or rearrangement of chunks of its constituent data.
0030 //
0031 // A Cord provides some benefit over `std::string` under the following (albeit
0032 // narrow) circumstances:
0033 //
0034 //   * Cord data is designed to grow and shrink over a Cord's lifetime. Cord
0035 //     provides efficient insertions and deletions at the start and end of the
0036 //     character sequences, avoiding copies in those cases. Static data should
0037 //     generally be stored as strings.
0038 //   * External memory consisting of string-like data can be directly added to
0039 //     a Cord without requiring copies or allocations.
0040 //   * Cord data may be shared and copied cheaply. Cord provides a copy-on-write
0041 //     implementation and cheap sub-Cord operations. Copying a Cord is an O(1)
0042 //     operation.
0043 //
0044 // As a consequence to the above, Cord data is generally large. Small data
0045 // should generally use strings, as construction of a Cord requires some
0046 // overhead. Small Cords (<= 15 bytes) are represented inline, but most small
0047 // Cords are expected to grow over their lifetimes.
0048 //
0049 // Note that because a Cord is made up of separate chunked data, random access
0050 // to character data within a Cord is slower than within a `std::string`.
0051 //
0052 // Thread Safety
0053 //
0054 // Cord has the same thread-safety properties as many other types like
0055 // std::string, std::vector<>, int, etc -- it is thread-compatible. In
0056 // particular, if threads do not call non-const methods, then it is safe to call
0057 // const methods without synchronization. Copying a Cord produces a new instance
0058 // that can be used concurrently with the original in arbitrary ways.
0059 
0060 #ifndef ABSL_STRINGS_CORD_H_
0061 #define ABSL_STRINGS_CORD_H_
0062 
0063 #include <algorithm>
0064 #include <cstddef>
0065 #include <cstdint>
0066 #include <cstring>
0067 #include <iosfwd>
0068 #include <iterator>
0069 #include <string>
0070 #include <type_traits>
0071 
0072 #include "absl/base/attributes.h"
0073 #include "absl/base/config.h"
0074 #include "absl/base/internal/endian.h"
0075 #include "absl/base/internal/per_thread_tls.h"
0076 #include "absl/base/macros.h"
0077 #include "absl/base/nullability.h"
0078 #include "absl/base/optimization.h"
0079 #include "absl/base/port.h"
0080 #include "absl/container/inlined_vector.h"
0081 #include "absl/crc/internal/crc_cord_state.h"
0082 #include "absl/functional/function_ref.h"
0083 #include "absl/meta/type_traits.h"
0084 #include "absl/strings/cord_analysis.h"
0085 #include "absl/strings/cord_buffer.h"
0086 #include "absl/strings/internal/cord_data_edge.h"
0087 #include "absl/strings/internal/cord_internal.h"
0088 #include "absl/strings/internal/cord_rep_btree.h"
0089 #include "absl/strings/internal/cord_rep_btree_reader.h"
0090 #include "absl/strings/internal/cord_rep_crc.h"
0091 #include "absl/strings/internal/cordz_functions.h"
0092 #include "absl/strings/internal/cordz_info.h"
0093 #include "absl/strings/internal/cordz_statistics.h"
0094 #include "absl/strings/internal/cordz_update_scope.h"
0095 #include "absl/strings/internal/cordz_update_tracker.h"
0096 #include "absl/strings/internal/resize_uninitialized.h"
0097 #include "absl/strings/internal/string_constant.h"
0098 #include "absl/strings/string_view.h"
0099 #include "absl/types/compare.h"
0100 #include "absl/types/optional.h"
0101 
0102 namespace absl {
0103 ABSL_NAMESPACE_BEGIN
0104 class Cord;
0105 class CordTestPeer;
0106 template <typename Releaser>
0107 Cord MakeCordFromExternal(absl::string_view, Releaser&&);
0108 void CopyCordToString(const Cord& src, absl::Nonnull<std::string*> dst);
0109 void AppendCordToString(const Cord& src, absl::Nonnull<std::string*> dst);
0110 
0111 // Cord memory accounting modes
0112 enum class CordMemoryAccounting {
0113   // Counts the *approximate* number of bytes held in full or in part by this
0114   // Cord (which may not remain the same between invocations). Cords that share
0115   // memory could each be "charged" independently for the same shared memory.
0116   // See also comment on `kTotalMorePrecise` on internally shared memory.
0117   kTotal,
0118 
0119   // Counts the *approximate* number of bytes held in full or in part by this
0120   // Cord for the distinct memory held by this cord. This option is similar
0121   // to `kTotal`, except that if the cord has multiple references to the same
0122   // memory, that memory is only counted once.
0123   //
0124   // For example:
0125   //   absl::Cord cord;
0126   //   cord.Append(some_other_cord);
0127   //   cord.Append(some_other_cord);
0128   //   // Counts `some_other_cord` twice:
0129   //   cord.EstimatedMemoryUsage(kTotal);
0130   //   // Counts `some_other_cord` once:
0131   //   cord.EstimatedMemoryUsage(kTotalMorePrecise);
0132   //
0133   // The `kTotalMorePrecise` number is more expensive to compute as it requires
0134   // deduplicating all memory references. Applications should prefer to use
0135   // `kFairShare` or `kTotal` unless they really need a more precise estimate
0136   // on "how much memory is potentially held / kept alive by this cord?"
0137   kTotalMorePrecise,
0138 
0139   // Counts the *approximate* number of bytes held in full or in part by this
0140   // Cord weighted by the sharing ratio of that data. For example, if some data
0141   // edge is shared by 4 different Cords, then each cord is attributed 1/4th of
0142   // the total memory usage as a 'fair share' of the total memory usage.
0143   kFairShare,
0144 };
0145 
0146 // Cord
0147 //
0148 // A Cord is a sequence of characters, designed to be more efficient than a
0149 // `std::string` in certain circumstances: namely, large string data that needs
0150 // to change over its lifetime or shared, especially when such data is shared
0151 // across API boundaries.
0152 //
0153 // A Cord stores its character data in a structure that allows efficient prepend
0154 // and append operations. This makes a Cord useful for large string data sent
0155 // over in a wire format that may need to be prepended or appended at some point
0156 // during the data exchange (e.g. HTTP, protocol buffers). For example, a
0157 // Cord is useful for storing an HTTP request, and prepending an HTTP header to
0158 // such a request.
0159 //
0160 // Cords should not be used for storing general string data, however. They
0161 // require overhead to construct and are slower than strings for random access.
0162 //
0163 // The Cord API provides the following common API operations:
0164 //
0165 // * Create or assign Cords out of existing string data, memory, or other Cords
0166 // * Append and prepend data to an existing Cord
0167 // * Create new Sub-Cords from existing Cord data
0168 // * Swap Cord data and compare Cord equality
0169 // * Write out Cord data by constructing a `std::string`
0170 //
0171 // Additionally, the API provides iterator utilities to iterate through Cord
0172 // data via chunks or character bytes.
0173 //
0174 class Cord {
0175  private:
0176   template <typename T>
0177   using EnableIfString =
0178       absl::enable_if_t<std::is_same<T, std::string>::value, int>;
0179 
0180  public:
0181   // Cord::Cord() Constructors.
0182 
0183   // Creates an empty Cord.
0184   constexpr Cord() noexcept;
0185 
0186   // Creates a Cord from an existing Cord. Cord is copyable and efficiently
0187   // movable. The moved-from state is valid but unspecified.
0188   Cord(const Cord& src);
0189   Cord(Cord&& src) noexcept;
0190   Cord& operator=(const Cord& x);
0191   Cord& operator=(Cord&& x) noexcept;
0192 
0193   // Creates a Cord from a `src` string. This constructor is marked explicit to
0194   // prevent implicit Cord constructions from arguments convertible to an
0195   // `absl::string_view`.
0196   explicit Cord(absl::string_view src);
0197   Cord& operator=(absl::string_view src);
0198 
0199   // Creates a Cord from a `std::string&&` rvalue. These constructors are
0200   // templated to avoid ambiguities for types that are convertible to both
0201   // `absl::string_view` and `std::string`, such as `const char*`.
0202   template <typename T, EnableIfString<T> = 0>
0203   explicit Cord(T&& src);
0204   template <typename T, EnableIfString<T> = 0>
0205   Cord& operator=(T&& src);
0206 
0207   // Cord::~Cord()
0208   //
0209   // Destructs the Cord.
0210   ~Cord() {
0211     if (contents_.is_tree()) DestroyCordSlow();
0212   }
0213 
0214   // MakeCordFromExternal()
0215   //
0216   // Creates a Cord that takes ownership of external string memory. The
0217   // contents of `data` are not copied to the Cord; instead, the external
0218   // memory is added to the Cord and reference-counted. This data may not be
0219   // changed for the life of the Cord, though it may be prepended or appended
0220   // to.
0221   //
0222   // `MakeCordFromExternal()` takes a callable "releaser" that is invoked when
0223   // the reference count for `data` reaches zero. As noted above, this data must
0224   // remain live until the releaser is invoked. The callable releaser also must:
0225   //
0226   //   * be move constructible
0227   //   * support `void operator()(absl::string_view) const` or `void operator()`
0228   //
0229   // Example:
0230   //
0231   // Cord MakeCord(BlockPool* pool) {
0232   //   Block* block = pool->NewBlock();
0233   //   FillBlock(block);
0234   //   return absl::MakeCordFromExternal(
0235   //       block->ToStringView(),
0236   //       [pool, block](absl::string_view v) {
0237   //         pool->FreeBlock(block, v);
0238   //       });
0239   // }
0240   //
0241   // WARNING: Because a Cord can be reference-counted, it's likely a bug if your
0242   // releaser doesn't do anything. For example, consider the following:
0243   //
0244   // void Foo(const char* buffer, int len) {
0245   //   auto c = absl::MakeCordFromExternal(absl::string_view(buffer, len),
0246   //                                       [](absl::string_view) {});
0247   //
0248   //   // BUG: If Bar() copies its cord for any reason, including keeping a
0249   //   // substring of it, the lifetime of buffer might be extended beyond
0250   //   // when Foo() returns.
0251   //   Bar(c);
0252   // }
0253   template <typename Releaser>
0254   friend Cord MakeCordFromExternal(absl::string_view data, Releaser&& releaser);
0255 
0256   // Cord::Clear()
0257   //
0258   // Releases the Cord data. Any nodes that share data with other Cords, if
0259   // applicable, will have their reference counts reduced by 1.
0260   ABSL_ATTRIBUTE_REINITIALIZES void Clear();
0261 
0262   // Cord::Append()
0263   //
0264   // Appends data to the Cord, which may come from another Cord or other string
0265   // data.
0266   void Append(const Cord& src);
0267   void Append(Cord&& src);
0268   void Append(absl::string_view src);
0269   template <typename T, EnableIfString<T> = 0>
0270   void Append(T&& src);
0271 
0272   // Appends `buffer` to this cord, unless `buffer` has a zero length in which
0273   // case this method has no effect on this cord instance.
0274   // This method is guaranteed to consume `buffer`.
0275   void Append(CordBuffer buffer);
0276 
0277   // Returns a CordBuffer, re-using potential existing capacity in this cord.
0278   //
0279   // Cord instances may have additional unused capacity in the last (or first)
0280   // nodes of the underlying tree to facilitate amortized growth. This method
0281   // allows applications to explicitly use this spare capacity if available,
0282   // or create a new CordBuffer instance otherwise.
0283   // If this cord has a final non-shared node with at least `min_capacity`
0284   // available, then this method will return that buffer including its data
0285   // contents. I.e.; the returned buffer will have a non-zero length, and
0286   // a capacity of at least `buffer.length + min_capacity`. Otherwise, this
0287   // method will return `CordBuffer::CreateWithDefaultLimit(capacity)`.
0288   //
0289   // Below an example of using GetAppendBuffer. Notice that in this example we
0290   // use `GetAppendBuffer()` only on the first iteration. As we know nothing
0291   // about any initial extra capacity in `cord`, we may be able to use the extra
0292   // capacity. But as we add new buffers with fully utilized contents after that
0293   // we avoid calling `GetAppendBuffer()` on subsequent iterations: while this
0294   // works fine, it results in an unnecessary inspection of cord contents:
0295   //
0296   //   void AppendRandomDataToCord(absl::Cord &cord, size_t n) {
0297   //     bool first = true;
0298   //     while (n > 0) {
0299   //       CordBuffer buffer = first ? cord.GetAppendBuffer(n)
0300   //                                 : CordBuffer::CreateWithDefaultLimit(n);
0301   //       absl::Span<char> data = buffer.available_up_to(n);
0302   //       FillRandomValues(data.data(), data.size());
0303   //       buffer.IncreaseLengthBy(data.size());
0304   //       cord.Append(std::move(buffer));
0305   //       n -= data.size();
0306   //       first = false;
0307   //     }
0308   //   }
0309   CordBuffer GetAppendBuffer(size_t capacity, size_t min_capacity = 16);
0310 
0311   // Returns a CordBuffer, re-using potential existing capacity in this cord.
0312   //
0313   // This function is identical to `GetAppendBuffer`, except that in the case
0314   // where a new `CordBuffer` is allocated, it is allocated using the provided
0315   // custom limit instead of the default limit. `GetAppendBuffer` will default
0316   // to `CordBuffer::CreateWithDefaultLimit(capacity)` whereas this method
0317   // will default to `CordBuffer::CreateWithCustomLimit(block_size, capacity)`.
0318   // This method is equivalent to `GetAppendBuffer` if `block_size` is zero.
0319   // See the documentation for `CreateWithCustomLimit` for more details on the
0320   // restrictions and legal values for `block_size`.
0321   CordBuffer GetCustomAppendBuffer(size_t block_size, size_t capacity,
0322                                    size_t min_capacity = 16);
0323 
0324   // Cord::Prepend()
0325   //
0326   // Prepends data to the Cord, which may come from another Cord or other string
0327   // data.
0328   void Prepend(const Cord& src);
0329   void Prepend(absl::string_view src);
0330   template <typename T, EnableIfString<T> = 0>
0331   void Prepend(T&& src);
0332 
0333   // Prepends `buffer` to this cord, unless `buffer` has a zero length in which
0334   // case this method has no effect on this cord instance.
0335   // This method is guaranteed to consume `buffer`.
0336   void Prepend(CordBuffer buffer);
0337 
0338   // Cord::RemovePrefix()
0339   //
0340   // Removes the first `n` bytes of a Cord.
0341   void RemovePrefix(size_t n);
0342   void RemoveSuffix(size_t n);
0343 
0344   // Cord::Subcord()
0345   //
0346   // Returns a new Cord representing the subrange [pos, pos + new_size) of
0347   // *this. If pos >= size(), the result is empty(). If
0348   // (pos + new_size) >= size(), the result is the subrange [pos, size()).
0349   Cord Subcord(size_t pos, size_t new_size) const;
0350 
0351   // Cord::swap()
0352   //
0353   // Swaps the contents of the Cord with `other`.
0354   void swap(Cord& other) noexcept;
0355 
0356   // swap()
0357   //
0358   // Swaps the contents of two Cords.
0359   friend void swap(Cord& x, Cord& y) noexcept { x.swap(y); }
0360 
0361   // Cord::size()
0362   //
0363   // Returns the size of the Cord.
0364   size_t size() const;
0365 
0366   // Cord::empty()
0367   //
0368   // Determines whether the given Cord is empty, returning `true` if so.
0369   bool empty() const;
0370 
0371   // Cord::EstimatedMemoryUsage()
0372   //
0373   // Returns the *approximate* number of bytes held by this cord.
0374   // See CordMemoryAccounting for more information on the accounting method.
0375   size_t EstimatedMemoryUsage(CordMemoryAccounting accounting_method =
0376                                   CordMemoryAccounting::kTotal) const;
0377 
0378   // Cord::Compare()
0379   //
0380   // Compares 'this' Cord with rhs. This function and its relatives treat Cords
0381   // as sequences of unsigned bytes. The comparison is a straightforward
0382   // lexicographic comparison. `Cord::Compare()` returns values as follows:
0383   //
0384   //   -1  'this' Cord is smaller
0385   //    0  two Cords are equal
0386   //    1  'this' Cord is larger
0387   int Compare(absl::string_view rhs) const;
0388   int Compare(const Cord& rhs) const;
0389 
0390   // Cord::StartsWith()
0391   //
0392   // Determines whether the Cord starts with the passed string data `rhs`.
0393   bool StartsWith(const Cord& rhs) const;
0394   bool StartsWith(absl::string_view rhs) const;
0395 
0396   // Cord::EndsWith()
0397   //
0398   // Determines whether the Cord ends with the passed string data `rhs`.
0399   bool EndsWith(absl::string_view rhs) const;
0400   bool EndsWith(const Cord& rhs) const;
0401 
0402   // Cord::Contains()
0403   //
0404   // Determines whether the Cord contains the passed string data `rhs`.
0405   bool Contains(absl::string_view rhs) const;
0406   bool Contains(const Cord& rhs) const;
0407 
0408   // Cord::operator std::string()
0409   //
0410   // Converts a Cord into a `std::string()`. This operator is marked explicit to
0411   // prevent unintended Cord usage in functions that take a string.
0412   explicit operator std::string() const;
0413 
0414   // CopyCordToString()
0415   //
0416   // Copies the contents of a `src` Cord into a `*dst` string.
0417   //
0418   // This function optimizes the case of reusing the destination string since it
0419   // can reuse previously allocated capacity. However, this function does not
0420   // guarantee that pointers previously returned by `dst->data()` remain valid
0421   // even if `*dst` had enough capacity to hold `src`. If `*dst` is a new
0422   // object, prefer to simply use the conversion operator to `std::string`.
0423   friend void CopyCordToString(const Cord& src,
0424                                absl::Nonnull<std::string*> dst);
0425 
0426   // AppendCordToString()
0427   //
0428   // Appends the contents of a `src` Cord to a `*dst` string.
0429   //
0430   // This function optimizes the case of appending to a non-empty destination
0431   // string. If `*dst` already has capacity to store the contents of the cord,
0432   // this function does not invalidate pointers previously returned by
0433   // `dst->data()`. If `*dst` is a new object, prefer to simply use the
0434   // conversion operator to `std::string`.
0435   friend void AppendCordToString(const Cord& src,
0436                                  absl::Nonnull<std::string*> dst);
0437 
0438   class CharIterator;
0439 
0440   //----------------------------------------------------------------------------
0441   // Cord::ChunkIterator
0442   //----------------------------------------------------------------------------
0443   //
0444   // A `Cord::ChunkIterator` allows iteration over the constituent chunks of its
0445   // Cord. Such iteration allows you to perform non-const operations on the data
0446   // of a Cord without modifying it.
0447   //
0448   // Generally, you do not instantiate a `Cord::ChunkIterator` directly;
0449   // instead, you create one implicitly through use of the `Cord::Chunks()`
0450   // member function.
0451   //
0452   // The `Cord::ChunkIterator` has the following properties:
0453   //
0454   //   * The iterator is invalidated after any non-const operation on the
0455   //     Cord object over which it iterates.
0456   //   * The `string_view` returned by dereferencing a valid, non-`end()`
0457   //     iterator is guaranteed to be non-empty.
0458   //   * Two `ChunkIterator` objects can be compared equal if and only if they
0459   //     remain valid and iterate over the same Cord.
0460   //   * The iterator in this case is a proxy iterator; the `string_view`
0461   //     returned by the iterator does not live inside the Cord, and its
0462   //     lifetime is limited to the lifetime of the iterator itself. To help
0463   //     prevent lifetime issues, `ChunkIterator::reference` is not a true
0464   //     reference type and is equivalent to `value_type`.
0465   //   * The iterator keeps state that can grow for Cords that contain many
0466   //     nodes and are imbalanced due to sharing. Prefer to pass this type by
0467   //     const reference instead of by value.
0468   class ChunkIterator {
0469    public:
0470     using iterator_category = std::input_iterator_tag;
0471     using value_type = absl::string_view;
0472     using difference_type = ptrdiff_t;
0473     using pointer = absl::Nonnull<const value_type*>;
0474     using reference = value_type;
0475 
0476     ChunkIterator() = default;
0477 
0478     ChunkIterator& operator++();
0479     ChunkIterator operator++(int);
0480     bool operator==(const ChunkIterator& other) const;
0481     bool operator!=(const ChunkIterator& other) const;
0482     reference operator*() const;
0483     pointer operator->() const;
0484 
0485     friend class Cord;
0486     friend class CharIterator;
0487 
0488    private:
0489     using CordRep = absl::cord_internal::CordRep;
0490     using CordRepBtree = absl::cord_internal::CordRepBtree;
0491     using CordRepBtreeReader = absl::cord_internal::CordRepBtreeReader;
0492 
0493     // Constructs a `begin()` iterator from `tree`.
0494     explicit ChunkIterator(absl::Nonnull<cord_internal::CordRep*> tree);
0495 
0496     // Constructs a `begin()` iterator from `cord`.
0497     explicit ChunkIterator(absl::Nonnull<const Cord*> cord);
0498 
0499     // Initializes this instance from a tree. Invoked by constructors.
0500     void InitTree(absl::Nonnull<cord_internal::CordRep*> tree);
0501 
0502     // Removes `n` bytes from `current_chunk_`. Expects `n` to be smaller than
0503     // `current_chunk_.size()`.
0504     void RemoveChunkPrefix(size_t n);
0505     Cord AdvanceAndReadBytes(size_t n);
0506     void AdvanceBytes(size_t n);
0507 
0508     // Btree specific operator++
0509     ChunkIterator& AdvanceBtree();
0510     void AdvanceBytesBtree(size_t n);
0511 
0512     // A view into bytes of the current `CordRep`. It may only be a view to a
0513     // suffix of bytes if this is being used by `CharIterator`.
0514     absl::string_view current_chunk_;
0515     // The current leaf, or `nullptr` if the iterator points to short data.
0516     // If the current chunk is a substring node, current_leaf_ points to the
0517     // underlying flat or external node.
0518     absl::Nullable<absl::cord_internal::CordRep*> current_leaf_ = nullptr;
0519     // The number of bytes left in the `Cord` over which we are iterating.
0520     size_t bytes_remaining_ = 0;
0521 
0522     // Cord reader for cord btrees. Empty if not traversing a btree.
0523     CordRepBtreeReader btree_reader_;
0524   };
0525 
0526   // Cord::chunk_begin()
0527   //
0528   // Returns an iterator to the first chunk of the `Cord`.
0529   //
0530   // Generally, prefer using `Cord::Chunks()` within a range-based for loop for
0531   // iterating over the chunks of a Cord. This method may be useful for getting
0532   // a `ChunkIterator` where range-based for-loops are not useful.
0533   //
0534   // Example:
0535   //
0536   //   absl::Cord::ChunkIterator FindAsChunk(const absl::Cord& c,
0537   //                                         absl::string_view s) {
0538   //     return std::find(c.chunk_begin(), c.chunk_end(), s);
0539   //   }
0540   ChunkIterator chunk_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
0541 
0542   // Cord::chunk_end()
0543   //
0544   // Returns an iterator one increment past the last chunk of the `Cord`.
0545   //
0546   // Generally, prefer using `Cord::Chunks()` within a range-based for loop for
0547   // iterating over the chunks of a Cord. This method may be useful for getting
0548   // a `ChunkIterator` where range-based for-loops may not be available.
0549   ChunkIterator chunk_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
0550 
0551   //----------------------------------------------------------------------------
0552   // Cord::ChunkRange
0553   //----------------------------------------------------------------------------
0554   //
0555   // `ChunkRange` is a helper class for iterating over the chunks of the `Cord`,
0556   // producing an iterator which can be used within a range-based for loop.
0557   // Construction of a `ChunkRange` will return an iterator pointing to the
0558   // first chunk of the Cord. Generally, do not construct a `ChunkRange`
0559   // directly; instead, prefer to use the `Cord::Chunks()` method.
0560   //
0561   // Implementation note: `ChunkRange` is simply a convenience wrapper over
0562   // `Cord::chunk_begin()` and `Cord::chunk_end()`.
0563   class ChunkRange {
0564    public:
0565     // Fulfill minimum c++ container requirements [container.requirements]
0566     // These (partial) container type definitions allow ChunkRange to be used
0567     // in various utilities expecting a subset of [container.requirements].
0568     // For example, the below enables using `::testing::ElementsAre(...)`
0569     using value_type = absl::string_view;
0570     using reference = value_type&;
0571     using const_reference = const value_type&;
0572     using iterator = ChunkIterator;
0573     using const_iterator = ChunkIterator;
0574 
0575     explicit ChunkRange(absl::Nonnull<const Cord*> cord) : cord_(cord) {}
0576 
0577     ChunkIterator begin() const;
0578     ChunkIterator end() const;
0579 
0580    private:
0581     absl::Nonnull<const Cord*> cord_;
0582   };
0583 
0584   // Cord::Chunks()
0585   //
0586   // Returns a `Cord::ChunkRange` for iterating over the chunks of a `Cord` with
0587   // a range-based for-loop. For most iteration tasks on a Cord, use
0588   // `Cord::Chunks()` to retrieve this iterator.
0589   //
0590   // Example:
0591   //
0592   //   void ProcessChunks(const Cord& cord) {
0593   //     for (absl::string_view chunk : cord.Chunks()) { ... }
0594   //   }
0595   //
0596   // Note that the ordinary caveats of temporary lifetime extension apply:
0597   //
0598   //   void Process() {
0599   //     for (absl::string_view chunk : CordFactory().Chunks()) {
0600   //       // The temporary Cord returned by CordFactory has been destroyed!
0601   //     }
0602   //   }
0603   ChunkRange Chunks() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
0604 
0605   //----------------------------------------------------------------------------
0606   // Cord::CharIterator
0607   //----------------------------------------------------------------------------
0608   //
0609   // A `Cord::CharIterator` allows iteration over the constituent characters of
0610   // a `Cord`.
0611   //
0612   // Generally, you do not instantiate a `Cord::CharIterator` directly; instead,
0613   // you create one implicitly through use of the `Cord::Chars()` member
0614   // function.
0615   //
0616   // A `Cord::CharIterator` has the following properties:
0617   //
0618   //   * The iterator is invalidated after any non-const operation on the
0619   //     Cord object over which it iterates.
0620   //   * Two `CharIterator` objects can be compared equal if and only if they
0621   //     remain valid and iterate over the same Cord.
0622   //   * The iterator keeps state that can grow for Cords that contain many
0623   //     nodes and are imbalanced due to sharing. Prefer to pass this type by
0624   //     const reference instead of by value.
0625   //   * This type cannot act as a forward iterator because a `Cord` can reuse
0626   //     sections of memory. This fact violates the requirement for forward
0627   //     iterators to compare equal if dereferencing them returns the same
0628   //     object.
0629   class CharIterator {
0630    public:
0631     using iterator_category = std::input_iterator_tag;
0632     using value_type = char;
0633     using difference_type = ptrdiff_t;
0634     using pointer = absl::Nonnull<const char*>;
0635     using reference = const char&;
0636 
0637     CharIterator() = default;
0638 
0639     CharIterator& operator++();
0640     CharIterator operator++(int);
0641     bool operator==(const CharIterator& other) const;
0642     bool operator!=(const CharIterator& other) const;
0643     reference operator*() const;
0644     pointer operator->() const;
0645 
0646     friend Cord;
0647 
0648    private:
0649     explicit CharIterator(absl::Nonnull<const Cord*> cord)
0650         : chunk_iterator_(cord) {}
0651 
0652     ChunkIterator chunk_iterator_;
0653   };
0654 
0655   // Cord::AdvanceAndRead()
0656   //
0657   // Advances the `Cord::CharIterator` by `n_bytes` and returns the bytes
0658   // advanced as a separate `Cord`. `n_bytes` must be less than or equal to the
0659   // number of bytes within the Cord; otherwise, behavior is undefined. It is
0660   // valid to pass `char_end()` and `0`.
0661   static Cord AdvanceAndRead(absl::Nonnull<CharIterator*> it, size_t n_bytes);
0662 
0663   // Cord::Advance()
0664   //
0665   // Advances the `Cord::CharIterator` by `n_bytes`. `n_bytes` must be less than
0666   // or equal to the number of bytes remaining within the Cord; otherwise,
0667   // behavior is undefined. It is valid to pass `char_end()` and `0`.
0668   static void Advance(absl::Nonnull<CharIterator*> it, size_t n_bytes);
0669 
0670   // Cord::ChunkRemaining()
0671   //
0672   // Returns the longest contiguous view starting at the iterator's position.
0673   //
0674   // `it` must be dereferenceable.
0675   static absl::string_view ChunkRemaining(const CharIterator& it);
0676 
0677   // Cord::char_begin()
0678   //
0679   // Returns an iterator to the first character of the `Cord`.
0680   //
0681   // Generally, prefer using `Cord::Chars()` within a range-based for loop for
0682   // iterating over the chunks of a Cord. This method may be useful for getting
0683   // a `CharIterator` where range-based for-loops may not be available.
0684   CharIterator char_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
0685 
0686   // Cord::char_end()
0687   //
0688   // Returns an iterator to one past the last character of the `Cord`.
0689   //
0690   // Generally, prefer using `Cord::Chars()` within a range-based for loop for
0691   // iterating over the chunks of a Cord. This method may be useful for getting
0692   // a `CharIterator` where range-based for-loops are not useful.
0693   CharIterator char_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
0694 
0695   // Cord::CharRange
0696   //
0697   // `CharRange` is a helper class for iterating over the characters of a
0698   // producing an iterator which can be used within a range-based for loop.
0699   // Construction of a `CharRange` will return an iterator pointing to the first
0700   // character of the Cord. Generally, do not construct a `CharRange` directly;
0701   // instead, prefer to use the `Cord::Chars()` method shown below.
0702   //
0703   // Implementation note: `CharRange` is simply a convenience wrapper over
0704   // `Cord::char_begin()` and `Cord::char_end()`.
0705   class CharRange {
0706    public:
0707     // Fulfill minimum c++ container requirements [container.requirements]
0708     // These (partial) container type definitions allow CharRange to be used
0709     // in various utilities expecting a subset of [container.requirements].
0710     // For example, the below enables using `::testing::ElementsAre(...)`
0711     using value_type = char;
0712     using reference = value_type&;
0713     using const_reference = const value_type&;
0714     using iterator = CharIterator;
0715     using const_iterator = CharIterator;
0716 
0717     explicit CharRange(absl::Nonnull<const Cord*> cord) : cord_(cord) {}
0718 
0719     CharIterator begin() const;
0720     CharIterator end() const;
0721 
0722    private:
0723     absl::Nonnull<const Cord*> cord_;
0724   };
0725 
0726   // Cord::Chars()
0727   //
0728   // Returns a `Cord::CharRange` for iterating over the characters of a `Cord`
0729   // with a range-based for-loop. For most character-based iteration tasks on a
0730   // Cord, use `Cord::Chars()` to retrieve this iterator.
0731   //
0732   // Example:
0733   //
0734   //   void ProcessCord(const Cord& cord) {
0735   //     for (char c : cord.Chars()) { ... }
0736   //   }
0737   //
0738   // Note that the ordinary caveats of temporary lifetime extension apply:
0739   //
0740   //   void Process() {
0741   //     for (char c : CordFactory().Chars()) {
0742   //       // The temporary Cord returned by CordFactory has been destroyed!
0743   //     }
0744   //   }
0745   CharRange Chars() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
0746 
0747   // Cord::operator[]
0748   //
0749   // Gets the "i"th character of the Cord and returns it, provided that
0750   // 0 <= i < Cord.size().
0751   //
0752   // NOTE: This routine is reasonably efficient. It is roughly
0753   // logarithmic based on the number of chunks that make up the cord. Still,
0754   // if you need to iterate over the contents of a cord, you should
0755   // use a CharIterator/ChunkIterator rather than call operator[] or Get()
0756   // repeatedly in a loop.
0757   char operator[](size_t i) const;
0758 
0759   // Cord::TryFlat()
0760   //
0761   // If this cord's representation is a single flat array, returns a
0762   // string_view referencing that array.  Otherwise returns nullopt.
0763   absl::optional<absl::string_view> TryFlat() const
0764       ABSL_ATTRIBUTE_LIFETIME_BOUND;
0765 
0766   // Cord::Flatten()
0767   //
0768   // Flattens the cord into a single array and returns a view of the data.
0769   //
0770   // If the cord was already flat, the contents are not modified.
0771   absl::string_view Flatten() ABSL_ATTRIBUTE_LIFETIME_BOUND;
0772 
0773   // Cord::Find()
0774   //
0775   // Returns an iterator to the first occurrence of the substring `needle`.
0776   //
0777   // If the substring `needle` does not occur, `Cord::char_end()` is returned.
0778   CharIterator Find(absl::string_view needle) const;
0779   CharIterator Find(const absl::Cord& needle) const;
0780 
0781   // Supports absl::Cord as a sink object for absl::Format().
0782   friend void AbslFormatFlush(absl::Nonnull<absl::Cord*> cord,
0783                               absl::string_view part) {
0784     cord->Append(part);
0785   }
0786 
0787   // Support automatic stringification with absl::StrCat and absl::StrFormat.
0788   template <typename Sink>
0789   friend void AbslStringify(Sink& sink, const absl::Cord& cord) {
0790     for (absl::string_view chunk : cord.Chunks()) {
0791       sink.Append(chunk);
0792     }
0793   }
0794 
0795   // Cord::SetExpectedChecksum()
0796   //
0797   // Stores a checksum value with this non-empty cord instance, for later
0798   // retrieval.
0799   //
0800   // The expected checksum is a number stored out-of-band, alongside the data.
0801   // It is preserved across copies and assignments, but any mutations to a cord
0802   // will cause it to lose its expected checksum.
0803   //
0804   // The expected checksum is not part of a Cord's value, and does not affect
0805   // operations such as equality or hashing.
0806   //
0807   // This field is intended to store a CRC32C checksum for later validation, to
0808   // help support end-to-end checksum workflows.  However, the Cord API itself
0809   // does no CRC validation, and assigns no meaning to this number.
0810   //
0811   // This call has no effect if this cord is empty.
0812   void SetExpectedChecksum(uint32_t crc);
0813 
0814   // Returns this cord's expected checksum, if it has one.  Otherwise, returns
0815   // nullopt.
0816   absl::optional<uint32_t> ExpectedChecksum() const;
0817 
0818   template <typename H>
0819   friend H AbslHashValue(H hash_state, const absl::Cord& c) {
0820     absl::optional<absl::string_view> maybe_flat = c.TryFlat();
0821     if (maybe_flat.has_value()) {
0822       return H::combine(std::move(hash_state), *maybe_flat);
0823     }
0824     return c.HashFragmented(std::move(hash_state));
0825   }
0826 
0827   // Create a Cord with the contents of StringConstant<T>::value.
0828   // No allocations will be done and no data will be copied.
0829   // This is an INTERNAL API and subject to change or removal. This API can only
0830   // be used by spelling absl::strings_internal::MakeStringConstant, which is
0831   // also an internal API.
0832   template <typename T>
0833   // NOLINTNEXTLINE(google-explicit-constructor)
0834   constexpr Cord(strings_internal::StringConstant<T>);
0835 
0836  private:
0837   using CordRep = absl::cord_internal::CordRep;
0838   using CordRepFlat = absl::cord_internal::CordRepFlat;
0839   using CordzInfo = cord_internal::CordzInfo;
0840   using CordzUpdateScope = cord_internal::CordzUpdateScope;
0841   using CordzUpdateTracker = cord_internal::CordzUpdateTracker;
0842   using InlineData = cord_internal::InlineData;
0843   using MethodIdentifier = CordzUpdateTracker::MethodIdentifier;
0844 
0845   // Creates a cord instance with `method` representing the originating
0846   // public API call causing the cord to be created.
0847   explicit Cord(absl::string_view src, MethodIdentifier method);
0848 
0849   friend class CordTestPeer;
0850   friend bool operator==(const Cord& lhs, const Cord& rhs);
0851   friend bool operator==(const Cord& lhs, absl::string_view rhs);
0852 
0853 #ifdef __cpp_impl_three_way_comparison
0854 
0855   // Cords support comparison with other Cords and string_views via operator<
0856   // and others; here we provide a wrapper for the C++20 three-way comparison
0857   // <=> operator.
0858 
0859   static inline std::strong_ordering ConvertCompareResultToStrongOrdering(
0860       int c) {
0861     if (c == 0) {
0862       return std::strong_ordering::equal;
0863     } else if (c < 0) {
0864       return std::strong_ordering::less;
0865     } else {
0866       return std::strong_ordering::greater;
0867     }
0868   }
0869 
0870   friend inline std::strong_ordering operator<=>(const Cord& x, const Cord& y) {
0871     return ConvertCompareResultToStrongOrdering(x.Compare(y));
0872   }
0873 
0874   friend inline std::strong_ordering operator<=>(const Cord& lhs,
0875                                                  absl::string_view rhs) {
0876     return ConvertCompareResultToStrongOrdering(lhs.Compare(rhs));
0877   }
0878 
0879   friend inline std::strong_ordering operator<=>(absl::string_view lhs,
0880                                                  const Cord& rhs) {
0881     return ConvertCompareResultToStrongOrdering(-rhs.Compare(lhs));
0882   }
0883 #endif
0884 
0885   friend absl::Nullable<const CordzInfo*> GetCordzInfoForTesting(
0886       const Cord& cord);
0887 
0888   // Calls the provided function once for each cord chunk, in order.  Unlike
0889   // Chunks(), this API will not allocate memory.
0890   void ForEachChunk(absl::FunctionRef<void(absl::string_view)>) const;
0891 
0892   // Allocates new contiguous storage for the contents of the cord. This is
0893   // called by Flatten() when the cord was not already flat.
0894   absl::string_view FlattenSlowPath();
0895 
0896   // Actual cord contents are hidden inside the following simple
0897   // class so that we can isolate the bulk of cord.cc from changes
0898   // to the representation.
0899   //
0900   // InlineRep holds either a tree pointer, or an array of kMaxInline bytes.
0901   class InlineRep {
0902    public:
0903     static constexpr unsigned char kMaxInline = cord_internal::kMaxInline;
0904     static_assert(kMaxInline >= sizeof(absl::cord_internal::CordRep*), "");
0905 
0906     constexpr InlineRep() : data_() {}
0907     explicit InlineRep(InlineData::DefaultInitType init) : data_(init) {}
0908     InlineRep(const InlineRep& src);
0909     InlineRep(InlineRep&& src);
0910     InlineRep& operator=(const InlineRep& src);
0911     InlineRep& operator=(InlineRep&& src) noexcept;
0912 
0913     explicit constexpr InlineRep(absl::string_view sv,
0914                                  absl::Nullable<CordRep*> rep);
0915 
0916     void Swap(absl::Nonnull<InlineRep*> rhs);
0917     size_t size() const;
0918     // Returns nullptr if holding pointer
0919     absl::Nullable<const char*> data() const;
0920     // Discards pointer, if any
0921     void set_data(absl::Nonnull<const char*> data, size_t n);
0922     absl::Nonnull<char*> set_data(size_t n);  // Write data to the result
0923     // Returns nullptr if holding bytes
0924     absl::Nullable<absl::cord_internal::CordRep*> tree() const;
0925     absl::Nonnull<absl::cord_internal::CordRep*> as_tree() const;
0926     absl::Nonnull<const char*> as_chars() const;
0927     // Returns non-null iff was holding a pointer
0928     absl::Nullable<absl::cord_internal::CordRep*> clear();
0929     // Converts to pointer if necessary.
0930     void reduce_size(size_t n);    // REQUIRES: holding data
0931     void remove_prefix(size_t n);  // REQUIRES: holding data
0932     void AppendArray(absl::string_view src, MethodIdentifier method);
0933     absl::string_view FindFlatStartPiece() const;
0934 
0935     // Creates a CordRepFlat instance from the current inlined data with `extra'
0936     // bytes of desired additional capacity.
0937     absl::Nonnull<CordRepFlat*> MakeFlatWithExtraCapacity(size_t extra);
0938 
0939     // Sets the tree value for this instance. `rep` must not be null.
0940     // Requires the current instance to hold a tree, and a lock to be held on
0941     // any CordzInfo referenced by this instance. The latter is enforced through
0942     // the CordzUpdateScope argument. If the current instance is sampled, then
0943     // the CordzInfo instance is updated to reference the new `rep` value.
0944     void SetTree(absl::Nonnull<CordRep*> rep, const CordzUpdateScope& scope);
0945 
0946     // Identical to SetTree(), except that `rep` is allowed to be null, in
0947     // which case the current instance is reset to an empty value.
0948     void SetTreeOrEmpty(absl::Nullable<CordRep*> rep,
0949                         const CordzUpdateScope& scope);
0950 
0951     // Sets the tree value for this instance, and randomly samples this cord.
0952     // This function disregards existing contents in `data_`, and should be
0953     // called when a Cord is 'promoted' from an 'uninitialized' or 'inlined'
0954     // value to a non-inlined (tree / ring) value.
0955     void EmplaceTree(absl::Nonnull<CordRep*> rep, MethodIdentifier method);
0956 
0957     // Identical to EmplaceTree, except that it copies the parent stack from
0958     // the provided `parent` data if the parent is sampled.
0959     void EmplaceTree(absl::Nonnull<CordRep*> rep, const InlineData& parent,
0960                      MethodIdentifier method);
0961 
0962     // Commits the change of a newly created, or updated `rep` root value into
0963     // this cord. `old_rep` indicates the old (inlined or tree) value of the
0964     // cord, and determines if the commit invokes SetTree() or EmplaceTree().
0965     void CommitTree(absl::Nullable<const CordRep*> old_rep,
0966                     absl::Nonnull<CordRep*> rep, const CordzUpdateScope& scope,
0967                     MethodIdentifier method);
0968 
0969     void AppendTreeToInlined(absl::Nonnull<CordRep*> tree,
0970                              MethodIdentifier method);
0971     void AppendTreeToTree(absl::Nonnull<CordRep*> tree,
0972                           MethodIdentifier method);
0973     void AppendTree(absl::Nonnull<CordRep*> tree, MethodIdentifier method);
0974     void PrependTreeToInlined(absl::Nonnull<CordRep*> tree,
0975                               MethodIdentifier method);
0976     void PrependTreeToTree(absl::Nonnull<CordRep*> tree,
0977                            MethodIdentifier method);
0978     void PrependTree(absl::Nonnull<CordRep*> tree, MethodIdentifier method);
0979 
0980     bool IsSame(const InlineRep& other) const { return data_ == other.data_; }
0981 
0982     void CopyTo(absl::Nonnull<std::string*> dst) const {
0983       // memcpy is much faster when operating on a known size. On most supported
0984       // platforms, the small string optimization is large enough that resizing
0985       // to 15 bytes does not cause a memory allocation.
0986       absl::strings_internal::STLStringResizeUninitialized(dst, kMaxInline);
0987       data_.copy_max_inline_to(&(*dst)[0]);
0988       // erase is faster than resize because the logic for memory allocation is
0989       // not needed.
0990       dst->erase(inline_size());
0991     }
0992 
0993     // Copies the inline contents into `dst`. Assumes the cord is not empty.
0994     void CopyToArray(absl::Nonnull<char*> dst) const;
0995 
0996     bool is_tree() const { return data_.is_tree(); }
0997 
0998     // Returns true if the Cord is being profiled by cordz.
0999     bool is_profiled() const { return data_.is_tree() && data_.is_profiled(); }
1000 
1001     // Returns the available inlined capacity, or 0 if is_tree() == true.
1002     size_t remaining_inline_capacity() const {
1003       return data_.is_tree() ? 0 : kMaxInline - data_.inline_size();
1004     }
1005 
1006     // Returns the profiled CordzInfo, or nullptr if not sampled.
1007     absl::Nullable<absl::cord_internal::CordzInfo*> cordz_info() const {
1008       return data_.cordz_info();
1009     }
1010 
1011     // Sets the profiled CordzInfo.
1012     void set_cordz_info(absl::Nonnull<cord_internal::CordzInfo*> cordz_info) {
1013       assert(cordz_info != nullptr);
1014       data_.set_cordz_info(cordz_info);
1015     }
1016 
1017     // Resets the current cordz_info to null / empty.
1018     void clear_cordz_info() { data_.clear_cordz_info(); }
1019 
1020    private:
1021     friend class Cord;
1022 
1023     void AssignSlow(const InlineRep& src);
1024     // Unrefs the tree and stops profiling.
1025     void UnrefTree();
1026 
1027     void ResetToEmpty() { data_ = {}; }
1028 
1029     void set_inline_size(size_t size) { data_.set_inline_size(size); }
1030     size_t inline_size() const { return data_.inline_size(); }
1031 
1032     // Empty cords that carry a checksum have a CordRepCrc node with a null
1033     // child node. The code can avoid lots of special cases where it would
1034     // otherwise transition from tree to inline storage if we just remove the
1035     // CordRepCrc node before mutations. Must never be called inside a
1036     // CordzUpdateScope since it untracks the cordz info.
1037     void MaybeRemoveEmptyCrcNode();
1038 
1039     cord_internal::InlineData data_;
1040   };
1041   InlineRep contents_;
1042 
1043   // Helper for GetFlat() and TryFlat().
1044   static bool GetFlatAux(absl::Nonnull<absl::cord_internal::CordRep*> rep,
1045                          absl::Nonnull<absl::string_view*> fragment);
1046 
1047   // Helper for ForEachChunk().
1048   static void ForEachChunkAux(
1049       absl::Nonnull<absl::cord_internal::CordRep*> rep,
1050       absl::FunctionRef<void(absl::string_view)> callback);
1051 
1052   // The destructor for non-empty Cords.
1053   void DestroyCordSlow();
1054 
1055   // Out-of-line implementation of slower parts of logic.
1056   void CopyToArraySlowPath(absl::Nonnull<char*> dst) const;
1057   int CompareSlowPath(absl::string_view rhs, size_t compared_size,
1058                       size_t size_to_compare) const;
1059   int CompareSlowPath(const Cord& rhs, size_t compared_size,
1060                       size_t size_to_compare) const;
1061   bool EqualsImpl(absl::string_view rhs, size_t size_to_compare) const;
1062   bool EqualsImpl(const Cord& rhs, size_t size_to_compare) const;
1063   int CompareImpl(const Cord& rhs) const;
1064 
1065   template <typename ResultType, typename RHS>
1066   friend ResultType GenericCompare(const Cord& lhs, const RHS& rhs,
1067                                    size_t size_to_compare);
1068   static absl::string_view GetFirstChunk(const Cord& c);
1069   static absl::string_view GetFirstChunk(absl::string_view sv);
1070 
1071   // Returns a new reference to contents_.tree(), or steals an existing
1072   // reference if called on an rvalue.
1073   absl::Nonnull<absl::cord_internal::CordRep*> TakeRep() const&;
1074   absl::Nonnull<absl::cord_internal::CordRep*> TakeRep() &&;
1075 
1076   // Helper for Append().
1077   template <typename C>
1078   void AppendImpl(C&& src);
1079 
1080   // Appends / Prepends `src` to this instance, using precise sizing.
1081   // This method does explicitly not attempt to use any spare capacity
1082   // in any pending last added private owned flat.
1083   // Requires `src` to be <= kMaxFlatLength.
1084   void AppendPrecise(absl::string_view src, MethodIdentifier method);
1085   void PrependPrecise(absl::string_view src, MethodIdentifier method);
1086 
1087   CordBuffer GetAppendBufferSlowPath(size_t block_size, size_t capacity,
1088                                      size_t min_capacity);
1089 
1090   // Prepends the provided data to this instance. `method` contains the public
1091   // API method for this action which is tracked for Cordz sampling purposes.
1092   void PrependArray(absl::string_view src, MethodIdentifier method);
1093 
1094   // Assigns the value in 'src' to this instance, 'stealing' its contents.
1095   // Requires src.length() > kMaxBytesToCopy.
1096   Cord& AssignLargeString(std::string&& src);
1097 
1098   // Helper for AbslHashValue().
1099   template <typename H>
1100   H HashFragmented(H hash_state) const {
1101     typename H::AbslInternalPiecewiseCombiner combiner;
1102     ForEachChunk([&combiner, &hash_state](absl::string_view chunk) {
1103       hash_state = combiner.add_buffer(std::move(hash_state), chunk.data(),
1104                                        chunk.size());
1105     });
1106     return H::combine(combiner.finalize(std::move(hash_state)), size());
1107   }
1108 
1109   friend class CrcCord;
1110   void SetCrcCordState(crc_internal::CrcCordState state);
1111   absl::Nullable<const crc_internal::CrcCordState*> MaybeGetCrcCordState()
1112       const;
1113 
1114   CharIterator FindImpl(CharIterator it, absl::string_view needle) const;
1115 
1116   void CopyToArrayImpl(absl::Nonnull<char*> dst) const;
1117 };
1118 
1119 ABSL_NAMESPACE_END
1120 }  // namespace absl
1121 
1122 namespace absl {
1123 ABSL_NAMESPACE_BEGIN
1124 
1125 // allow a Cord to be logged
1126 extern std::ostream& operator<<(std::ostream& out, const Cord& cord);
1127 
1128 // ------------------------------------------------------------------
1129 // Internal details follow.  Clients should ignore.
1130 
1131 namespace cord_internal {
1132 
1133 // Does non-template-specific `CordRepExternal` initialization.
1134 // Requires `data` to be non-empty.
1135 void InitializeCordRepExternal(absl::string_view data,
1136                                absl::Nonnull<CordRepExternal*> rep);
1137 
1138 // Creates a new `CordRep` that owns `data` and `releaser` and returns a pointer
1139 // to it. Requires `data` to be non-empty.
1140 template <typename Releaser>
1141 // NOLINTNEXTLINE - suppress clang-tidy raw pointer return.
1142 absl::Nonnull<CordRep*> NewExternalRep(absl::string_view data,
1143                                        Releaser&& releaser) {
1144   assert(!data.empty());
1145   using ReleaserType = absl::decay_t<Releaser>;
1146   CordRepExternal* rep = new CordRepExternalImpl<ReleaserType>(
1147       std::forward<Releaser>(releaser), 0);
1148   InitializeCordRepExternal(data, rep);
1149   return rep;
1150 }
1151 
1152 // Overload for function reference types that dispatches using a function
1153 // pointer because there are no `alignof()` or `sizeof()` a function reference.
1154 // NOLINTNEXTLINE - suppress clang-tidy raw pointer return.
1155 inline absl::Nonnull<CordRep*> NewExternalRep(
1156     absl::string_view data, void (&releaser)(absl::string_view)) {
1157   return NewExternalRep(data, &releaser);
1158 }
1159 
1160 }  // namespace cord_internal
1161 
1162 template <typename Releaser>
1163 Cord MakeCordFromExternal(absl::string_view data, Releaser&& releaser) {
1164   Cord cord;
1165   if (ABSL_PREDICT_TRUE(!data.empty())) {
1166     cord.contents_.EmplaceTree(::absl::cord_internal::NewExternalRep(
1167                                    data, std::forward<Releaser>(releaser)),
1168                                Cord::MethodIdentifier::kMakeCordFromExternal);
1169   } else {
1170     using ReleaserType = absl::decay_t<Releaser>;
1171     cord_internal::InvokeReleaser(
1172         cord_internal::Rank1{}, ReleaserType(std::forward<Releaser>(releaser)),
1173         data);
1174   }
1175   return cord;
1176 }
1177 
1178 constexpr Cord::InlineRep::InlineRep(absl::string_view sv,
1179                                      absl::Nullable<CordRep*> rep)
1180     : data_(sv, rep) {}
1181 
1182 inline Cord::InlineRep::InlineRep(const Cord::InlineRep& src)
1183     : data_(InlineData::kDefaultInit) {
1184   if (CordRep* tree = src.tree()) {
1185     EmplaceTree(CordRep::Ref(tree), src.data_,
1186                 CordzUpdateTracker::kConstructorCord);
1187   } else {
1188     data_ = src.data_;
1189   }
1190 }
1191 
1192 inline Cord::InlineRep::InlineRep(Cord::InlineRep&& src) : data_(src.data_) {
1193   src.ResetToEmpty();
1194 }
1195 
1196 inline Cord::InlineRep& Cord::InlineRep::operator=(const Cord::InlineRep& src) {
1197   if (this == &src) {
1198     return *this;
1199   }
1200   if (!is_tree() && !src.is_tree()) {
1201     data_ = src.data_;
1202     return *this;
1203   }
1204   AssignSlow(src);
1205   return *this;
1206 }
1207 
1208 inline Cord::InlineRep& Cord::InlineRep::operator=(
1209     Cord::InlineRep&& src) noexcept {
1210   if (is_tree()) {
1211     UnrefTree();
1212   }
1213   data_ = src.data_;
1214   src.ResetToEmpty();
1215   return *this;
1216 }
1217 
1218 inline void Cord::InlineRep::Swap(absl::Nonnull<Cord::InlineRep*> rhs) {
1219   if (rhs == this) {
1220     return;
1221   }
1222   using std::swap;
1223   swap(data_, rhs->data_);
1224 }
1225 
1226 inline absl::Nullable<const char*> Cord::InlineRep::data() const {
1227   return is_tree() ? nullptr : data_.as_chars();
1228 }
1229 
1230 inline absl::Nonnull<const char*> Cord::InlineRep::as_chars() const {
1231   assert(!data_.is_tree());
1232   return data_.as_chars();
1233 }
1234 
1235 inline absl::Nonnull<absl::cord_internal::CordRep*> Cord::InlineRep::as_tree()
1236     const {
1237   assert(data_.is_tree());
1238   return data_.as_tree();
1239 }
1240 
1241 inline absl::Nullable<absl::cord_internal::CordRep*> Cord::InlineRep::tree()
1242     const {
1243   if (is_tree()) {
1244     return as_tree();
1245   } else {
1246     return nullptr;
1247   }
1248 }
1249 
1250 inline size_t Cord::InlineRep::size() const {
1251   return is_tree() ? as_tree()->length : inline_size();
1252 }
1253 
1254 inline absl::Nonnull<cord_internal::CordRepFlat*>
1255 Cord::InlineRep::MakeFlatWithExtraCapacity(size_t extra) {
1256   static_assert(cord_internal::kMinFlatLength >= sizeof(data_), "");
1257   size_t len = data_.inline_size();
1258   auto* result = CordRepFlat::New(len + extra);
1259   result->length = len;
1260   data_.copy_max_inline_to(result->Data());
1261   return result;
1262 }
1263 
1264 inline void Cord::InlineRep::EmplaceTree(absl::Nonnull<CordRep*> rep,
1265                                          MethodIdentifier method) {
1266   assert(rep);
1267   data_.make_tree(rep);
1268   CordzInfo::MaybeTrackCord(data_, method);
1269 }
1270 
1271 inline void Cord::InlineRep::EmplaceTree(absl::Nonnull<CordRep*> rep,
1272                                          const InlineData& parent,
1273                                          MethodIdentifier method) {
1274   data_.make_tree(rep);
1275   CordzInfo::MaybeTrackCord(data_, parent, method);
1276 }
1277 
1278 inline void Cord::InlineRep::SetTree(absl::Nonnull<CordRep*> rep,
1279                                      const CordzUpdateScope& scope) {
1280   assert(rep);
1281   assert(data_.is_tree());
1282   data_.set_tree(rep);
1283   scope.SetCordRep(rep);
1284 }
1285 
1286 inline void Cord::InlineRep::SetTreeOrEmpty(absl::Nullable<CordRep*> rep,
1287                                             const CordzUpdateScope& scope) {
1288   assert(data_.is_tree());
1289   if (rep) {
1290     data_.set_tree(rep);
1291   } else {
1292     data_ = {};
1293   }
1294   scope.SetCordRep(rep);
1295 }
1296 
1297 inline void Cord::InlineRep::CommitTree(absl::Nullable<const CordRep*> old_rep,
1298                                         absl::Nonnull<CordRep*> rep,
1299                                         const CordzUpdateScope& scope,
1300                                         MethodIdentifier method) {
1301   if (old_rep) {
1302     SetTree(rep, scope);
1303   } else {
1304     EmplaceTree(rep, method);
1305   }
1306 }
1307 
1308 inline absl::Nullable<absl::cord_internal::CordRep*> Cord::InlineRep::clear() {
1309   if (is_tree()) {
1310     CordzInfo::MaybeUntrackCord(cordz_info());
1311   }
1312   absl::cord_internal::CordRep* result = tree();
1313   ResetToEmpty();
1314   return result;
1315 }
1316 
1317 inline void Cord::InlineRep::CopyToArray(absl::Nonnull<char*> dst) const {
1318   assert(!is_tree());
1319   size_t n = inline_size();
1320   assert(n != 0);
1321   cord_internal::SmallMemmove(dst, data_.as_chars(), n);
1322 }
1323 
1324 inline void Cord::InlineRep::MaybeRemoveEmptyCrcNode() {
1325   CordRep* rep = tree();
1326   if (rep == nullptr || ABSL_PREDICT_TRUE(rep->length > 0)) {
1327     return;
1328   }
1329   assert(rep->IsCrc());
1330   assert(rep->crc()->child == nullptr);
1331   CordzInfo::MaybeUntrackCord(cordz_info());
1332   CordRep::Unref(rep);
1333   ResetToEmpty();
1334 }
1335 
1336 constexpr inline Cord::Cord() noexcept {}
1337 
1338 inline Cord::Cord(absl::string_view src)
1339     : Cord(src, CordzUpdateTracker::kConstructorString) {}
1340 
1341 template <typename T>
1342 constexpr Cord::Cord(strings_internal::StringConstant<T>)
1343     : contents_(strings_internal::StringConstant<T>::value,
1344                 strings_internal::StringConstant<T>::value.size() <=
1345                         cord_internal::kMaxInline
1346                     ? nullptr
1347                     : &cord_internal::ConstInitExternalStorage<
1348                           strings_internal::StringConstant<T>>::value) {}
1349 
1350 inline Cord& Cord::operator=(const Cord& x) {
1351   contents_ = x.contents_;
1352   return *this;
1353 }
1354 
1355 template <typename T, Cord::EnableIfString<T>>
1356 Cord& Cord::operator=(T&& src) {
1357   if (src.size() <= cord_internal::kMaxBytesToCopy) {
1358     return operator=(absl::string_view(src));
1359   } else {
1360     return AssignLargeString(std::forward<T>(src));
1361   }
1362 }
1363 
1364 inline Cord::Cord(const Cord& src) : contents_(src.contents_) {}
1365 
1366 inline Cord::Cord(Cord&& src) noexcept : contents_(std::move(src.contents_)) {}
1367 
1368 inline void Cord::swap(Cord& other) noexcept {
1369   contents_.Swap(&other.contents_);
1370 }
1371 
1372 inline Cord& Cord::operator=(Cord&& x) noexcept {
1373   contents_ = std::move(x.contents_);
1374   return *this;
1375 }
1376 
1377 extern template Cord::Cord(std::string&& src);
1378 
1379 inline size_t Cord::size() const {
1380   // Length is 1st field in str.rep_
1381   return contents_.size();
1382 }
1383 
1384 inline bool Cord::empty() const { return size() == 0; }
1385 
1386 inline size_t Cord::EstimatedMemoryUsage(
1387     CordMemoryAccounting accounting_method) const {
1388   size_t result = sizeof(Cord);
1389   if (const absl::cord_internal::CordRep* rep = contents_.tree()) {
1390     switch (accounting_method) {
1391       case CordMemoryAccounting::kFairShare:
1392         result += cord_internal::GetEstimatedFairShareMemoryUsage(rep);
1393         break;
1394       case CordMemoryAccounting::kTotalMorePrecise:
1395         result += cord_internal::GetMorePreciseMemoryUsage(rep);
1396         break;
1397       case CordMemoryAccounting::kTotal:
1398         result += cord_internal::GetEstimatedMemoryUsage(rep);
1399         break;
1400     }
1401   }
1402   return result;
1403 }
1404 
1405 inline absl::optional<absl::string_view> Cord::TryFlat() const
1406     ABSL_ATTRIBUTE_LIFETIME_BOUND {
1407   absl::cord_internal::CordRep* rep = contents_.tree();
1408   if (rep == nullptr) {
1409     return absl::string_view(contents_.data(), contents_.size());
1410   }
1411   absl::string_view fragment;
1412   if (GetFlatAux(rep, &fragment)) {
1413     return fragment;
1414   }
1415   return absl::nullopt;
1416 }
1417 
1418 inline absl::string_view Cord::Flatten() ABSL_ATTRIBUTE_LIFETIME_BOUND {
1419   absl::cord_internal::CordRep* rep = contents_.tree();
1420   if (rep == nullptr) {
1421     return absl::string_view(contents_.data(), contents_.size());
1422   } else {
1423     absl::string_view already_flat_contents;
1424     if (GetFlatAux(rep, &already_flat_contents)) {
1425       return already_flat_contents;
1426     }
1427   }
1428   return FlattenSlowPath();
1429 }
1430 
1431 inline void Cord::Append(absl::string_view src) {
1432   contents_.AppendArray(src, CordzUpdateTracker::kAppendString);
1433 }
1434 
1435 inline void Cord::Prepend(absl::string_view src) {
1436   PrependArray(src, CordzUpdateTracker::kPrependString);
1437 }
1438 
1439 inline void Cord::Append(CordBuffer buffer) {
1440   if (ABSL_PREDICT_FALSE(buffer.length() == 0)) return;
1441   contents_.MaybeRemoveEmptyCrcNode();
1442   absl::string_view short_value;
1443   if (CordRep* rep = buffer.ConsumeValue(short_value)) {
1444     contents_.AppendTree(rep, CordzUpdateTracker::kAppendCordBuffer);
1445   } else {
1446     AppendPrecise(short_value, CordzUpdateTracker::kAppendCordBuffer);
1447   }
1448 }
1449 
1450 inline void Cord::Prepend(CordBuffer buffer) {
1451   if (ABSL_PREDICT_FALSE(buffer.length() == 0)) return;
1452   contents_.MaybeRemoveEmptyCrcNode();
1453   absl::string_view short_value;
1454   if (CordRep* rep = buffer.ConsumeValue(short_value)) {
1455     contents_.PrependTree(rep, CordzUpdateTracker::kPrependCordBuffer);
1456   } else {
1457     PrependPrecise(short_value, CordzUpdateTracker::kPrependCordBuffer);
1458   }
1459 }
1460 
1461 inline CordBuffer Cord::GetAppendBuffer(size_t capacity, size_t min_capacity) {
1462   if (empty()) return CordBuffer::CreateWithDefaultLimit(capacity);
1463   return GetAppendBufferSlowPath(0, capacity, min_capacity);
1464 }
1465 
1466 inline CordBuffer Cord::GetCustomAppendBuffer(size_t block_size,
1467                                               size_t capacity,
1468                                               size_t min_capacity) {
1469   if (empty()) {
1470     return block_size ? CordBuffer::CreateWithCustomLimit(block_size, capacity)
1471                       : CordBuffer::CreateWithDefaultLimit(capacity);
1472   }
1473   return GetAppendBufferSlowPath(block_size, capacity, min_capacity);
1474 }
1475 
1476 extern template void Cord::Append(std::string&& src);
1477 extern template void Cord::Prepend(std::string&& src);
1478 
1479 inline int Cord::Compare(const Cord& rhs) const {
1480   if (!contents_.is_tree() && !rhs.contents_.is_tree()) {
1481     return contents_.data_.Compare(rhs.contents_.data_);
1482   }
1483 
1484   return CompareImpl(rhs);
1485 }
1486 
1487 // Does 'this' cord start/end with rhs
1488 inline bool Cord::StartsWith(const Cord& rhs) const {
1489   if (contents_.IsSame(rhs.contents_)) return true;
1490   size_t rhs_size = rhs.size();
1491   if (size() < rhs_size) return false;
1492   return EqualsImpl(rhs, rhs_size);
1493 }
1494 
1495 inline bool Cord::StartsWith(absl::string_view rhs) const {
1496   size_t rhs_size = rhs.size();
1497   if (size() < rhs_size) return false;
1498   return EqualsImpl(rhs, rhs_size);
1499 }
1500 
1501 inline void Cord::CopyToArrayImpl(absl::Nonnull<char*> dst) const {
1502   if (!contents_.is_tree()) {
1503     if (!empty()) contents_.CopyToArray(dst);
1504   } else {
1505     CopyToArraySlowPath(dst);
1506   }
1507 }
1508 
1509 inline void Cord::ChunkIterator::InitTree(
1510     absl::Nonnull<cord_internal::CordRep*> tree) {
1511   tree = cord_internal::SkipCrcNode(tree);
1512   if (tree->tag == cord_internal::BTREE) {
1513     current_chunk_ = btree_reader_.Init(tree->btree());
1514   } else {
1515     current_leaf_ = tree;
1516     current_chunk_ = cord_internal::EdgeData(tree);
1517   }
1518 }
1519 
1520 inline Cord::ChunkIterator::ChunkIterator(
1521     absl::Nonnull<cord_internal::CordRep*> tree) {
1522   bytes_remaining_ = tree->length;
1523   InitTree(tree);
1524 }
1525 
1526 inline Cord::ChunkIterator::ChunkIterator(absl::Nonnull<const Cord*> cord) {
1527   if (CordRep* tree = cord->contents_.tree()) {
1528     bytes_remaining_ = tree->length;
1529     if (ABSL_PREDICT_TRUE(bytes_remaining_ != 0)) {
1530       InitTree(tree);
1531     } else {
1532       current_chunk_ = {};
1533     }
1534   } else {
1535     bytes_remaining_ = cord->contents_.inline_size();
1536     current_chunk_ = {cord->contents_.data(), bytes_remaining_};
1537   }
1538 }
1539 
1540 inline Cord::ChunkIterator& Cord::ChunkIterator::AdvanceBtree() {
1541   current_chunk_ = btree_reader_.Next();
1542   return *this;
1543 }
1544 
1545 inline void Cord::ChunkIterator::AdvanceBytesBtree(size_t n) {
1546   assert(n >= current_chunk_.size());
1547   bytes_remaining_ -= n;
1548   if (bytes_remaining_) {
1549     if (n == current_chunk_.size()) {
1550       current_chunk_ = btree_reader_.Next();
1551     } else {
1552       size_t offset = btree_reader_.length() - bytes_remaining_;
1553       current_chunk_ = btree_reader_.Seek(offset);
1554     }
1555   } else {
1556     current_chunk_ = {};
1557   }
1558 }
1559 
1560 inline Cord::ChunkIterator& Cord::ChunkIterator::operator++() {
1561   ABSL_HARDENING_ASSERT(bytes_remaining_ > 0 &&
1562                         "Attempted to iterate past `end()`");
1563   assert(bytes_remaining_ >= current_chunk_.size());
1564   bytes_remaining_ -= current_chunk_.size();
1565   if (bytes_remaining_ > 0) {
1566     if (btree_reader_) {
1567       return AdvanceBtree();
1568     } else {
1569       assert(!current_chunk_.empty());  // Called on invalid iterator.
1570     }
1571     current_chunk_ = {};
1572   }
1573   return *this;
1574 }
1575 
1576 inline Cord::ChunkIterator Cord::ChunkIterator::operator++(int) {
1577   ChunkIterator tmp(*this);
1578   operator++();
1579   return tmp;
1580 }
1581 
1582 inline bool Cord::ChunkIterator::operator==(const ChunkIterator& other) const {
1583   return bytes_remaining_ == other.bytes_remaining_;
1584 }
1585 
1586 inline bool Cord::ChunkIterator::operator!=(const ChunkIterator& other) const {
1587   return !(*this == other);
1588 }
1589 
1590 inline Cord::ChunkIterator::reference Cord::ChunkIterator::operator*() const {
1591   ABSL_HARDENING_ASSERT(bytes_remaining_ != 0);
1592   return current_chunk_;
1593 }
1594 
1595 inline Cord::ChunkIterator::pointer Cord::ChunkIterator::operator->() const {
1596   ABSL_HARDENING_ASSERT(bytes_remaining_ != 0);
1597   return &current_chunk_;
1598 }
1599 
1600 inline void Cord::ChunkIterator::RemoveChunkPrefix(size_t n) {
1601   assert(n < current_chunk_.size());
1602   current_chunk_.remove_prefix(n);
1603   bytes_remaining_ -= n;
1604 }
1605 
1606 inline void Cord::ChunkIterator::AdvanceBytes(size_t n) {
1607   assert(bytes_remaining_ >= n);
1608   if (ABSL_PREDICT_TRUE(n < current_chunk_.size())) {
1609     RemoveChunkPrefix(n);
1610   } else if (n != 0) {
1611     if (btree_reader_) {
1612       AdvanceBytesBtree(n);
1613     } else {
1614       bytes_remaining_ = 0;
1615     }
1616   }
1617 }
1618 
1619 inline Cord::ChunkIterator Cord::chunk_begin() const {
1620   return ChunkIterator(this);
1621 }
1622 
1623 inline Cord::ChunkIterator Cord::chunk_end() const { return ChunkIterator(); }
1624 
1625 inline Cord::ChunkIterator Cord::ChunkRange::begin() const {
1626   return cord_->chunk_begin();
1627 }
1628 
1629 inline Cord::ChunkIterator Cord::ChunkRange::end() const {
1630   return cord_->chunk_end();
1631 }
1632 
1633 inline Cord::ChunkRange Cord::Chunks() const { return ChunkRange(this); }
1634 
1635 inline Cord::CharIterator& Cord::CharIterator::operator++() {
1636   if (ABSL_PREDICT_TRUE(chunk_iterator_->size() > 1)) {
1637     chunk_iterator_.RemoveChunkPrefix(1);
1638   } else {
1639     ++chunk_iterator_;
1640   }
1641   return *this;
1642 }
1643 
1644 inline Cord::CharIterator Cord::CharIterator::operator++(int) {
1645   CharIterator tmp(*this);
1646   operator++();
1647   return tmp;
1648 }
1649 
1650 inline bool Cord::CharIterator::operator==(const CharIterator& other) const {
1651   return chunk_iterator_ == other.chunk_iterator_;
1652 }
1653 
1654 inline bool Cord::CharIterator::operator!=(const CharIterator& other) const {
1655   return !(*this == other);
1656 }
1657 
1658 inline Cord::CharIterator::reference Cord::CharIterator::operator*() const {
1659   return *chunk_iterator_->data();
1660 }
1661 
1662 inline Cord::CharIterator::pointer Cord::CharIterator::operator->() const {
1663   return chunk_iterator_->data();
1664 }
1665 
1666 inline Cord Cord::AdvanceAndRead(absl::Nonnull<CharIterator*> it,
1667                                  size_t n_bytes) {
1668   assert(it != nullptr);
1669   return it->chunk_iterator_.AdvanceAndReadBytes(n_bytes);
1670 }
1671 
1672 inline void Cord::Advance(absl::Nonnull<CharIterator*> it, size_t n_bytes) {
1673   assert(it != nullptr);
1674   it->chunk_iterator_.AdvanceBytes(n_bytes);
1675 }
1676 
1677 inline absl::string_view Cord::ChunkRemaining(const CharIterator& it) {
1678   return *it.chunk_iterator_;
1679 }
1680 
1681 inline Cord::CharIterator Cord::char_begin() const {
1682   return CharIterator(this);
1683 }
1684 
1685 inline Cord::CharIterator Cord::char_end() const { return CharIterator(); }
1686 
1687 inline Cord::CharIterator Cord::CharRange::begin() const {
1688   return cord_->char_begin();
1689 }
1690 
1691 inline Cord::CharIterator Cord::CharRange::end() const {
1692   return cord_->char_end();
1693 }
1694 
1695 inline Cord::CharRange Cord::Chars() const { return CharRange(this); }
1696 
1697 inline void Cord::ForEachChunk(
1698     absl::FunctionRef<void(absl::string_view)> callback) const {
1699   absl::cord_internal::CordRep* rep = contents_.tree();
1700   if (rep == nullptr) {
1701     callback(absl::string_view(contents_.data(), contents_.size()));
1702   } else {
1703     ForEachChunkAux(rep, callback);
1704   }
1705 }
1706 
1707 // Nonmember Cord-to-Cord relational operators.
1708 inline bool operator==(const Cord& lhs, const Cord& rhs) {
1709   if (lhs.contents_.IsSame(rhs.contents_)) return true;
1710   size_t rhs_size = rhs.size();
1711   if (lhs.size() != rhs_size) return false;
1712   return lhs.EqualsImpl(rhs, rhs_size);
1713 }
1714 
1715 inline bool operator!=(const Cord& x, const Cord& y) { return !(x == y); }
1716 inline bool operator<(const Cord& x, const Cord& y) { return x.Compare(y) < 0; }
1717 inline bool operator>(const Cord& x, const Cord& y) { return x.Compare(y) > 0; }
1718 inline bool operator<=(const Cord& x, const Cord& y) {
1719   return x.Compare(y) <= 0;
1720 }
1721 inline bool operator>=(const Cord& x, const Cord& y) {
1722   return x.Compare(y) >= 0;
1723 }
1724 
1725 // Nonmember Cord-to-absl::string_view relational operators.
1726 //
1727 // Due to implicit conversions, these also enable comparisons of Cord with
1728 // std::string and const char*.
1729 inline bool operator==(const Cord& lhs, absl::string_view rhs) {
1730   size_t lhs_size = lhs.size();
1731   size_t rhs_size = rhs.size();
1732   if (lhs_size != rhs_size) return false;
1733   return lhs.EqualsImpl(rhs, rhs_size);
1734 }
1735 
1736 inline bool operator==(absl::string_view x, const Cord& y) { return y == x; }
1737 inline bool operator!=(const Cord& x, absl::string_view y) { return !(x == y); }
1738 inline bool operator!=(absl::string_view x, const Cord& y) { return !(x == y); }
1739 inline bool operator<(const Cord& x, absl::string_view y) {
1740   return x.Compare(y) < 0;
1741 }
1742 inline bool operator<(absl::string_view x, const Cord& y) {
1743   return y.Compare(x) > 0;
1744 }
1745 inline bool operator>(const Cord& x, absl::string_view y) { return y < x; }
1746 inline bool operator>(absl::string_view x, const Cord& y) { return y < x; }
1747 inline bool operator<=(const Cord& x, absl::string_view y) { return !(y < x); }
1748 inline bool operator<=(absl::string_view x, const Cord& y) { return !(y < x); }
1749 inline bool operator>=(const Cord& x, absl::string_view y) { return !(x < y); }
1750 inline bool operator>=(absl::string_view x, const Cord& y) { return !(x < y); }
1751 
1752 // Some internals exposed to test code.
1753 namespace strings_internal {
1754 class CordTestAccess {
1755  public:
1756   static size_t FlatOverhead();
1757   static size_t MaxFlatLength();
1758   static size_t SizeofCordRepExternal();
1759   static size_t SizeofCordRepSubstring();
1760   static size_t FlatTagToLength(uint8_t tag);
1761   static uint8_t LengthToTag(size_t s);
1762 };
1763 }  // namespace strings_internal
1764 ABSL_NAMESPACE_END
1765 }  // namespace absl
1766 
1767 #endif  // ABSL_STRINGS_CORD_H_