Coverage Report

Created: 2026-07-16 06:43

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