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