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