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