Coverage Report

Created: 2026-02-26 07:14

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