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