Coverage Report

Created: 2026-05-12 06:37

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