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