• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // -----------------------------------------------------------------------------
16 // File: cord.h
17 // -----------------------------------------------------------------------------
18 //
19 // This file defines the `absl::Cord` data structure and operations on that data
20 // structure. A Cord is a string-like sequence of characters optimized for
21 // specific use cases. Unlike a `std::string`, which stores an array of
22 // contiguous characters, Cord data is stored in a structure consisting of
23 // separate, reference-counted "chunks."
24 //
25 // Because a Cord consists of these chunks, data can be added to or removed from
26 // a Cord during its lifetime. Chunks may also be shared between Cords. Unlike a
27 // `std::string`, a Cord can therefore accommodate data that changes over its
28 // lifetime, though it's not quite "mutable"; it can change only in the
29 // attachment, detachment, or rearrangement of chunks of its constituent data.
30 //
31 // A Cord provides some benefit over `std::string` under the following (albeit
32 // narrow) circumstances:
33 //
34 //   * Cord data is designed to grow and shrink over a Cord's lifetime. Cord
35 //     provides efficient insertions and deletions at the start and end of the
36 //     character sequences, avoiding copies in those cases. Static data should
37 //     generally be stored as strings.
38 //   * External memory consisting of string-like data can be directly added to
39 //     a Cord without requiring copies or allocations.
40 //   * Cord data may be shared and copied cheaply. Cord provides a copy-on-write
41 //     implementation and cheap sub-Cord operations. Copying a Cord is an O(1)
42 //     operation.
43 //
44 // As a consequence to the above, Cord data is generally large. Small data
45 // should generally use strings, as construction of a Cord requires some
46 // overhead. Small Cords (<= 15 bytes) are represented inline, but most small
47 // Cords are expected to grow over their lifetimes.
48 //
49 // Note that because a Cord is made up of separate chunked data, random access
50 // to character data within a Cord is slower than within a `std::string`.
51 //
52 // Thread Safety
53 //
54 // Cord has the same thread-safety properties as many other types like
55 // std::string, std::vector<>, int, etc -- it is thread-compatible. In
56 // particular, if threads do not call non-const methods, then it is safe to call
57 // const methods without synchronization. Copying a Cord produces a new instance
58 // that can be used concurrently with the original in arbitrary ways.
59 
60 #ifndef ABSL_STRINGS_CORD_H_
61 #define ABSL_STRINGS_CORD_H_
62 
63 #include <algorithm>
64 #include <cstddef>
65 #include <cstdint>
66 #include <cstring>
67 #include <iosfwd>
68 #include <iterator>
69 #include <string>
70 #include <type_traits>
71 
72 #include "absl/base/attributes.h"
73 #include "absl/base/config.h"
74 #include "absl/base/internal/endian.h"
75 #include "absl/base/internal/per_thread_tls.h"
76 #include "absl/base/macros.h"
77 #include "absl/base/nullability.h"
78 #include "absl/base/optimization.h"
79 #include "absl/base/port.h"
80 #include "absl/container/inlined_vector.h"
81 #include "absl/crc/internal/crc_cord_state.h"
82 #include "absl/functional/function_ref.h"
83 #include "absl/meta/type_traits.h"
84 #include "absl/strings/cord_analysis.h"
85 #include "absl/strings/cord_buffer.h"
86 #include "absl/strings/internal/cord_data_edge.h"
87 #include "absl/strings/internal/cord_internal.h"
88 #include "absl/strings/internal/cord_rep_btree.h"
89 #include "absl/strings/internal/cord_rep_btree_reader.h"
90 #include "absl/strings/internal/cord_rep_crc.h"
91 #include "absl/strings/internal/cordz_functions.h"
92 #include "absl/strings/internal/cordz_info.h"
93 #include "absl/strings/internal/cordz_statistics.h"
94 #include "absl/strings/internal/cordz_update_scope.h"
95 #include "absl/strings/internal/cordz_update_tracker.h"
96 #include "absl/strings/internal/resize_uninitialized.h"
97 #include "absl/strings/internal/string_constant.h"
98 #include "absl/strings/string_view.h"
99 #include "absl/types/optional.h"
100 
101 namespace absl {
102 ABSL_NAMESPACE_BEGIN
103 class Cord;
104 class CordTestPeer;
105 template <typename Releaser>
106 Cord MakeCordFromExternal(absl::string_view, Releaser&&);
107 void CopyCordToString(const Cord& src, absl::Nonnull<std::string*> dst);
108 void AppendCordToString(const Cord& src, absl::Nonnull<std::string*> dst);
109 
110 // Cord memory accounting modes
111 enum class CordMemoryAccounting {
112   // Counts the *approximate* number of bytes held in full or in part by this
113   // Cord (which may not remain the same between invocations). Cords that share
114   // memory could each be "charged" independently for the same shared memory.
115   // See also comment on `kTotalMorePrecise` on internally shared memory.
116   kTotal,
117 
118   // Counts the *approximate* number of bytes held in full or in part by this
119   // Cord for the distinct memory held by this cord. This option is similar
120   // to `kTotal`, except that if the cord has multiple references to the same
121   // memory, that memory is only counted once.
122   //
123   // For example:
124   //   absl::Cord cord;
125   //   cord.Append(some_other_cord);
126   //   cord.Append(some_other_cord);
127   //   // Counts `some_other_cord` twice:
128   //   cord.EstimatedMemoryUsage(kTotal);
129   //   // Counts `some_other_cord` once:
130   //   cord.EstimatedMemoryUsage(kTotalMorePrecise);
131   //
132   // The `kTotalMorePrecise` number is more expensive to compute as it requires
133   // deduplicating all memory references. Applications should prefer to use
134   // `kFairShare` or `kTotal` unless they really need a more precise estimate
135   // on "how much memory is potentially held / kept alive by this cord?"
136   kTotalMorePrecise,
137 
138   // Counts the *approximate* number of bytes held in full or in part by this
139   // Cord weighted by the sharing ratio of that data. For example, if some data
140   // edge is shared by 4 different Cords, then each cord is attributed 1/4th of
141   // the total memory usage as a 'fair share' of the total memory usage.
142   kFairShare,
143 };
144 
145 // Cord
146 //
147 // A Cord is a sequence of characters, designed to be more efficient than a
148 // `std::string` in certain circumstances: namely, large string data that needs
149 // to change over its lifetime or shared, especially when such data is shared
150 // across API boundaries.
151 //
152 // A Cord stores its character data in a structure that allows efficient prepend
153 // and append operations. This makes a Cord useful for large string data sent
154 // over in a wire format that may need to be prepended or appended at some point
155 // during the data exchange (e.g. HTTP, protocol buffers). For example, a
156 // Cord is useful for storing an HTTP request, and prepending an HTTP header to
157 // such a request.
158 //
159 // Cords should not be used for storing general string data, however. They
160 // require overhead to construct and are slower than strings for random access.
161 //
162 // The Cord API provides the following common API operations:
163 //
164 // * Create or assign Cords out of existing string data, memory, or other Cords
165 // * Append and prepend data to an existing Cord
166 // * Create new Sub-Cords from existing Cord data
167 // * Swap Cord data and compare Cord equality
168 // * Write out Cord data by constructing a `std::string`
169 //
170 // Additionally, the API provides iterator utilities to iterate through Cord
171 // data via chunks or character bytes.
172 //
173 class Cord {
174  private:
175   template <typename T>
176   using EnableIfString =
177       absl::enable_if_t<std::is_same<T, std::string>::value, int>;
178 
179  public:
180   // Cord::Cord() Constructors.
181 
182   // Creates an empty Cord.
183   constexpr Cord() noexcept;
184 
185   // Creates a Cord from an existing Cord. Cord is copyable and efficiently
186   // movable. The moved-from state is valid but unspecified.
187   Cord(const Cord& src);
188   Cord(Cord&& src) noexcept;
189   Cord& operator=(const Cord& x);
190   Cord& operator=(Cord&& x) noexcept;
191 
192   // Creates a Cord from a `src` string. This constructor is marked explicit to
193   // prevent implicit Cord constructions from arguments convertible to an
194   // `absl::string_view`.
195   explicit Cord(absl::string_view src);
196   Cord& operator=(absl::string_view src);
197 
198   // Creates a Cord from a `std::string&&` rvalue. These constructors are
199   // templated to avoid ambiguities for types that are convertible to both
200   // `absl::string_view` and `std::string`, such as `const char*`.
201   template <typename T, EnableIfString<T> = 0>
202   explicit Cord(T&& src);
203   template <typename T, EnableIfString<T> = 0>
204   Cord& operator=(T&& src);
205 
206   // Cord::~Cord()
207   //
208   // Destructs the Cord.
~Cord()209   ~Cord() {
210     if (contents_.is_tree()) DestroyCordSlow();
211   }
212 
213   // MakeCordFromExternal()
214   //
215   // Creates a Cord that takes ownership of external string memory. The
216   // contents of `data` are not copied to the Cord; instead, the external
217   // memory is added to the Cord and reference-counted. This data may not be
218   // changed for the life of the Cord, though it may be prepended or appended
219   // to.
220   //
221   // `MakeCordFromExternal()` takes a callable "releaser" that is invoked when
222   // the reference count for `data` reaches zero. As noted above, this data must
223   // remain live until the releaser is invoked. The callable releaser also must:
224   //
225   //   * be move constructible
226   //   * support `void operator()(absl::string_view) const` or `void operator()`
227   //
228   // Example:
229   //
230   // Cord MakeCord(BlockPool* pool) {
231   //   Block* block = pool->NewBlock();
232   //   FillBlock(block);
233   //   return absl::MakeCordFromExternal(
234   //       block->ToStringView(),
235   //       [pool, block](absl::string_view v) {
236   //         pool->FreeBlock(block, v);
237   //       });
238   // }
239   //
240   // WARNING: Because a Cord can be reference-counted, it's likely a bug if your
241   // releaser doesn't do anything. For example, consider the following:
242   //
243   // void Foo(const char* buffer, int len) {
244   //   auto c = absl::MakeCordFromExternal(absl::string_view(buffer, len),
245   //                                       [](absl::string_view) {});
246   //
247   //   // BUG: If Bar() copies its cord for any reason, including keeping a
248   //   // substring of it, the lifetime of buffer might be extended beyond
249   //   // when Foo() returns.
250   //   Bar(c);
251   // }
252   template <typename Releaser>
253   friend Cord MakeCordFromExternal(absl::string_view data, Releaser&& releaser);
254 
255   // Cord::Clear()
256   //
257   // Releases the Cord data. Any nodes that share data with other Cords, if
258   // applicable, will have their reference counts reduced by 1.
259   ABSL_ATTRIBUTE_REINITIALIZES void Clear();
260 
261   // Cord::Append()
262   //
263   // Appends data to the Cord, which may come from another Cord or other string
264   // data.
265   void Append(const Cord& src);
266   void Append(Cord&& src);
267   void Append(absl::string_view src);
268   template <typename T, EnableIfString<T> = 0>
269   void Append(T&& src);
270 
271   // Appends `buffer` to this cord, unless `buffer` has a zero length in which
272   // case this method has no effect on this cord instance.
273   // This method is guaranteed to consume `buffer`.
274   void Append(CordBuffer buffer);
275 
276   // Returns a CordBuffer, re-using potential existing capacity in this cord.
277   //
278   // Cord instances may have additional unused capacity in the last (or first)
279   // nodes of the underlying tree to facilitate amortized growth. This method
280   // allows applications to explicitly use this spare capacity if available,
281   // or create a new CordBuffer instance otherwise.
282   // If this cord has a final non-shared node with at least `min_capacity`
283   // available, then this method will return that buffer including its data
284   // contents. I.e.; the returned buffer will have a non-zero length, and
285   // a capacity of at least `buffer.length + min_capacity`. Otherwise, this
286   // method will return `CordBuffer::CreateWithDefaultLimit(capacity)`.
287   //
288   // Below an example of using GetAppendBuffer. Notice that in this example we
289   // use `GetAppendBuffer()` only on the first iteration. As we know nothing
290   // about any initial extra capacity in `cord`, we may be able to use the extra
291   // capacity. But as we add new buffers with fully utilized contents after that
292   // we avoid calling `GetAppendBuffer()` on subsequent iterations: while this
293   // works fine, it results in an unnecessary inspection of cord contents:
294   //
295   //   void AppendRandomDataToCord(absl::Cord &cord, size_t n) {
296   //     bool first = true;
297   //     while (n > 0) {
298   //       CordBuffer buffer = first ? cord.GetAppendBuffer(n)
299   //                                 : CordBuffer::CreateWithDefaultLimit(n);
300   //       absl::Span<char> data = buffer.available_up_to(n);
301   //       FillRandomValues(data.data(), data.size());
302   //       buffer.IncreaseLengthBy(data.size());
303   //       cord.Append(std::move(buffer));
304   //       n -= data.size();
305   //       first = false;
306   //     }
307   //   }
308   CordBuffer GetAppendBuffer(size_t capacity, size_t min_capacity = 16);
309 
310   // Returns a CordBuffer, re-using potential existing capacity in this cord.
311   //
312   // This function is identical to `GetAppendBuffer`, except that in the case
313   // where a new `CordBuffer` is allocated, it is allocated using the provided
314   // custom limit instead of the default limit. `GetAppendBuffer` will default
315   // to `CordBuffer::CreateWithDefaultLimit(capacity)` whereas this method
316   // will default to `CordBuffer::CreateWithCustomLimit(block_size, capacity)`.
317   // This method is equivalent to `GetAppendBuffer` if `block_size` is zero.
318   // See the documentation for `CreateWithCustomLimit` for more details on the
319   // restrictions and legal values for `block_size`.
320   CordBuffer GetCustomAppendBuffer(size_t block_size, size_t capacity,
321                                    size_t min_capacity = 16);
322 
323   // Cord::Prepend()
324   //
325   // Prepends data to the Cord, which may come from another Cord or other string
326   // data.
327   void Prepend(const Cord& src);
328   void Prepend(absl::string_view src);
329   template <typename T, EnableIfString<T> = 0>
330   void Prepend(T&& src);
331 
332   // Prepends `buffer` to this cord, unless `buffer` has a zero length in which
333   // case this method has no effect on this cord instance.
334   // This method is guaranteed to consume `buffer`.
335   void Prepend(CordBuffer buffer);
336 
337   // Cord::RemovePrefix()
338   //
339   // Removes the first `n` bytes of a Cord.
340   void RemovePrefix(size_t n);
341   void RemoveSuffix(size_t n);
342 
343   // Cord::Subcord()
344   //
345   // Returns a new Cord representing the subrange [pos, pos + new_size) of
346   // *this. If pos >= size(), the result is empty(). If
347   // (pos + new_size) >= size(), the result is the subrange [pos, size()).
348   Cord Subcord(size_t pos, size_t new_size) const;
349 
350   // Cord::swap()
351   //
352   // Swaps the contents of the Cord with `other`.
353   void swap(Cord& other) noexcept;
354 
355   // swap()
356   //
357   // Swaps the contents of two Cords.
swap(Cord & x,Cord & y)358   friend void swap(Cord& x, Cord& y) noexcept { x.swap(y); }
359 
360   // Cord::size()
361   //
362   // Returns the size of the Cord.
363   size_t size() const;
364 
365   // Cord::empty()
366   //
367   // Determines whether the given Cord is empty, returning `true` if so.
368   bool empty() const;
369 
370   // Cord::EstimatedMemoryUsage()
371   //
372   // Returns the *approximate* number of bytes held by this cord.
373   // See CordMemoryAccounting for more information on the accounting method.
374   size_t EstimatedMemoryUsage(CordMemoryAccounting accounting_method =
375                                   CordMemoryAccounting::kTotal) const;
376 
377   // Cord::Compare()
378   //
379   // Compares 'this' Cord with rhs. This function and its relatives treat Cords
380   // as sequences of unsigned bytes. The comparison is a straightforward
381   // lexicographic comparison. `Cord::Compare()` returns values as follows:
382   //
383   //   -1  'this' Cord is smaller
384   //    0  two Cords are equal
385   //    1  'this' Cord is larger
386   int Compare(absl::string_view rhs) const;
387   int Compare(const Cord& rhs) const;
388 
389   // Cord::StartsWith()
390   //
391   // Determines whether the Cord starts with the passed string data `rhs`.
392   bool StartsWith(const Cord& rhs) const;
393   bool StartsWith(absl::string_view rhs) const;
394 
395   // Cord::EndsWith()
396   //
397   // Determines whether the Cord ends with the passed string data `rhs`.
398   bool EndsWith(absl::string_view rhs) const;
399   bool EndsWith(const Cord& rhs) const;
400 
401   // Cord::Contains()
402   //
403   // Determines whether the Cord contains the passed string data `rhs`.
404   bool Contains(absl::string_view rhs) const;
405   bool Contains(const Cord& rhs) const;
406 
407   // Cord::operator std::string()
408   //
409   // Converts a Cord into a `std::string()`. This operator is marked explicit to
410   // prevent unintended Cord usage in functions that take a string.
411   explicit operator std::string() const;
412 
413   // CopyCordToString()
414   //
415   // Copies the contents of a `src` Cord into a `*dst` string.
416   //
417   // This function optimizes the case of reusing the destination string since it
418   // can reuse previously allocated capacity. However, this function does not
419   // guarantee that pointers previously returned by `dst->data()` remain valid
420   // even if `*dst` had enough capacity to hold `src`. If `*dst` is a new
421   // object, prefer to simply use the conversion operator to `std::string`.
422   friend void CopyCordToString(const Cord& src,
423                                absl::Nonnull<std::string*> dst);
424 
425   // AppendCordToString()
426   //
427   // Appends the contents of a `src` Cord to a `*dst` string.
428   //
429   // This function optimizes the case of appending to a non-empty destination
430   // string. If `*dst` already has capacity to store the contents of the cord,
431   // this function does not invalidate pointers previously returned by
432   // `dst->data()`. If `*dst` is a new object, prefer to simply use the
433   // conversion operator to `std::string`.
434   friend void AppendCordToString(const Cord& src,
435                                  absl::Nonnull<std::string*> dst);
436 
437   class CharIterator;
438 
439   //----------------------------------------------------------------------------
440   // Cord::ChunkIterator
441   //----------------------------------------------------------------------------
442   //
443   // A `Cord::ChunkIterator` allows iteration over the constituent chunks of its
444   // Cord. Such iteration allows you to perform non-const operations on the data
445   // of a Cord without modifying it.
446   //
447   // Generally, you do not instantiate a `Cord::ChunkIterator` directly;
448   // instead, you create one implicitly through use of the `Cord::Chunks()`
449   // member function.
450   //
451   // The `Cord::ChunkIterator` has the following properties:
452   //
453   //   * The iterator is invalidated after any non-const operation on the
454   //     Cord object over which it iterates.
455   //   * The `string_view` returned by dereferencing a valid, non-`end()`
456   //     iterator is guaranteed to be non-empty.
457   //   * Two `ChunkIterator` objects can be compared equal if and only if they
458   //     remain valid and iterate over the same Cord.
459   //   * The iterator in this case is a proxy iterator; the `string_view`
460   //     returned by the iterator does not live inside the Cord, and its
461   //     lifetime is limited to the lifetime of the iterator itself. To help
462   //     prevent lifetime issues, `ChunkIterator::reference` is not a true
463   //     reference type and is equivalent to `value_type`.
464   //   * The iterator keeps state that can grow for Cords that contain many
465   //     nodes and are imbalanced due to sharing. Prefer to pass this type by
466   //     const reference instead of by value.
467   class ChunkIterator {
468    public:
469     using iterator_category = std::input_iterator_tag;
470     using value_type = absl::string_view;
471     using difference_type = ptrdiff_t;
472     using pointer = absl::Nonnull<const value_type*>;
473     using reference = value_type;
474 
475     ChunkIterator() = default;
476 
477     ChunkIterator& operator++();
478     ChunkIterator operator++(int);
479     bool operator==(const ChunkIterator& other) const;
480     bool operator!=(const ChunkIterator& other) const;
481     reference operator*() const;
482     pointer operator->() const;
483 
484     friend class Cord;
485     friend class CharIterator;
486 
487    private:
488     using CordRep = absl::cord_internal::CordRep;
489     using CordRepBtree = absl::cord_internal::CordRepBtree;
490     using CordRepBtreeReader = absl::cord_internal::CordRepBtreeReader;
491 
492     // Constructs a `begin()` iterator from `tree`.
493     explicit ChunkIterator(absl::Nonnull<cord_internal::CordRep*> tree);
494 
495     // Constructs a `begin()` iterator from `cord`.
496     explicit ChunkIterator(absl::Nonnull<const Cord*> cord);
497 
498     // Initializes this instance from a tree. Invoked by constructors.
499     void InitTree(absl::Nonnull<cord_internal::CordRep*> tree);
500 
501     // Removes `n` bytes from `current_chunk_`. Expects `n` to be smaller than
502     // `current_chunk_.size()`.
503     void RemoveChunkPrefix(size_t n);
504     Cord AdvanceAndReadBytes(size_t n);
505     void AdvanceBytes(size_t n);
506 
507     // Btree specific operator++
508     ChunkIterator& AdvanceBtree();
509     void AdvanceBytesBtree(size_t n);
510 
511     // A view into bytes of the current `CordRep`. It may only be a view to a
512     // suffix of bytes if this is being used by `CharIterator`.
513     absl::string_view current_chunk_;
514     // The current leaf, or `nullptr` if the iterator points to short data.
515     // If the current chunk is a substring node, current_leaf_ points to the
516     // underlying flat or external node.
517     absl::Nullable<absl::cord_internal::CordRep*> current_leaf_ = nullptr;
518     // The number of bytes left in the `Cord` over which we are iterating.
519     size_t bytes_remaining_ = 0;
520 
521     // Cord reader for cord btrees. Empty if not traversing a btree.
522     CordRepBtreeReader btree_reader_;
523   };
524 
525   // Cord::chunk_begin()
526   //
527   // Returns an iterator to the first chunk of the `Cord`.
528   //
529   // Generally, prefer using `Cord::Chunks()` within a range-based for loop for
530   // iterating over the chunks of a Cord. This method may be useful for getting
531   // a `ChunkIterator` where range-based for-loops are not useful.
532   //
533   // Example:
534   //
535   //   absl::Cord::ChunkIterator FindAsChunk(const absl::Cord& c,
536   //                                         absl::string_view s) {
537   //     return std::find(c.chunk_begin(), c.chunk_end(), s);
538   //   }
539   ChunkIterator chunk_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
540 
541   // Cord::chunk_end()
542   //
543   // Returns an iterator one increment past the last chunk of the `Cord`.
544   //
545   // Generally, prefer using `Cord::Chunks()` within a range-based for loop for
546   // iterating over the chunks of a Cord. This method may be useful for getting
547   // a `ChunkIterator` where range-based for-loops may not be available.
548   ChunkIterator chunk_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
549 
550   //----------------------------------------------------------------------------
551   // Cord::ChunkRange
552   //----------------------------------------------------------------------------
553   //
554   // `ChunkRange` is a helper class for iterating over the chunks of the `Cord`,
555   // producing an iterator which can be used within a range-based for loop.
556   // Construction of a `ChunkRange` will return an iterator pointing to the
557   // first chunk of the Cord. Generally, do not construct a `ChunkRange`
558   // directly; instead, prefer to use the `Cord::Chunks()` method.
559   //
560   // Implementation note: `ChunkRange` is simply a convenience wrapper over
561   // `Cord::chunk_begin()` and `Cord::chunk_end()`.
562   class ChunkRange {
563    public:
564     // Fulfill minimum c++ container requirements [container.requirements]
565     // These (partial) container type definitions allow ChunkRange to be used
566     // in various utilities expecting a subset of [container.requirements].
567     // For example, the below enables using `::testing::ElementsAre(...)`
568     using value_type = absl::string_view;
569     using reference = value_type&;
570     using const_reference = const value_type&;
571     using iterator = ChunkIterator;
572     using const_iterator = ChunkIterator;
573 
ChunkRange(absl::Nonnull<const Cord * > cord)574     explicit ChunkRange(absl::Nonnull<const Cord*> cord) : cord_(cord) {}
575 
576     ChunkIterator begin() const;
577     ChunkIterator end() const;
578 
579    private:
580     absl::Nonnull<const Cord*> cord_;
581   };
582 
583   // Cord::Chunks()
584   //
585   // Returns a `Cord::ChunkRange` for iterating over the chunks of a `Cord` with
586   // a range-based for-loop. For most iteration tasks on a Cord, use
587   // `Cord::Chunks()` to retrieve this iterator.
588   //
589   // Example:
590   //
591   //   void ProcessChunks(const Cord& cord) {
592   //     for (absl::string_view chunk : cord.Chunks()) { ... }
593   //   }
594   //
595   // Note that the ordinary caveats of temporary lifetime extension apply:
596   //
597   //   void Process() {
598   //     for (absl::string_view chunk : CordFactory().Chunks()) {
599   //       // The temporary Cord returned by CordFactory has been destroyed!
600   //     }
601   //   }
602   ChunkRange Chunks() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
603 
604   //----------------------------------------------------------------------------
605   // Cord::CharIterator
606   //----------------------------------------------------------------------------
607   //
608   // A `Cord::CharIterator` allows iteration over the constituent characters of
609   // a `Cord`.
610   //
611   // Generally, you do not instantiate a `Cord::CharIterator` directly; instead,
612   // you create one implicitly through use of the `Cord::Chars()` member
613   // function.
614   //
615   // A `Cord::CharIterator` has the following properties:
616   //
617   //   * The iterator is invalidated after any non-const operation on the
618   //     Cord object over which it iterates.
619   //   * Two `CharIterator` objects can be compared equal if and only if they
620   //     remain valid and iterate over the same Cord.
621   //   * The iterator keeps state that can grow for Cords that contain many
622   //     nodes and are imbalanced due to sharing. Prefer to pass this type by
623   //     const reference instead of by value.
624   //   * This type cannot act as a forward iterator because a `Cord` can reuse
625   //     sections of memory. This fact violates the requirement for forward
626   //     iterators to compare equal if dereferencing them returns the same
627   //     object.
628   class CharIterator {
629    public:
630     using iterator_category = std::input_iterator_tag;
631     using value_type = char;
632     using difference_type = ptrdiff_t;
633     using pointer = absl::Nonnull<const char*>;
634     using reference = const char&;
635 
636     CharIterator() = default;
637 
638     CharIterator& operator++();
639     CharIterator operator++(int);
640     bool operator==(const CharIterator& other) const;
641     bool operator!=(const CharIterator& other) const;
642     reference operator*() const;
643     pointer operator->() const;
644 
645     friend Cord;
646 
647    private:
CharIterator(absl::Nonnull<const Cord * > cord)648     explicit CharIterator(absl::Nonnull<const Cord*> cord)
649         : chunk_iterator_(cord) {}
650 
651     ChunkIterator chunk_iterator_;
652   };
653 
654   // Cord::AdvanceAndRead()
655   //
656   // Advances the `Cord::CharIterator` by `n_bytes` and returns the bytes
657   // advanced as a separate `Cord`. `n_bytes` must be less than or equal to the
658   // number of bytes within the Cord; otherwise, behavior is undefined. It is
659   // valid to pass `char_end()` and `0`.
660   static Cord AdvanceAndRead(absl::Nonnull<CharIterator*> it, size_t n_bytes);
661 
662   // Cord::Advance()
663   //
664   // Advances the `Cord::CharIterator` by `n_bytes`. `n_bytes` must be less than
665   // or equal to the number of bytes remaining within the Cord; otherwise,
666   // behavior is undefined. It is valid to pass `char_end()` and `0`.
667   static void Advance(absl::Nonnull<CharIterator*> it, size_t n_bytes);
668 
669   // Cord::ChunkRemaining()
670   //
671   // Returns the longest contiguous view starting at the iterator's position.
672   //
673   // `it` must be dereferenceable.
674   static absl::string_view ChunkRemaining(const CharIterator& it);
675 
676   // Cord::char_begin()
677   //
678   // Returns an iterator to the first character of the `Cord`.
679   //
680   // Generally, prefer using `Cord::Chars()` within a range-based for loop for
681   // iterating over the chunks of a Cord. This method may be useful for getting
682   // a `CharIterator` where range-based for-loops may not be available.
683   CharIterator char_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
684 
685   // Cord::char_end()
686   //
687   // Returns an iterator to one past the last character of the `Cord`.
688   //
689   // Generally, prefer using `Cord::Chars()` within a range-based for loop for
690   // iterating over the chunks of a Cord. This method may be useful for getting
691   // a `CharIterator` where range-based for-loops are not useful.
692   CharIterator char_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
693 
694   // Cord::CharRange
695   //
696   // `CharRange` is a helper class for iterating over the characters of a
697   // producing an iterator which can be used within a range-based for loop.
698   // Construction of a `CharRange` will return an iterator pointing to the first
699   // character of the Cord. Generally, do not construct a `CharRange` directly;
700   // instead, prefer to use the `Cord::Chars()` method shown below.
701   //
702   // Implementation note: `CharRange` is simply a convenience wrapper over
703   // `Cord::char_begin()` and `Cord::char_end()`.
704   class CharRange {
705    public:
706     // Fulfill minimum c++ container requirements [container.requirements]
707     // These (partial) container type definitions allow CharRange to be used
708     // in various utilities expecting a subset of [container.requirements].
709     // For example, the below enables using `::testing::ElementsAre(...)`
710     using value_type = char;
711     using reference = value_type&;
712     using const_reference = const value_type&;
713     using iterator = CharIterator;
714     using const_iterator = CharIterator;
715 
CharRange(absl::Nonnull<const Cord * > cord)716     explicit CharRange(absl::Nonnull<const Cord*> cord) : cord_(cord) {}
717 
718     CharIterator begin() const;
719     CharIterator end() const;
720 
721    private:
722     absl::Nonnull<const Cord*> cord_;
723   };
724 
725   // Cord::Chars()
726   //
727   // Returns a `Cord::CharRange` for iterating over the characters of a `Cord`
728   // with a range-based for-loop. For most character-based iteration tasks on a
729   // Cord, use `Cord::Chars()` to retrieve this iterator.
730   //
731   // Example:
732   //
733   //   void ProcessCord(const Cord& cord) {
734   //     for (char c : cord.Chars()) { ... }
735   //   }
736   //
737   // Note that the ordinary caveats of temporary lifetime extension apply:
738   //
739   //   void Process() {
740   //     for (char c : CordFactory().Chars()) {
741   //       // The temporary Cord returned by CordFactory has been destroyed!
742   //     }
743   //   }
744   CharRange Chars() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
745 
746   // Cord::operator[]
747   //
748   // Gets the "i"th character of the Cord and returns it, provided that
749   // 0 <= i < Cord.size().
750   //
751   // NOTE: This routine is reasonably efficient. It is roughly
752   // logarithmic based on the number of chunks that make up the cord. Still,
753   // if you need to iterate over the contents of a cord, you should
754   // use a CharIterator/ChunkIterator rather than call operator[] or Get()
755   // repeatedly in a loop.
756   char operator[](size_t i) const;
757 
758   // Cord::TryFlat()
759   //
760   // If this cord's representation is a single flat array, returns a
761   // string_view referencing that array.  Otherwise returns nullopt.
762   absl::optional<absl::string_view> TryFlat() const
763       ABSL_ATTRIBUTE_LIFETIME_BOUND;
764 
765   // Cord::Flatten()
766   //
767   // Flattens the cord into a single array and returns a view of the data.
768   //
769   // If the cord was already flat, the contents are not modified.
770   absl::string_view Flatten() ABSL_ATTRIBUTE_LIFETIME_BOUND;
771 
772   // Cord::Find()
773   //
774   // Returns an iterator to the first occurrance of the substring `needle`.
775   //
776   // If the substring `needle` does not occur, `Cord::char_end()` is returned.
777   CharIterator Find(absl::string_view needle) const;
778   CharIterator Find(const absl::Cord& needle) const;
779 
780   // Supports absl::Cord as a sink object for absl::Format().
AbslFormatFlush(absl::Nonnull<absl::Cord * > cord,absl::string_view part)781   friend void AbslFormatFlush(absl::Nonnull<absl::Cord*> cord,
782                               absl::string_view part) {
783     cord->Append(part);
784   }
785 
786   // Support automatic stringification with absl::StrCat and absl::StrFormat.
787   template <typename Sink>
AbslStringify(Sink & sink,const absl::Cord & cord)788   friend void AbslStringify(Sink& sink, const absl::Cord& cord) {
789     for (absl::string_view chunk : cord.Chunks()) {
790       sink.Append(chunk);
791     }
792   }
793 
794   // Cord::SetExpectedChecksum()
795   //
796   // Stores a checksum value with this non-empty cord instance, for later
797   // retrieval.
798   //
799   // The expected checksum is a number stored out-of-band, alongside the data.
800   // It is preserved across copies and assignments, but any mutations to a cord
801   // will cause it to lose its expected checksum.
802   //
803   // The expected checksum is not part of a Cord's value, and does not affect
804   // operations such as equality or hashing.
805   //
806   // This field is intended to store a CRC32C checksum for later validation, to
807   // help support end-to-end checksum workflows.  However, the Cord API itself
808   // does no CRC validation, and assigns no meaning to this number.
809   //
810   // This call has no effect if this cord is empty.
811   void SetExpectedChecksum(uint32_t crc);
812 
813   // Returns this cord's expected checksum, if it has one.  Otherwise, returns
814   // nullopt.
815   absl::optional<uint32_t> ExpectedChecksum() const;
816 
817   template <typename H>
AbslHashValue(H hash_state,const absl::Cord & c)818   friend H AbslHashValue(H hash_state, const absl::Cord& c) {
819     absl::optional<absl::string_view> maybe_flat = c.TryFlat();
820     if (maybe_flat.has_value()) {
821       return H::combine(std::move(hash_state), *maybe_flat);
822     }
823     return c.HashFragmented(std::move(hash_state));
824   }
825 
826   // Create a Cord with the contents of StringConstant<T>::value.
827   // No allocations will be done and no data will be copied.
828   // This is an INTERNAL API and subject to change or removal. This API can only
829   // be used by spelling absl::strings_internal::MakeStringConstant, which is
830   // also an internal API.
831   template <typename T>
832   // NOLINTNEXTLINE(google-explicit-constructor)
833   constexpr Cord(strings_internal::StringConstant<T>);
834 
835  private:
836   using CordRep = absl::cord_internal::CordRep;
837   using CordRepFlat = absl::cord_internal::CordRepFlat;
838   using CordzInfo = cord_internal::CordzInfo;
839   using CordzUpdateScope = cord_internal::CordzUpdateScope;
840   using CordzUpdateTracker = cord_internal::CordzUpdateTracker;
841   using InlineData = cord_internal::InlineData;
842   using MethodIdentifier = CordzUpdateTracker::MethodIdentifier;
843 
844   // Creates a cord instance with `method` representing the originating
845   // public API call causing the cord to be created.
846   explicit Cord(absl::string_view src, MethodIdentifier method);
847 
848   friend class CordTestPeer;
849   friend bool operator==(const Cord& lhs, const Cord& rhs);
850   friend bool operator==(const Cord& lhs, absl::string_view rhs);
851 
852   friend absl::Nullable<const CordzInfo*> GetCordzInfoForTesting(
853       const Cord& cord);
854 
855   // Calls the provided function once for each cord chunk, in order.  Unlike
856   // Chunks(), this API will not allocate memory.
857   void ForEachChunk(absl::FunctionRef<void(absl::string_view)>) const;
858 
859   // Allocates new contiguous storage for the contents of the cord. This is
860   // called by Flatten() when the cord was not already flat.
861   absl::string_view FlattenSlowPath();
862 
863   // Actual cord contents are hidden inside the following simple
864   // class so that we can isolate the bulk of cord.cc from changes
865   // to the representation.
866   //
867   // InlineRep holds either a tree pointer, or an array of kMaxInline bytes.
868   class InlineRep {
869    public:
870     static constexpr unsigned char kMaxInline = cord_internal::kMaxInline;
871     static_assert(kMaxInline >= sizeof(absl::cord_internal::CordRep*), "");
872 
InlineRep()873     constexpr InlineRep() : data_() {}
InlineRep(InlineData::DefaultInitType init)874     explicit InlineRep(InlineData::DefaultInitType init) : data_(init) {}
875     InlineRep(const InlineRep& src);
876     InlineRep(InlineRep&& src);
877     InlineRep& operator=(const InlineRep& src);
878     InlineRep& operator=(InlineRep&& src) noexcept;
879 
880     explicit constexpr InlineRep(absl::string_view sv,
881                                  absl::Nullable<CordRep*> rep);
882 
883     void Swap(absl::Nonnull<InlineRep*> rhs);
884     size_t size() const;
885     // Returns nullptr if holding pointer
886     absl::Nullable<const char*> data() const;
887     // Discards pointer, if any
888     void set_data(absl::Nonnull<const char*> data, size_t n);
889     absl::Nonnull<char*> set_data(size_t n);  // Write data to the result
890     // Returns nullptr if holding bytes
891     absl::Nullable<absl::cord_internal::CordRep*> tree() const;
892     absl::Nonnull<absl::cord_internal::CordRep*> as_tree() const;
893     absl::Nonnull<const char*> as_chars() const;
894     // Returns non-null iff was holding a pointer
895     absl::Nullable<absl::cord_internal::CordRep*> clear();
896     // Converts to pointer if necessary.
897     void reduce_size(size_t n);    // REQUIRES: holding data
898     void remove_prefix(size_t n);  // REQUIRES: holding data
899     void AppendArray(absl::string_view src, MethodIdentifier method);
900     absl::string_view FindFlatStartPiece() const;
901 
902     // Creates a CordRepFlat instance from the current inlined data with `extra'
903     // bytes of desired additional capacity.
904     absl::Nonnull<CordRepFlat*> MakeFlatWithExtraCapacity(size_t extra);
905 
906     // Sets the tree value for this instance. `rep` must not be null.
907     // Requires the current instance to hold a tree, and a lock to be held on
908     // any CordzInfo referenced by this instance. The latter is enforced through
909     // the CordzUpdateScope argument. If the current instance is sampled, then
910     // the CordzInfo instance is updated to reference the new `rep` value.
911     void SetTree(absl::Nonnull<CordRep*> rep, const CordzUpdateScope& scope);
912 
913     // Identical to SetTree(), except that `rep` is allowed to be null, in
914     // which case the current instance is reset to an empty value.
915     void SetTreeOrEmpty(absl::Nullable<CordRep*> rep,
916                         const CordzUpdateScope& scope);
917 
918     // Sets the tree value for this instance, and randomly samples this cord.
919     // This function disregards existing contents in `data_`, and should be
920     // called when a Cord is 'promoted' from an 'uninitialized' or 'inlined'
921     // value to a non-inlined (tree / ring) value.
922     void EmplaceTree(absl::Nonnull<CordRep*> rep, MethodIdentifier method);
923 
924     // Identical to EmplaceTree, except that it copies the parent stack from
925     // the provided `parent` data if the parent is sampled.
926     void EmplaceTree(absl::Nonnull<CordRep*> rep, const InlineData& parent,
927                      MethodIdentifier method);
928 
929     // Commits the change of a newly created, or updated `rep` root value into
930     // this cord. `old_rep` indicates the old (inlined or tree) value of the
931     // cord, and determines if the commit invokes SetTree() or EmplaceTree().
932     void CommitTree(absl::Nullable<const CordRep*> old_rep,
933                     absl::Nonnull<CordRep*> rep, const CordzUpdateScope& scope,
934                     MethodIdentifier method);
935 
936     void AppendTreeToInlined(absl::Nonnull<CordRep*> tree,
937                              MethodIdentifier method);
938     void AppendTreeToTree(absl::Nonnull<CordRep*> tree,
939                           MethodIdentifier method);
940     void AppendTree(absl::Nonnull<CordRep*> tree, MethodIdentifier method);
941     void PrependTreeToInlined(absl::Nonnull<CordRep*> tree,
942                               MethodIdentifier method);
943     void PrependTreeToTree(absl::Nonnull<CordRep*> tree,
944                            MethodIdentifier method);
945     void PrependTree(absl::Nonnull<CordRep*> tree, MethodIdentifier method);
946 
IsSame(const InlineRep & other)947     bool IsSame(const InlineRep& other) const { return data_ == other.data_; }
948 
CopyTo(absl::Nonnull<std::string * > dst)949     void CopyTo(absl::Nonnull<std::string*> dst) const {
950       // memcpy is much faster when operating on a known size. On most supported
951       // platforms, the small string optimization is large enough that resizing
952       // to 15 bytes does not cause a memory allocation.
953       absl::strings_internal::STLStringResizeUninitialized(dst, kMaxInline);
954       data_.copy_max_inline_to(&(*dst)[0]);
955       // erase is faster than resize because the logic for memory allocation is
956       // not needed.
957       dst->erase(inline_size());
958     }
959 
960     // Copies the inline contents into `dst`. Assumes the cord is not empty.
961     void CopyToArray(absl::Nonnull<char*> dst) const;
962 
is_tree()963     bool is_tree() const { return data_.is_tree(); }
964 
965     // Returns true if the Cord is being profiled by cordz.
is_profiled()966     bool is_profiled() const { return data_.is_tree() && data_.is_profiled(); }
967 
968     // Returns the available inlined capacity, or 0 if is_tree() == true.
remaining_inline_capacity()969     size_t remaining_inline_capacity() const {
970       return data_.is_tree() ? 0 : kMaxInline - data_.inline_size();
971     }
972 
973     // Returns the profiled CordzInfo, or nullptr if not sampled.
cordz_info()974     absl::Nullable<absl::cord_internal::CordzInfo*> cordz_info() const {
975       return data_.cordz_info();
976     }
977 
978     // Sets the profiled CordzInfo.
set_cordz_info(absl::Nonnull<cord_internal::CordzInfo * > cordz_info)979     void set_cordz_info(absl::Nonnull<cord_internal::CordzInfo*> cordz_info) {
980       assert(cordz_info != nullptr);
981       data_.set_cordz_info(cordz_info);
982     }
983 
984     // Resets the current cordz_info to null / empty.
clear_cordz_info()985     void clear_cordz_info() { data_.clear_cordz_info(); }
986 
987    private:
988     friend class Cord;
989 
990     void AssignSlow(const InlineRep& src);
991     // Unrefs the tree and stops profiling.
992     void UnrefTree();
993 
ResetToEmpty()994     void ResetToEmpty() { data_ = {}; }
995 
set_inline_size(size_t size)996     void set_inline_size(size_t size) { data_.set_inline_size(size); }
inline_size()997     size_t inline_size() const { return data_.inline_size(); }
998 
999     // Empty cords that carry a checksum have a CordRepCrc node with a null
1000     // child node. The code can avoid lots of special cases where it would
1001     // otherwise transition from tree to inline storage if we just remove the
1002     // CordRepCrc node before mutations. Must never be called inside a
1003     // CordzUpdateScope since it untracks the cordz info.
1004     void MaybeRemoveEmptyCrcNode();
1005 
1006     cord_internal::InlineData data_;
1007   };
1008   InlineRep contents_;
1009 
1010   // Helper for GetFlat() and TryFlat().
1011   static bool GetFlatAux(absl::Nonnull<absl::cord_internal::CordRep*> rep,
1012                          absl::Nonnull<absl::string_view*> fragment);
1013 
1014   // Helper for ForEachChunk().
1015   static void ForEachChunkAux(
1016       absl::Nonnull<absl::cord_internal::CordRep*> rep,
1017       absl::FunctionRef<void(absl::string_view)> callback);
1018 
1019   // The destructor for non-empty Cords.
1020   void DestroyCordSlow();
1021 
1022   // Out-of-line implementation of slower parts of logic.
1023   void CopyToArraySlowPath(absl::Nonnull<char*> dst) const;
1024   int CompareSlowPath(absl::string_view rhs, size_t compared_size,
1025                       size_t size_to_compare) const;
1026   int CompareSlowPath(const Cord& rhs, size_t compared_size,
1027                       size_t size_to_compare) const;
1028   bool EqualsImpl(absl::string_view rhs, size_t size_to_compare) const;
1029   bool EqualsImpl(const Cord& rhs, size_t size_to_compare) const;
1030   int CompareImpl(const Cord& rhs) const;
1031 
1032   template <typename ResultType, typename RHS>
1033   friend ResultType GenericCompare(const Cord& lhs, const RHS& rhs,
1034                                    size_t size_to_compare);
1035   static absl::string_view GetFirstChunk(const Cord& c);
1036   static absl::string_view GetFirstChunk(absl::string_view sv);
1037 
1038   // Returns a new reference to contents_.tree(), or steals an existing
1039   // reference if called on an rvalue.
1040   absl::Nonnull<absl::cord_internal::CordRep*> TakeRep() const&;
1041   absl::Nonnull<absl::cord_internal::CordRep*> TakeRep() &&;
1042 
1043   // Helper for Append().
1044   template <typename C>
1045   void AppendImpl(C&& src);
1046 
1047   // Appends / Prepends `src` to this instance, using precise sizing.
1048   // This method does explicitly not attempt to use any spare capacity
1049   // in any pending last added private owned flat.
1050   // Requires `src` to be <= kMaxFlatLength.
1051   void AppendPrecise(absl::string_view src, MethodIdentifier method);
1052   void PrependPrecise(absl::string_view src, MethodIdentifier method);
1053 
1054   CordBuffer GetAppendBufferSlowPath(size_t block_size, size_t capacity,
1055                                      size_t min_capacity);
1056 
1057   // Prepends the provided data to this instance. `method` contains the public
1058   // API method for this action which is tracked for Cordz sampling purposes.
1059   void PrependArray(absl::string_view src, MethodIdentifier method);
1060 
1061   // Assigns the value in 'src' to this instance, 'stealing' its contents.
1062   // Requires src.length() > kMaxBytesToCopy.
1063   Cord& AssignLargeString(std::string&& src);
1064 
1065   // Helper for AbslHashValue().
1066   template <typename H>
HashFragmented(H hash_state)1067   H HashFragmented(H hash_state) const {
1068     typename H::AbslInternalPiecewiseCombiner combiner;
1069     ForEachChunk([&combiner, &hash_state](absl::string_view chunk) {
1070       hash_state = combiner.add_buffer(std::move(hash_state), chunk.data(),
1071                                        chunk.size());
1072     });
1073     return H::combine(combiner.finalize(std::move(hash_state)), size());
1074   }
1075 
1076   friend class CrcCord;
1077   void SetCrcCordState(crc_internal::CrcCordState state);
1078   absl::Nullable<const crc_internal::CrcCordState*> MaybeGetCrcCordState()
1079       const;
1080 
1081   CharIterator FindImpl(CharIterator it, absl::string_view needle) const;
1082 
1083   void CopyToArrayImpl(absl::Nonnull<char*> dst) const;
1084 };
1085 
1086 ABSL_NAMESPACE_END
1087 }  // namespace absl
1088 
1089 namespace absl {
1090 ABSL_NAMESPACE_BEGIN
1091 
1092 // allow a Cord to be logged
1093 extern std::ostream& operator<<(std::ostream& out, const Cord& cord);
1094 
1095 // ------------------------------------------------------------------
1096 // Internal details follow.  Clients should ignore.
1097 
1098 namespace cord_internal {
1099 
1100 // Does non-template-specific `CordRepExternal` initialization.
1101 // Requires `data` to be non-empty.
1102 void InitializeCordRepExternal(absl::string_view data,
1103                                absl::Nonnull<CordRepExternal*> rep);
1104 
1105 // Creates a new `CordRep` that owns `data` and `releaser` and returns a pointer
1106 // to it. Requires `data` to be non-empty.
1107 template <typename Releaser>
1108 // NOLINTNEXTLINE - suppress clang-tidy raw pointer return.
NewExternalRep(absl::string_view data,Releaser && releaser)1109 absl::Nonnull<CordRep*> NewExternalRep(absl::string_view data,
1110                                        Releaser&& releaser) {
1111   assert(!data.empty());
1112   using ReleaserType = absl::decay_t<Releaser>;
1113   CordRepExternal* rep = new CordRepExternalImpl<ReleaserType>(
1114       std::forward<Releaser>(releaser), 0);
1115   InitializeCordRepExternal(data, rep);
1116   return rep;
1117 }
1118 
1119 // Overload for function reference types that dispatches using a function
1120 // pointer because there are no `alignof()` or `sizeof()` a function reference.
1121 // NOLINTNEXTLINE - suppress clang-tidy raw pointer return.
NewExternalRep(absl::string_view data,void (& releaser)(absl::string_view))1122 inline absl::Nonnull<CordRep*> NewExternalRep(
1123     absl::string_view data, void (&releaser)(absl::string_view)) {
1124   return NewExternalRep(data, &releaser);
1125 }
1126 
1127 }  // namespace cord_internal
1128 
1129 template <typename Releaser>
MakeCordFromExternal(absl::string_view data,Releaser && releaser)1130 Cord MakeCordFromExternal(absl::string_view data, Releaser&& releaser) {
1131   Cord cord;
1132   if (ABSL_PREDICT_TRUE(!data.empty())) {
1133     cord.contents_.EmplaceTree(::absl::cord_internal::NewExternalRep(
1134                                    data, std::forward<Releaser>(releaser)),
1135                                Cord::MethodIdentifier::kMakeCordFromExternal);
1136   } else {
1137     using ReleaserType = absl::decay_t<Releaser>;
1138     cord_internal::InvokeReleaser(
1139         cord_internal::Rank1{}, ReleaserType(std::forward<Releaser>(releaser)),
1140         data);
1141   }
1142   return cord;
1143 }
1144 
InlineRep(absl::string_view sv,absl::Nullable<CordRep * > rep)1145 constexpr Cord::InlineRep::InlineRep(absl::string_view sv,
1146                                      absl::Nullable<CordRep*> rep)
1147     : data_(sv, rep) {}
1148 
InlineRep(const Cord::InlineRep & src)1149 inline Cord::InlineRep::InlineRep(const Cord::InlineRep& src)
1150     : data_(InlineData::kDefaultInit) {
1151   if (CordRep* tree = src.tree()) {
1152     EmplaceTree(CordRep::Ref(tree), src.data_,
1153                 CordzUpdateTracker::kConstructorCord);
1154   } else {
1155     data_ = src.data_;
1156   }
1157 }
1158 
InlineRep(Cord::InlineRep && src)1159 inline Cord::InlineRep::InlineRep(Cord::InlineRep&& src) : data_(src.data_) {
1160   src.ResetToEmpty();
1161 }
1162 
1163 inline Cord::InlineRep& Cord::InlineRep::operator=(const Cord::InlineRep& src) {
1164   if (this == &src) {
1165     return *this;
1166   }
1167   if (!is_tree() && !src.is_tree()) {
1168     data_ = src.data_;
1169     return *this;
1170   }
1171   AssignSlow(src);
1172   return *this;
1173 }
1174 
1175 inline Cord::InlineRep& Cord::InlineRep::operator=(
1176     Cord::InlineRep&& src) noexcept {
1177   if (is_tree()) {
1178     UnrefTree();
1179   }
1180   data_ = src.data_;
1181   src.ResetToEmpty();
1182   return *this;
1183 }
1184 
Swap(absl::Nonnull<Cord::InlineRep * > rhs)1185 inline void Cord::InlineRep::Swap(absl::Nonnull<Cord::InlineRep*> rhs) {
1186   if (rhs == this) {
1187     return;
1188   }
1189   using std::swap;
1190   swap(data_, rhs->data_);
1191 }
1192 
data()1193 inline absl::Nullable<const char*> Cord::InlineRep::data() const {
1194   return is_tree() ? nullptr : data_.as_chars();
1195 }
1196 
as_chars()1197 inline absl::Nonnull<const char*> Cord::InlineRep::as_chars() const {
1198   assert(!data_.is_tree());
1199   return data_.as_chars();
1200 }
1201 
as_tree()1202 inline absl::Nonnull<absl::cord_internal::CordRep*> Cord::InlineRep::as_tree()
1203     const {
1204   assert(data_.is_tree());
1205   return data_.as_tree();
1206 }
1207 
tree()1208 inline absl::Nullable<absl::cord_internal::CordRep*> Cord::InlineRep::tree()
1209     const {
1210   if (is_tree()) {
1211     return as_tree();
1212   } else {
1213     return nullptr;
1214   }
1215 }
1216 
size()1217 inline size_t Cord::InlineRep::size() const {
1218   return is_tree() ? as_tree()->length : inline_size();
1219 }
1220 
1221 inline absl::Nonnull<cord_internal::CordRepFlat*>
MakeFlatWithExtraCapacity(size_t extra)1222 Cord::InlineRep::MakeFlatWithExtraCapacity(size_t extra) {
1223   static_assert(cord_internal::kMinFlatLength >= sizeof(data_), "");
1224   size_t len = data_.inline_size();
1225   auto* result = CordRepFlat::New(len + extra);
1226   result->length = len;
1227   data_.copy_max_inline_to(result->Data());
1228   return result;
1229 }
1230 
EmplaceTree(absl::Nonnull<CordRep * > rep,MethodIdentifier method)1231 inline void Cord::InlineRep::EmplaceTree(absl::Nonnull<CordRep*> rep,
1232                                          MethodIdentifier method) {
1233   assert(rep);
1234   data_.make_tree(rep);
1235   CordzInfo::MaybeTrackCord(data_, method);
1236 }
1237 
EmplaceTree(absl::Nonnull<CordRep * > rep,const InlineData & parent,MethodIdentifier method)1238 inline void Cord::InlineRep::EmplaceTree(absl::Nonnull<CordRep*> rep,
1239                                          const InlineData& parent,
1240                                          MethodIdentifier method) {
1241   data_.make_tree(rep);
1242   CordzInfo::MaybeTrackCord(data_, parent, method);
1243 }
1244 
SetTree(absl::Nonnull<CordRep * > rep,const CordzUpdateScope & scope)1245 inline void Cord::InlineRep::SetTree(absl::Nonnull<CordRep*> rep,
1246                                      const CordzUpdateScope& scope) {
1247   assert(rep);
1248   assert(data_.is_tree());
1249   data_.set_tree(rep);
1250   scope.SetCordRep(rep);
1251 }
1252 
SetTreeOrEmpty(absl::Nullable<CordRep * > rep,const CordzUpdateScope & scope)1253 inline void Cord::InlineRep::SetTreeOrEmpty(absl::Nullable<CordRep*> rep,
1254                                             const CordzUpdateScope& scope) {
1255   assert(data_.is_tree());
1256   if (rep) {
1257     data_.set_tree(rep);
1258   } else {
1259     data_ = {};
1260   }
1261   scope.SetCordRep(rep);
1262 }
1263 
CommitTree(absl::Nullable<const CordRep * > old_rep,absl::Nonnull<CordRep * > rep,const CordzUpdateScope & scope,MethodIdentifier method)1264 inline void Cord::InlineRep::CommitTree(absl::Nullable<const CordRep*> old_rep,
1265                                         absl::Nonnull<CordRep*> rep,
1266                                         const CordzUpdateScope& scope,
1267                                         MethodIdentifier method) {
1268   if (old_rep) {
1269     SetTree(rep, scope);
1270   } else {
1271     EmplaceTree(rep, method);
1272   }
1273 }
1274 
clear()1275 inline absl::Nullable<absl::cord_internal::CordRep*> Cord::InlineRep::clear() {
1276   if (is_tree()) {
1277     CordzInfo::MaybeUntrackCord(cordz_info());
1278   }
1279   absl::cord_internal::CordRep* result = tree();
1280   ResetToEmpty();
1281   return result;
1282 }
1283 
CopyToArray(absl::Nonnull<char * > dst)1284 inline void Cord::InlineRep::CopyToArray(absl::Nonnull<char*> dst) const {
1285   assert(!is_tree());
1286   size_t n = inline_size();
1287   assert(n != 0);
1288   cord_internal::SmallMemmove(dst, data_.as_chars(), n);
1289 }
1290 
MaybeRemoveEmptyCrcNode()1291 inline void Cord::InlineRep::MaybeRemoveEmptyCrcNode() {
1292   CordRep* rep = tree();
1293   if (rep == nullptr || ABSL_PREDICT_TRUE(rep->length > 0)) {
1294     return;
1295   }
1296   assert(rep->IsCrc());
1297   assert(rep->crc()->child == nullptr);
1298   CordzInfo::MaybeUntrackCord(cordz_info());
1299   CordRep::Unref(rep);
1300   ResetToEmpty();
1301 }
1302 
Cord()1303 constexpr inline Cord::Cord() noexcept {}
1304 
Cord(absl::string_view src)1305 inline Cord::Cord(absl::string_view src)
1306     : Cord(src, CordzUpdateTracker::kConstructorString) {}
1307 
1308 template <typename T>
Cord(strings_internal::StringConstant<T>)1309 constexpr Cord::Cord(strings_internal::StringConstant<T>)
1310     : contents_(strings_internal::StringConstant<T>::value,
1311                 strings_internal::StringConstant<T>::value.size() <=
1312                         cord_internal::kMaxInline
1313                     ? nullptr
1314                     : &cord_internal::ConstInitExternalStorage<
1315                           strings_internal::StringConstant<T>>::value) {}
1316 
1317 inline Cord& Cord::operator=(const Cord& x) {
1318   contents_ = x.contents_;
1319   return *this;
1320 }
1321 
1322 template <typename T, Cord::EnableIfString<T>>
1323 Cord& Cord::operator=(T&& src) {
1324   if (src.size() <= cord_internal::kMaxBytesToCopy) {
1325     return operator=(absl::string_view(src));
1326   } else {
1327     return AssignLargeString(std::forward<T>(src));
1328   }
1329 }
1330 
Cord(const Cord & src)1331 inline Cord::Cord(const Cord& src) : contents_(src.contents_) {}
1332 
Cord(Cord && src)1333 inline Cord::Cord(Cord&& src) noexcept : contents_(std::move(src.contents_)) {}
1334 
swap(Cord & other)1335 inline void Cord::swap(Cord& other) noexcept {
1336   contents_.Swap(&other.contents_);
1337 }
1338 
1339 inline Cord& Cord::operator=(Cord&& x) noexcept {
1340   contents_ = std::move(x.contents_);
1341   return *this;
1342 }
1343 
1344 extern template Cord::Cord(std::string&& src);
1345 
size()1346 inline size_t Cord::size() const {
1347   // Length is 1st field in str.rep_
1348   return contents_.size();
1349 }
1350 
empty()1351 inline bool Cord::empty() const { return size() == 0; }
1352 
EstimatedMemoryUsage(CordMemoryAccounting accounting_method)1353 inline size_t Cord::EstimatedMemoryUsage(
1354     CordMemoryAccounting accounting_method) const {
1355   size_t result = sizeof(Cord);
1356   if (const absl::cord_internal::CordRep* rep = contents_.tree()) {
1357     switch (accounting_method) {
1358       case CordMemoryAccounting::kFairShare:
1359         result += cord_internal::GetEstimatedFairShareMemoryUsage(rep);
1360         break;
1361       case CordMemoryAccounting::kTotalMorePrecise:
1362         result += cord_internal::GetMorePreciseMemoryUsage(rep);
1363         break;
1364       case CordMemoryAccounting::kTotal:
1365         result += cord_internal::GetEstimatedMemoryUsage(rep);
1366         break;
1367     }
1368   }
1369   return result;
1370 }
1371 
TryFlat()1372 inline absl::optional<absl::string_view> Cord::TryFlat() const
1373     ABSL_ATTRIBUTE_LIFETIME_BOUND {
1374   absl::cord_internal::CordRep* rep = contents_.tree();
1375   if (rep == nullptr) {
1376     return absl::string_view(contents_.data(), contents_.size());
1377   }
1378   absl::string_view fragment;
1379   if (GetFlatAux(rep, &fragment)) {
1380     return fragment;
1381   }
1382   return absl::nullopt;
1383 }
1384 
Flatten()1385 inline absl::string_view Cord::Flatten() ABSL_ATTRIBUTE_LIFETIME_BOUND {
1386   absl::cord_internal::CordRep* rep = contents_.tree();
1387   if (rep == nullptr) {
1388     return absl::string_view(contents_.data(), contents_.size());
1389   } else {
1390     absl::string_view already_flat_contents;
1391     if (GetFlatAux(rep, &already_flat_contents)) {
1392       return already_flat_contents;
1393     }
1394   }
1395   return FlattenSlowPath();
1396 }
1397 
Append(absl::string_view src)1398 inline void Cord::Append(absl::string_view src) {
1399   contents_.AppendArray(src, CordzUpdateTracker::kAppendString);
1400 }
1401 
Prepend(absl::string_view src)1402 inline void Cord::Prepend(absl::string_view src) {
1403   PrependArray(src, CordzUpdateTracker::kPrependString);
1404 }
1405 
Append(CordBuffer buffer)1406 inline void Cord::Append(CordBuffer buffer) {
1407   if (ABSL_PREDICT_FALSE(buffer.length() == 0)) return;
1408   contents_.MaybeRemoveEmptyCrcNode();
1409   absl::string_view short_value;
1410   if (CordRep* rep = buffer.ConsumeValue(short_value)) {
1411     contents_.AppendTree(rep, CordzUpdateTracker::kAppendCordBuffer);
1412   } else {
1413     AppendPrecise(short_value, CordzUpdateTracker::kAppendCordBuffer);
1414   }
1415 }
1416 
Prepend(CordBuffer buffer)1417 inline void Cord::Prepend(CordBuffer buffer) {
1418   if (ABSL_PREDICT_FALSE(buffer.length() == 0)) return;
1419   contents_.MaybeRemoveEmptyCrcNode();
1420   absl::string_view short_value;
1421   if (CordRep* rep = buffer.ConsumeValue(short_value)) {
1422     contents_.PrependTree(rep, CordzUpdateTracker::kPrependCordBuffer);
1423   } else {
1424     PrependPrecise(short_value, CordzUpdateTracker::kPrependCordBuffer);
1425   }
1426 }
1427 
GetAppendBuffer(size_t capacity,size_t min_capacity)1428 inline CordBuffer Cord::GetAppendBuffer(size_t capacity, size_t min_capacity) {
1429   if (empty()) return CordBuffer::CreateWithDefaultLimit(capacity);
1430   return GetAppendBufferSlowPath(0, capacity, min_capacity);
1431 }
1432 
GetCustomAppendBuffer(size_t block_size,size_t capacity,size_t min_capacity)1433 inline CordBuffer Cord::GetCustomAppendBuffer(size_t block_size,
1434                                               size_t capacity,
1435                                               size_t min_capacity) {
1436   if (empty()) {
1437     return block_size ? CordBuffer::CreateWithCustomLimit(block_size, capacity)
1438                       : CordBuffer::CreateWithDefaultLimit(capacity);
1439   }
1440   return GetAppendBufferSlowPath(block_size, capacity, min_capacity);
1441 }
1442 
1443 extern template void Cord::Append(std::string&& src);
1444 extern template void Cord::Prepend(std::string&& src);
1445 
Compare(const Cord & rhs)1446 inline int Cord::Compare(const Cord& rhs) const {
1447   if (!contents_.is_tree() && !rhs.contents_.is_tree()) {
1448     return contents_.data_.Compare(rhs.contents_.data_);
1449   }
1450 
1451   return CompareImpl(rhs);
1452 }
1453 
1454 // Does 'this' cord start/end with rhs
StartsWith(const Cord & rhs)1455 inline bool Cord::StartsWith(const Cord& rhs) const {
1456   if (contents_.IsSame(rhs.contents_)) return true;
1457   size_t rhs_size = rhs.size();
1458   if (size() < rhs_size) return false;
1459   return EqualsImpl(rhs, rhs_size);
1460 }
1461 
StartsWith(absl::string_view rhs)1462 inline bool Cord::StartsWith(absl::string_view rhs) const {
1463   size_t rhs_size = rhs.size();
1464   if (size() < rhs_size) return false;
1465   return EqualsImpl(rhs, rhs_size);
1466 }
1467 
CopyToArrayImpl(absl::Nonnull<char * > dst)1468 inline void Cord::CopyToArrayImpl(absl::Nonnull<char*> dst) const {
1469   if (!contents_.is_tree()) {
1470     if (!empty()) contents_.CopyToArray(dst);
1471   } else {
1472     CopyToArraySlowPath(dst);
1473   }
1474 }
1475 
InitTree(absl::Nonnull<cord_internal::CordRep * > tree)1476 inline void Cord::ChunkIterator::InitTree(
1477     absl::Nonnull<cord_internal::CordRep*> tree) {
1478   tree = cord_internal::SkipCrcNode(tree);
1479   if (tree->tag == cord_internal::BTREE) {
1480     current_chunk_ = btree_reader_.Init(tree->btree());
1481   } else {
1482     current_leaf_ = tree;
1483     current_chunk_ = cord_internal::EdgeData(tree);
1484   }
1485 }
1486 
ChunkIterator(absl::Nonnull<cord_internal::CordRep * > tree)1487 inline Cord::ChunkIterator::ChunkIterator(
1488     absl::Nonnull<cord_internal::CordRep*> tree) {
1489   bytes_remaining_ = tree->length;
1490   InitTree(tree);
1491 }
1492 
ChunkIterator(absl::Nonnull<const Cord * > cord)1493 inline Cord::ChunkIterator::ChunkIterator(absl::Nonnull<const Cord*> cord) {
1494   if (CordRep* tree = cord->contents_.tree()) {
1495     bytes_remaining_ = tree->length;
1496     if (ABSL_PREDICT_TRUE(bytes_remaining_ != 0)) {
1497       InitTree(tree);
1498     } else {
1499       current_chunk_ = {};
1500     }
1501   } else {
1502     bytes_remaining_ = cord->contents_.inline_size();
1503     current_chunk_ = {cord->contents_.data(), bytes_remaining_};
1504   }
1505 }
1506 
AdvanceBtree()1507 inline Cord::ChunkIterator& Cord::ChunkIterator::AdvanceBtree() {
1508   current_chunk_ = btree_reader_.Next();
1509   return *this;
1510 }
1511 
AdvanceBytesBtree(size_t n)1512 inline void Cord::ChunkIterator::AdvanceBytesBtree(size_t n) {
1513   assert(n >= current_chunk_.size());
1514   bytes_remaining_ -= n;
1515   if (bytes_remaining_) {
1516     if (n == current_chunk_.size()) {
1517       current_chunk_ = btree_reader_.Next();
1518     } else {
1519       size_t offset = btree_reader_.length() - bytes_remaining_;
1520       current_chunk_ = btree_reader_.Seek(offset);
1521     }
1522   } else {
1523     current_chunk_ = {};
1524   }
1525 }
1526 
1527 inline Cord::ChunkIterator& Cord::ChunkIterator::operator++() {
1528   ABSL_HARDENING_ASSERT(bytes_remaining_ > 0 &&
1529                         "Attempted to iterate past `end()`");
1530   assert(bytes_remaining_ >= current_chunk_.size());
1531   bytes_remaining_ -= current_chunk_.size();
1532   if (bytes_remaining_ > 0) {
1533     if (btree_reader_) {
1534       return AdvanceBtree();
1535     } else {
1536       assert(!current_chunk_.empty());  // Called on invalid iterator.
1537     }
1538     current_chunk_ = {};
1539   }
1540   return *this;
1541 }
1542 
1543 inline Cord::ChunkIterator Cord::ChunkIterator::operator++(int) {
1544   ChunkIterator tmp(*this);
1545   operator++();
1546   return tmp;
1547 }
1548 
1549 inline bool Cord::ChunkIterator::operator==(const ChunkIterator& other) const {
1550   return bytes_remaining_ == other.bytes_remaining_;
1551 }
1552 
1553 inline bool Cord::ChunkIterator::operator!=(const ChunkIterator& other) const {
1554   return !(*this == other);
1555 }
1556 
1557 inline Cord::ChunkIterator::reference Cord::ChunkIterator::operator*() const {
1558   ABSL_HARDENING_ASSERT(bytes_remaining_ != 0);
1559   return current_chunk_;
1560 }
1561 
1562 inline Cord::ChunkIterator::pointer Cord::ChunkIterator::operator->() const {
1563   ABSL_HARDENING_ASSERT(bytes_remaining_ != 0);
1564   return &current_chunk_;
1565 }
1566 
RemoveChunkPrefix(size_t n)1567 inline void Cord::ChunkIterator::RemoveChunkPrefix(size_t n) {
1568   assert(n < current_chunk_.size());
1569   current_chunk_.remove_prefix(n);
1570   bytes_remaining_ -= n;
1571 }
1572 
AdvanceBytes(size_t n)1573 inline void Cord::ChunkIterator::AdvanceBytes(size_t n) {
1574   assert(bytes_remaining_ >= n);
1575   if (ABSL_PREDICT_TRUE(n < current_chunk_.size())) {
1576     RemoveChunkPrefix(n);
1577   } else if (n != 0) {
1578     if (btree_reader_) {
1579       AdvanceBytesBtree(n);
1580     } else {
1581       bytes_remaining_ = 0;
1582     }
1583   }
1584 }
1585 
chunk_begin()1586 inline Cord::ChunkIterator Cord::chunk_begin() const {
1587   return ChunkIterator(this);
1588 }
1589 
chunk_end()1590 inline Cord::ChunkIterator Cord::chunk_end() const { return ChunkIterator(); }
1591 
begin()1592 inline Cord::ChunkIterator Cord::ChunkRange::begin() const {
1593   return cord_->chunk_begin();
1594 }
1595 
end()1596 inline Cord::ChunkIterator Cord::ChunkRange::end() const {
1597   return cord_->chunk_end();
1598 }
1599 
Chunks()1600 inline Cord::ChunkRange Cord::Chunks() const { return ChunkRange(this); }
1601 
1602 inline Cord::CharIterator& Cord::CharIterator::operator++() {
1603   if (ABSL_PREDICT_TRUE(chunk_iterator_->size() > 1)) {
1604     chunk_iterator_.RemoveChunkPrefix(1);
1605   } else {
1606     ++chunk_iterator_;
1607   }
1608   return *this;
1609 }
1610 
1611 inline Cord::CharIterator Cord::CharIterator::operator++(int) {
1612   CharIterator tmp(*this);
1613   operator++();
1614   return tmp;
1615 }
1616 
1617 inline bool Cord::CharIterator::operator==(const CharIterator& other) const {
1618   return chunk_iterator_ == other.chunk_iterator_;
1619 }
1620 
1621 inline bool Cord::CharIterator::operator!=(const CharIterator& other) const {
1622   return !(*this == other);
1623 }
1624 
1625 inline Cord::CharIterator::reference Cord::CharIterator::operator*() const {
1626   return *chunk_iterator_->data();
1627 }
1628 
1629 inline Cord::CharIterator::pointer Cord::CharIterator::operator->() const {
1630   return chunk_iterator_->data();
1631 }
1632 
AdvanceAndRead(absl::Nonnull<CharIterator * > it,size_t n_bytes)1633 inline Cord Cord::AdvanceAndRead(absl::Nonnull<CharIterator*> it,
1634                                  size_t n_bytes) {
1635   assert(it != nullptr);
1636   return it->chunk_iterator_.AdvanceAndReadBytes(n_bytes);
1637 }
1638 
Advance(absl::Nonnull<CharIterator * > it,size_t n_bytes)1639 inline void Cord::Advance(absl::Nonnull<CharIterator*> it, size_t n_bytes) {
1640   assert(it != nullptr);
1641   it->chunk_iterator_.AdvanceBytes(n_bytes);
1642 }
1643 
ChunkRemaining(const CharIterator & it)1644 inline absl::string_view Cord::ChunkRemaining(const CharIterator& it) {
1645   return *it.chunk_iterator_;
1646 }
1647 
char_begin()1648 inline Cord::CharIterator Cord::char_begin() const {
1649   return CharIterator(this);
1650 }
1651 
char_end()1652 inline Cord::CharIterator Cord::char_end() const { return CharIterator(); }
1653 
begin()1654 inline Cord::CharIterator Cord::CharRange::begin() const {
1655   return cord_->char_begin();
1656 }
1657 
end()1658 inline Cord::CharIterator Cord::CharRange::end() const {
1659   return cord_->char_end();
1660 }
1661 
Chars()1662 inline Cord::CharRange Cord::Chars() const { return CharRange(this); }
1663 
ForEachChunk(absl::FunctionRef<void (absl::string_view)> callback)1664 inline void Cord::ForEachChunk(
1665     absl::FunctionRef<void(absl::string_view)> callback) const {
1666   absl::cord_internal::CordRep* rep = contents_.tree();
1667   if (rep == nullptr) {
1668     callback(absl::string_view(contents_.data(), contents_.size()));
1669   } else {
1670     ForEachChunkAux(rep, callback);
1671   }
1672 }
1673 
1674 // Nonmember Cord-to-Cord relational operators.
1675 inline bool operator==(const Cord& lhs, const Cord& rhs) {
1676   if (lhs.contents_.IsSame(rhs.contents_)) return true;
1677   size_t rhs_size = rhs.size();
1678   if (lhs.size() != rhs_size) return false;
1679   return lhs.EqualsImpl(rhs, rhs_size);
1680 }
1681 
1682 inline bool operator!=(const Cord& x, const Cord& y) { return !(x == y); }
1683 inline bool operator<(const Cord& x, const Cord& y) { return x.Compare(y) < 0; }
1684 inline bool operator>(const Cord& x, const Cord& y) { return x.Compare(y) > 0; }
1685 inline bool operator<=(const Cord& x, const Cord& y) {
1686   return x.Compare(y) <= 0;
1687 }
1688 inline bool operator>=(const Cord& x, const Cord& y) {
1689   return x.Compare(y) >= 0;
1690 }
1691 
1692 // Nonmember Cord-to-absl::string_view relational operators.
1693 //
1694 // Due to implicit conversions, these also enable comparisons of Cord with
1695 // std::string and const char*.
1696 inline bool operator==(const Cord& lhs, absl::string_view rhs) {
1697   size_t lhs_size = lhs.size();
1698   size_t rhs_size = rhs.size();
1699   if (lhs_size != rhs_size) return false;
1700   return lhs.EqualsImpl(rhs, rhs_size);
1701 }
1702 
1703 inline bool operator==(absl::string_view x, const Cord& y) { return y == x; }
1704 inline bool operator!=(const Cord& x, absl::string_view y) { return !(x == y); }
1705 inline bool operator!=(absl::string_view x, const Cord& y) { return !(x == y); }
1706 inline bool operator<(const Cord& x, absl::string_view y) {
1707   return x.Compare(y) < 0;
1708 }
1709 inline bool operator<(absl::string_view x, const Cord& y) {
1710   return y.Compare(x) > 0;
1711 }
1712 inline bool operator>(const Cord& x, absl::string_view y) { return y < x; }
1713 inline bool operator>(absl::string_view x, const Cord& y) { return y < x; }
1714 inline bool operator<=(const Cord& x, absl::string_view y) { return !(y < x); }
1715 inline bool operator<=(absl::string_view x, const Cord& y) { return !(y < x); }
1716 inline bool operator>=(const Cord& x, absl::string_view y) { return !(x < y); }
1717 inline bool operator>=(absl::string_view x, const Cord& y) { return !(x < y); }
1718 
1719 // Some internals exposed to test code.
1720 namespace strings_internal {
1721 class CordTestAccess {
1722  public:
1723   static size_t FlatOverhead();
1724   static size_t MaxFlatLength();
1725   static size_t SizeofCordRepExternal();
1726   static size_t SizeofCordRepSubstring();
1727   static size_t FlatTagToLength(uint8_t tag);
1728   static uint8_t LengthToTag(size_t s);
1729 };
1730 }  // namespace strings_internal
1731 ABSL_NAMESPACE_END
1732 }  // namespace absl
1733 
1734 #endif  // ABSL_STRINGS_CORD_H_
1735