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