blob: 7136f03449bcedd01a3ce89561d3cdd975c64e5e [file] [log] [blame]
Austin Schuhb4691e92020-12-31 12:37:18 -08001// 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." (Currently, this implementation is a
24// tree structure, though that implementation may change.)
25//
26// Because a Cord consists of these chunks, data can be added to or removed from
27// a Cord during its lifetime. Chunks may also be shared between Cords. Unlike a
28// `std::string`, a Cord can therefore accomodate data that changes over its
29// lifetime, though it's not quite "mutable"; it can change only in the
30// attachment, detachment, or rearrangement of chunks of its constituent data.
31//
32// A Cord provides some benefit over `std::string` under the following (albeit
33// narrow) circumstances:
34//
35// * Cord data is designed to grow and shrink over a Cord's lifetime. Cord
36// provides efficient insertions and deletions at the start and end of the
37// character sequences, avoiding copies in those cases. Static data should
38// generally be stored as strings.
39// * External memory consisting of string-like data can be directly added to
40// a Cord without requiring copies or allocations.
41// * Cord data may be shared and copied cheaply. Cord provides a copy-on-write
42// implementation and cheap sub-Cord operations. Copying a Cord is an O(1)
43// operation.
44//
45// As a consequence to the above, Cord data is generally large. Small data
46// should generally use strings, as construction of a Cord requires some
47// overhead. Small Cords (<= 15 bytes) are represented inline, but most small
48// Cords are expected to grow over their lifetimes.
49//
50// Note that because a Cord is made up of separate chunked data, random access
51// to character data within a Cord is slower than within a `std::string`.
52//
53// Thread Safety
54//
55// Cord has the same thread-safety properties as many other types like
56// std::string, std::vector<>, int, etc -- it is thread-compatible. In
57// particular, if threads do not call non-const methods, then it is safe to call
58// const methods without synchronization. Copying a Cord produces a new instance
59// that can be used concurrently with the original in arbitrary ways.
60
61#ifndef ABSL_STRINGS_CORD_H_
62#define ABSL_STRINGS_CORD_H_
63
64#include <algorithm>
65#include <cstddef>
66#include <cstdint>
67#include <cstring>
68#include <iosfwd>
69#include <iterator>
70#include <string>
71#include <type_traits>
72
73#include "absl/base/internal/endian.h"
74#include "absl/base/internal/per_thread_tls.h"
75#include "absl/base/macros.h"
76#include "absl/base/port.h"
77#include "absl/container/inlined_vector.h"
78#include "absl/functional/function_ref.h"
79#include "absl/meta/type_traits.h"
80#include "absl/strings/internal/cord_internal.h"
81#include "absl/strings/internal/resize_uninitialized.h"
82#include "absl/strings/internal/string_constant.h"
83#include "absl/strings/string_view.h"
84#include "absl/types/optional.h"
85
86namespace absl {
87ABSL_NAMESPACE_BEGIN
88class Cord;
89class CordTestPeer;
90template <typename Releaser>
91Cord MakeCordFromExternal(absl::string_view, Releaser&&);
92void CopyCordToString(const Cord& src, std::string* dst);
93
94// Cord
95//
96// A Cord is a sequence of characters, designed to be more efficient than a
97// `std::string` in certain circumstances: namely, large string data that needs
98// to change over its lifetime or shared, especially when such data is shared
99// across API boundaries.
100//
101// A Cord stores its character data in a structure that allows efficient prepend
102// and append operations. This makes a Cord useful for large string data sent
103// over in a wire format that may need to be prepended or appended at some point
104// during the data exchange (e.g. HTTP, protocol buffers). For example, a
105// Cord is useful for storing an HTTP request, and prepending an HTTP header to
106// such a request.
107//
108// Cords should not be used for storing general string data, however. They
109// require overhead to construct and are slower than strings for random access.
110//
111// The Cord API provides the following common API operations:
112//
113// * Create or assign Cords out of existing string data, memory, or other Cords
114// * Append and prepend data to an existing Cord
115// * Create new Sub-Cords from existing Cord data
116// * Swap Cord data and compare Cord equality
117// * Write out Cord data by constructing a `std::string`
118//
119// Additionally, the API provides iterator utilities to iterate through Cord
120// data via chunks or character bytes.
121//
122class Cord {
123 private:
124 template <typename T>
125 using EnableIfString =
126 absl::enable_if_t<std::is_same<T, std::string>::value, int>;
127
128 public:
129 // Cord::Cord() Constructors.
130
131 // Creates an empty Cord.
132 constexpr Cord() noexcept;
133
134 // Creates a Cord from an existing Cord. Cord is copyable and efficiently
135 // movable. The moved-from state is valid but unspecified.
136 Cord(const Cord& src);
137 Cord(Cord&& src) noexcept;
138 Cord& operator=(const Cord& x);
139 Cord& operator=(Cord&& x) noexcept;
140
141 // Creates a Cord from a `src` string. This constructor is marked explicit to
142 // prevent implicit Cord constructions from arguments convertible to an
143 // `absl::string_view`.
144 explicit Cord(absl::string_view src);
145 Cord& operator=(absl::string_view src);
146
147 // Creates a Cord from a `std::string&&` rvalue. These constructors are
148 // templated to avoid ambiguities for types that are convertible to both
149 // `absl::string_view` and `std::string`, such as `const char*`.
150 template <typename T, EnableIfString<T> = 0>
151 explicit Cord(T&& src);
152 template <typename T, EnableIfString<T> = 0>
153 Cord& operator=(T&& src);
154
155 // Cord::~Cord()
156 //
157 // Destructs the Cord.
158 ~Cord() {
159 if (contents_.is_tree()) DestroyCordSlow();
160 }
161
162 // MakeCordFromExternal()
163 //
164 // Creates a Cord that takes ownership of external string memory. The
165 // contents of `data` are not copied to the Cord; instead, the external
166 // memory is added to the Cord and reference-counted. This data may not be
167 // changed for the life of the Cord, though it may be prepended or appended
168 // to.
169 //
170 // `MakeCordFromExternal()` takes a callable "releaser" that is invoked when
171 // the reference count for `data` reaches zero. As noted above, this data must
172 // remain live until the releaser is invoked. The callable releaser also must:
173 //
174 // * be move constructible
175 // * support `void operator()(absl::string_view) const` or `void operator()`
176 //
177 // Example:
178 //
179 // Cord MakeCord(BlockPool* pool) {
180 // Block* block = pool->NewBlock();
181 // FillBlock(block);
182 // return absl::MakeCordFromExternal(
183 // block->ToStringView(),
184 // [pool, block](absl::string_view v) {
185 // pool->FreeBlock(block, v);
186 // });
187 // }
188 //
189 // WARNING: Because a Cord can be reference-counted, it's likely a bug if your
190 // releaser doesn't do anything. For example, consider the following:
191 //
192 // void Foo(const char* buffer, int len) {
193 // auto c = absl::MakeCordFromExternal(absl::string_view(buffer, len),
194 // [](absl::string_view) {});
195 //
196 // // BUG: If Bar() copies its cord for any reason, including keeping a
197 // // substring of it, the lifetime of buffer might be extended beyond
198 // // when Foo() returns.
199 // Bar(c);
200 // }
201 template <typename Releaser>
202 friend Cord MakeCordFromExternal(absl::string_view data, Releaser&& releaser);
203
204 // Cord::Clear()
205 //
206 // Releases the Cord data. Any nodes that share data with other Cords, if
207 // applicable, will have their reference counts reduced by 1.
208 void Clear();
209
210 // Cord::Append()
211 //
212 // Appends data to the Cord, which may come from another Cord or other string
213 // data.
214 void Append(const Cord& src);
215 void Append(Cord&& src);
216 void Append(absl::string_view src);
217 template <typename T, EnableIfString<T> = 0>
218 void Append(T&& src);
219
220 // Cord::Prepend()
221 //
222 // Prepends data to the Cord, which may come from another Cord or other string
223 // data.
224 void Prepend(const Cord& src);
225 void Prepend(absl::string_view src);
226 template <typename T, EnableIfString<T> = 0>
227 void Prepend(T&& src);
228
229 // Cord::RemovePrefix()
230 //
231 // Removes the first `n` bytes of a Cord.
232 void RemovePrefix(size_t n);
233 void RemoveSuffix(size_t n);
234
235 // Cord::Subcord()
236 //
237 // Returns a new Cord representing the subrange [pos, pos + new_size) of
238 // *this. If pos >= size(), the result is empty(). If
239 // (pos + new_size) >= size(), the result is the subrange [pos, size()).
240 Cord Subcord(size_t pos, size_t new_size) const;
241
242 // Cord::swap()
243 //
244 // Swaps the contents of the Cord with `other`.
245 void swap(Cord& other) noexcept;
246
247 // swap()
248 //
249 // Swaps the contents of two Cords.
250 friend void swap(Cord& x, Cord& y) noexcept {
251 x.swap(y);
252 }
253
254 // Cord::size()
255 //
256 // Returns the size of the Cord.
257 size_t size() const;
258
259 // Cord::empty()
260 //
261 // Determines whether the given Cord is empty, returning `true` is so.
262 bool empty() const;
263
264 // Cord::EstimatedMemoryUsage()
265 //
266 // Returns the *approximate* number of bytes held in full or in part by this
267 // Cord (which may not remain the same between invocations). Note that Cords
268 // that share memory could each be "charged" independently for the same shared
269 // memory.
270 size_t EstimatedMemoryUsage() const;
271
272 // Cord::Compare()
273 //
274 // Compares 'this' Cord with rhs. This function and its relatives treat Cords
275 // as sequences of unsigned bytes. The comparison is a straightforward
276 // lexicographic comparison. `Cord::Compare()` returns values as follows:
277 //
278 // -1 'this' Cord is smaller
279 // 0 two Cords are equal
280 // 1 'this' Cord is larger
281 int Compare(absl::string_view rhs) const;
282 int Compare(const Cord& rhs) const;
283
284 // Cord::StartsWith()
285 //
286 // Determines whether the Cord starts with the passed string data `rhs`.
287 bool StartsWith(const Cord& rhs) const;
288 bool StartsWith(absl::string_view rhs) const;
289
290 // Cord::EndsWidth()
291 //
292 // Determines whether the Cord ends with the passed string data `rhs`.
293 bool EndsWith(absl::string_view rhs) const;
294 bool EndsWith(const Cord& rhs) const;
295
296 // Cord::operator std::string()
297 //
298 // Converts a Cord into a `std::string()`. This operator is marked explicit to
299 // prevent unintended Cord usage in functions that take a string.
300 explicit operator std::string() const;
301
302 // CopyCordToString()
303 //
304 // Copies the contents of a `src` Cord into a `*dst` string.
305 //
306 // This function optimizes the case of reusing the destination string since it
307 // can reuse previously allocated capacity. However, this function does not
308 // guarantee that pointers previously returned by `dst->data()` remain valid
309 // even if `*dst` had enough capacity to hold `src`. If `*dst` is a new
310 // object, prefer to simply use the conversion operator to `std::string`.
311 friend void CopyCordToString(const Cord& src, std::string* dst);
312
313 class CharIterator;
314
315 //----------------------------------------------------------------------------
316 // Cord::ChunkIterator
317 //----------------------------------------------------------------------------
318 //
319 // A `Cord::ChunkIterator` allows iteration over the constituent chunks of its
320 // Cord. Such iteration allows you to perform non-const operatons on the data
321 // of a Cord without modifying it.
322 //
323 // Generally, you do not instantiate a `Cord::ChunkIterator` directly;
324 // instead, you create one implicitly through use of the `Cord::Chunks()`
325 // member function.
326 //
327 // The `Cord::ChunkIterator` has the following properties:
328 //
329 // * The iterator is invalidated after any non-const operation on the
330 // Cord object over which it iterates.
331 // * The `string_view` returned by dereferencing a valid, non-`end()`
332 // iterator is guaranteed to be non-empty.
333 // * Two `ChunkIterator` objects can be compared equal if and only if they
334 // remain valid and iterate over the same Cord.
335 // * The iterator in this case is a proxy iterator; the `string_view`
336 // returned by the iterator does not live inside the Cord, and its
337 // lifetime is limited to the lifetime of the iterator itself. To help
338 // prevent lifetime issues, `ChunkIterator::reference` is not a true
339 // reference type and is equivalent to `value_type`.
340 // * The iterator keeps state that can grow for Cords that contain many
341 // nodes and are imbalanced due to sharing. Prefer to pass this type by
342 // const reference instead of by value.
343 class ChunkIterator {
344 public:
345 using iterator_category = std::input_iterator_tag;
346 using value_type = absl::string_view;
347 using difference_type = ptrdiff_t;
348 using pointer = const value_type*;
349 using reference = value_type;
350
351 ChunkIterator() = default;
352
353 ChunkIterator& operator++();
354 ChunkIterator operator++(int);
355 bool operator==(const ChunkIterator& other) const;
356 bool operator!=(const ChunkIterator& other) const;
357 reference operator*() const;
358 pointer operator->() const;
359
360 friend class Cord;
361 friend class CharIterator;
362
363 private:
364 // Stack of right children of concat nodes that we have to visit.
365 // Keep this at the end of the structure to avoid cache-thrashing.
366 // TODO(jgm): Benchmark to see if there's a more optimal value than 47 for
367 // the inlined vector size (47 exists for backward compatibility).
368 using Stack = absl::InlinedVector<absl::cord_internal::CordRep*, 47>;
369
370 // Constructs a `begin()` iterator from `cord`.
371 explicit ChunkIterator(const Cord* cord);
372
373 // Removes `n` bytes from `current_chunk_`. Expects `n` to be smaller than
374 // `current_chunk_.size()`.
375 void RemoveChunkPrefix(size_t n);
376 Cord AdvanceAndReadBytes(size_t n);
377 void AdvanceBytes(size_t n);
378
379 // Stack specific operator++
380 ChunkIterator& AdvanceStack();
381
382 // Iterates `n` bytes, where `n` is expected to be greater than or equal to
383 // `current_chunk_.size()`.
384 void AdvanceBytesSlowPath(size_t n);
385
386 // A view into bytes of the current `CordRep`. It may only be a view to a
387 // suffix of bytes if this is being used by `CharIterator`.
388 absl::string_view current_chunk_;
389 // The current leaf, or `nullptr` if the iterator points to short data.
390 // If the current chunk is a substring node, current_leaf_ points to the
391 // underlying flat or external node.
392 absl::cord_internal::CordRep* current_leaf_ = nullptr;
393 // The number of bytes left in the `Cord` over which we are iterating.
394 size_t bytes_remaining_ = 0;
395 // See 'Stack' alias definition.
396 Stack stack_of_right_children_;
397 };
398
399 // Cord::ChunkIterator::chunk_begin()
400 //
401 // Returns an iterator to the first chunk of the `Cord`.
402 //
403 // Generally, prefer using `Cord::Chunks()` within a range-based for loop for
404 // iterating over the chunks of a Cord. This method may be useful for getting
405 // a `ChunkIterator` where range-based for-loops are not useful.
406 //
407 // Example:
408 //
409 // absl::Cord::ChunkIterator FindAsChunk(const absl::Cord& c,
410 // absl::string_view s) {
411 // return std::find(c.chunk_begin(), c.chunk_end(), s);
412 // }
413 ChunkIterator chunk_begin() const;
414
415 // Cord::ChunkItertator::chunk_end()
416 //
417 // Returns an iterator one increment past the last chunk of the `Cord`.
418 //
419 // Generally, prefer using `Cord::Chunks()` within a range-based for loop for
420 // iterating over the chunks of a Cord. This method may be useful for getting
421 // a `ChunkIterator` where range-based for-loops may not be available.
422 ChunkIterator chunk_end() const;
423
424 //----------------------------------------------------------------------------
425 // Cord::ChunkIterator::ChunkRange
426 //----------------------------------------------------------------------------
427 //
428 // `ChunkRange` is a helper class for iterating over the chunks of the `Cord`,
429 // producing an iterator which can be used within a range-based for loop.
430 // Construction of a `ChunkRange` will return an iterator pointing to the
431 // first chunk of the Cord. Generally, do not construct a `ChunkRange`
432 // directly; instead, prefer to use the `Cord::Chunks()` method.
433 //
434 // Implementation note: `ChunkRange` is simply a convenience wrapper over
435 // `Cord::chunk_begin()` and `Cord::chunk_end()`.
436 class ChunkRange {
437 public:
438 explicit ChunkRange(const Cord* cord) : cord_(cord) {}
439
440 ChunkIterator begin() const;
441 ChunkIterator end() const;
442
443 private:
444 const Cord* cord_;
445 };
446
447 // Cord::Chunks()
448 //
449 // Returns a `Cord::ChunkIterator::ChunkRange` for iterating over the chunks
450 // of a `Cord` with a range-based for-loop. For most iteration tasks on a
451 // Cord, use `Cord::Chunks()` to retrieve this iterator.
452 //
453 // Example:
454 //
455 // void ProcessChunks(const Cord& cord) {
456 // for (absl::string_view chunk : cord.Chunks()) { ... }
457 // }
458 //
459 // Note that the ordinary caveats of temporary lifetime extension apply:
460 //
461 // void Process() {
462 // for (absl::string_view chunk : CordFactory().Chunks()) {
463 // // The temporary Cord returned by CordFactory has been destroyed!
464 // }
465 // }
466 ChunkRange Chunks() const;
467
468 //----------------------------------------------------------------------------
469 // Cord::CharIterator
470 //----------------------------------------------------------------------------
471 //
472 // A `Cord::CharIterator` allows iteration over the constituent characters of
473 // a `Cord`.
474 //
475 // Generally, you do not instantiate a `Cord::CharIterator` directly; instead,
476 // you create one implicitly through use of the `Cord::Chars()` member
477 // function.
478 //
479 // A `Cord::CharIterator` has the following properties:
480 //
481 // * The iterator is invalidated after any non-const operation on the
482 // Cord object over which it iterates.
483 // * Two `CharIterator` objects can be compared equal if and only if they
484 // remain valid and iterate over the same Cord.
485 // * The iterator keeps state that can grow for Cords that contain many
486 // nodes and are imbalanced due to sharing. Prefer to pass this type by
487 // const reference instead of by value.
488 // * This type cannot act as a forward iterator because a `Cord` can reuse
489 // sections of memory. This fact violates the requirement for forward
490 // iterators to compare equal if dereferencing them returns the same
491 // object.
492 class CharIterator {
493 public:
494 using iterator_category = std::input_iterator_tag;
495 using value_type = char;
496 using difference_type = ptrdiff_t;
497 using pointer = const char*;
498 using reference = const char&;
499
500 CharIterator() = default;
501
502 CharIterator& operator++();
503 CharIterator operator++(int);
504 bool operator==(const CharIterator& other) const;
505 bool operator!=(const CharIterator& other) const;
506 reference operator*() const;
507 pointer operator->() const;
508
509 friend Cord;
510
511 private:
512 explicit CharIterator(const Cord* cord) : chunk_iterator_(cord) {}
513
514 ChunkIterator chunk_iterator_;
515 };
516
517 // Cord::CharIterator::AdvanceAndRead()
518 //
519 // Advances the `Cord::CharIterator` by `n_bytes` and returns the bytes
520 // advanced as a separate `Cord`. `n_bytes` must be less than or equal to the
521 // number of bytes within the Cord; otherwise, behavior is undefined. It is
522 // valid to pass `char_end()` and `0`.
523 static Cord AdvanceAndRead(CharIterator* it, size_t n_bytes);
524
525 // Cord::CharIterator::Advance()
526 //
527 // Advances the `Cord::CharIterator` by `n_bytes`. `n_bytes` must be less than
528 // or equal to the number of bytes remaining within the Cord; otherwise,
529 // behavior is undefined. It is valid to pass `char_end()` and `0`.
530 static void Advance(CharIterator* it, size_t n_bytes);
531
532 // Cord::CharIterator::ChunkRemaining()
533 //
534 // Returns the longest contiguous view starting at the iterator's position.
535 //
536 // `it` must be dereferenceable.
537 static absl::string_view ChunkRemaining(const CharIterator& it);
538
539 // Cord::CharIterator::char_begin()
540 //
541 // Returns an iterator to the first character of the `Cord`.
542 //
543 // Generally, prefer using `Cord::Chars()` within a range-based for loop for
544 // iterating over the chunks of a Cord. This method may be useful for getting
545 // a `CharIterator` where range-based for-loops may not be available.
546 CharIterator char_begin() const;
547
548 // Cord::CharIterator::char_end()
549 //
550 // Returns an iterator to one past the last character of the `Cord`.
551 //
552 // Generally, prefer using `Cord::Chars()` within a range-based for loop for
553 // iterating over the chunks of a Cord. This method may be useful for getting
554 // a `CharIterator` where range-based for-loops are not useful.
555 CharIterator char_end() const;
556
557 // Cord::CharIterator::CharRange
558 //
559 // `CharRange` is a helper class for iterating over the characters of a
560 // producing an iterator which can be used within a range-based for loop.
561 // Construction of a `CharRange` will return an iterator pointing to the first
562 // character of the Cord. Generally, do not construct a `CharRange` directly;
563 // instead, prefer to use the `Cord::Chars()` method show below.
564 //
565 // Implementation note: `CharRange` is simply a convenience wrapper over
566 // `Cord::char_begin()` and `Cord::char_end()`.
567 class CharRange {
568 public:
569 explicit CharRange(const Cord* cord) : cord_(cord) {}
570
571 CharIterator begin() const;
572 CharIterator end() const;
573
574 private:
575 const Cord* cord_;
576 };
577
578 // Cord::CharIterator::Chars()
579 //
580 // Returns a `Cord::CharIterator` for iterating over the characters of a
581 // `Cord` with a range-based for-loop. For most character-based iteration
582 // tasks on a Cord, use `Cord::Chars()` to retrieve this iterator.
583 //
584 // Example:
585 //
586 // void ProcessCord(const Cord& cord) {
587 // for (char c : cord.Chars()) { ... }
588 // }
589 //
590 // Note that the ordinary caveats of temporary lifetime extension apply:
591 //
592 // void Process() {
593 // for (char c : CordFactory().Chars()) {
594 // // The temporary Cord returned by CordFactory has been destroyed!
595 // }
596 // }
597 CharRange Chars() const;
598
599 // Cord::operator[]
600 //
601 // Gets the "i"th character of the Cord and returns it, provided that
602 // 0 <= i < Cord.size().
603 //
604 // NOTE: This routine is reasonably efficient. It is roughly
605 // logarithmic based on the number of chunks that make up the cord. Still,
606 // if you need to iterate over the contents of a cord, you should
607 // use a CharIterator/ChunkIterator rather than call operator[] or Get()
608 // repeatedly in a loop.
609 char operator[](size_t i) const;
610
611 // Cord::TryFlat()
612 //
613 // If this cord's representation is a single flat array, returns a
614 // string_view referencing that array. Otherwise returns nullopt.
615 absl::optional<absl::string_view> TryFlat() const;
616
617 // Cord::Flatten()
618 //
619 // Flattens the cord into a single array and returns a view of the data.
620 //
621 // If the cord was already flat, the contents are not modified.
622 absl::string_view Flatten();
623
624 // Supports absl::Cord as a sink object for absl::Format().
625 friend void AbslFormatFlush(absl::Cord* cord, absl::string_view part) {
626 cord->Append(part);
627 }
628
629 template <typename H>
630 friend H AbslHashValue(H hash_state, const absl::Cord& c) {
631 absl::optional<absl::string_view> maybe_flat = c.TryFlat();
632 if (maybe_flat.has_value()) {
633 return H::combine(std::move(hash_state), *maybe_flat);
634 }
635 return c.HashFragmented(std::move(hash_state));
636 }
637
638 // Create a Cord with the contents of StringConstant<T>::value.
639 // No allocations will be done and no data will be copied.
640 // This is an INTERNAL API and subject to change or removal. This API can only
641 // be used by spelling absl::strings_internal::MakeStringConstant, which is
642 // also an internal API.
643 template <typename T>
644 explicit constexpr Cord(strings_internal::StringConstant<T>);
645
646 private:
647 friend class CordTestPeer;
648 friend bool operator==(const Cord& lhs, const Cord& rhs);
649 friend bool operator==(const Cord& lhs, absl::string_view rhs);
650
651 // Calls the provided function once for each cord chunk, in order. Unlike
652 // Chunks(), this API will not allocate memory.
653 void ForEachChunk(absl::FunctionRef<void(absl::string_view)>) const;
654
655 // Allocates new contiguous storage for the contents of the cord. This is
656 // called by Flatten() when the cord was not already flat.
657 absl::string_view FlattenSlowPath();
658
659 // Actual cord contents are hidden inside the following simple
660 // class so that we can isolate the bulk of cord.cc from changes
661 // to the representation.
662 //
663 // InlineRep holds either a tree pointer, or an array of kMaxInline bytes.
664 class InlineRep {
665 public:
666 static constexpr unsigned char kMaxInline = cord_internal::kMaxInline;
667 static_assert(kMaxInline >= sizeof(absl::cord_internal::CordRep*), "");
668 static constexpr unsigned char kTreeFlag = cord_internal::kTreeFlag;
669 static constexpr unsigned char kProfiledFlag = cord_internal::kProfiledFlag;
670
671 constexpr InlineRep() : data_() {}
672 InlineRep(const InlineRep& src);
673 InlineRep(InlineRep&& src);
674 InlineRep& operator=(const InlineRep& src);
675 InlineRep& operator=(InlineRep&& src) noexcept;
676
677 explicit constexpr InlineRep(cord_internal::InlineData data);
678
679 void Swap(InlineRep* rhs);
680 bool empty() const;
681 size_t size() const;
682 const char* data() const; // Returns nullptr if holding pointer
683 void set_data(const char* data, size_t n,
684 bool nullify_tail); // Discards pointer, if any
685 char* set_data(size_t n); // Write data to the result
686 // Returns nullptr if holding bytes
687 absl::cord_internal::CordRep* tree() const;
688 // Discards old pointer, if any
689 void set_tree(absl::cord_internal::CordRep* rep);
690 // Replaces a tree with a new root. This is faster than set_tree, but it
691 // should only be used when it's clear that the old rep was a tree.
692 void replace_tree(absl::cord_internal::CordRep* rep);
693 // Returns non-null iff was holding a pointer
694 absl::cord_internal::CordRep* clear();
695 // Converts to pointer if necessary.
696 absl::cord_internal::CordRep* force_tree(size_t extra_hint);
697 void reduce_size(size_t n); // REQUIRES: holding data
698 void remove_prefix(size_t n); // REQUIRES: holding data
699 void AppendArray(const char* src_data, size_t src_size);
700 absl::string_view FindFlatStartPiece() const;
701 void AppendTree(absl::cord_internal::CordRep* tree);
702 void PrependTree(absl::cord_internal::CordRep* tree);
703 void GetAppendRegion(char** region, size_t* size, size_t max_length);
704 void GetAppendRegion(char** region, size_t* size);
705 bool IsSame(const InlineRep& other) const {
706 return memcmp(&data_, &other.data_, sizeof(data_)) == 0;
707 }
708 int BitwiseCompare(const InlineRep& other) const {
709 uint64_t x, y;
710 // Use memcpy to avoid aliasing issues.
711 memcpy(&x, &data_, sizeof(x));
712 memcpy(&y, &other.data_, sizeof(y));
713 if (x == y) {
714 memcpy(&x, reinterpret_cast<const char*>(&data_) + 8, sizeof(x));
715 memcpy(&y, reinterpret_cast<const char*>(&other.data_) + 8, sizeof(y));
716 if (x == y) return 0;
717 }
718 return absl::big_endian::FromHost64(x) < absl::big_endian::FromHost64(y)
719 ? -1
720 : 1;
721 }
722 void CopyTo(std::string* dst) const {
723 // memcpy is much faster when operating on a known size. On most supported
724 // platforms, the small string optimization is large enough that resizing
725 // to 15 bytes does not cause a memory allocation.
726 absl::strings_internal::STLStringResizeUninitialized(dst,
727 sizeof(data_) - 1);
728 memcpy(&(*dst)[0], &data_, sizeof(data_) - 1);
729 // erase is faster than resize because the logic for memory allocation is
730 // not needed.
731 dst->erase(tagged_size());
732 }
733
734 // Copies the inline contents into `dst`. Assumes the cord is not empty.
735 void CopyToArray(char* dst) const;
736
737 bool is_tree() const { return tagged_size() > kMaxInline; }
738
739 private:
740 friend class Cord;
741
742 void AssignSlow(const InlineRep& src);
743 // Unrefs the tree, stops profiling, and zeroes the contents
744 void ClearSlow();
745
746 void ResetToEmpty() { data_ = {}; }
747
748 // This uses reinterpret_cast instead of the union to avoid accessing the
749 // inactive union element. The tagged size is not a common prefix.
750 void set_tagged_size(char new_tag) {
751 reinterpret_cast<char*>(&data_)[kMaxInline] = new_tag;
752 }
753 char tagged_size() const {
754 return reinterpret_cast<const char*>(&data_)[kMaxInline];
755 }
756
757 cord_internal::InlineData data_;
758 };
759 InlineRep contents_;
760
761 // Helper for MemoryUsage().
762 static size_t MemoryUsageAux(const absl::cord_internal::CordRep* rep);
763
764 // Helper for GetFlat() and TryFlat().
765 static bool GetFlatAux(absl::cord_internal::CordRep* rep,
766 absl::string_view* fragment);
767
768 // Helper for ForEachChunk().
769 static void ForEachChunkAux(
770 absl::cord_internal::CordRep* rep,
771 absl::FunctionRef<void(absl::string_view)> callback);
772
773 // The destructor for non-empty Cords.
774 void DestroyCordSlow();
775
776 // Out-of-line implementation of slower parts of logic.
777 void CopyToArraySlowPath(char* dst) const;
778 int CompareSlowPath(absl::string_view rhs, size_t compared_size,
779 size_t size_to_compare) const;
780 int CompareSlowPath(const Cord& rhs, size_t compared_size,
781 size_t size_to_compare) const;
782 bool EqualsImpl(absl::string_view rhs, size_t size_to_compare) const;
783 bool EqualsImpl(const Cord& rhs, size_t size_to_compare) const;
784 int CompareImpl(const Cord& rhs) const;
785
786 template <typename ResultType, typename RHS>
787 friend ResultType GenericCompare(const Cord& lhs, const RHS& rhs,
788 size_t size_to_compare);
789 static absl::string_view GetFirstChunk(const Cord& c);
790 static absl::string_view GetFirstChunk(absl::string_view sv);
791
792 // Returns a new reference to contents_.tree(), or steals an existing
793 // reference if called on an rvalue.
794 absl::cord_internal::CordRep* TakeRep() const&;
795 absl::cord_internal::CordRep* TakeRep() &&;
796
797 // Helper for Append().
798 template <typename C>
799 void AppendImpl(C&& src);
800
801 // Helper for AbslHashValue().
802 template <typename H>
803 H HashFragmented(H hash_state) const {
804 typename H::AbslInternalPiecewiseCombiner combiner;
805 ForEachChunk([&combiner, &hash_state](absl::string_view chunk) {
806 hash_state = combiner.add_buffer(std::move(hash_state), chunk.data(),
807 chunk.size());
808 });
809 return H::combine(combiner.finalize(std::move(hash_state)), size());
810 }
811};
812
813ABSL_NAMESPACE_END
814} // namespace absl
815
816namespace absl {
817ABSL_NAMESPACE_BEGIN
818
819// allow a Cord to be logged
820extern std::ostream& operator<<(std::ostream& out, const Cord& cord);
821
822// ------------------------------------------------------------------
823// Internal details follow. Clients should ignore.
824
825namespace cord_internal {
826
827// Fast implementation of memmove for up to 15 bytes. This implementation is
828// safe for overlapping regions. If nullify_tail is true, the destination is
829// padded with '\0' up to 16 bytes.
830inline void SmallMemmove(char* dst, const char* src, size_t n,
831 bool nullify_tail = false) {
832 if (n >= 8) {
833 assert(n <= 16);
834 uint64_t buf1;
835 uint64_t buf2;
836 memcpy(&buf1, src, 8);
837 memcpy(&buf2, src + n - 8, 8);
838 if (nullify_tail) {
839 memset(dst + 8, 0, 8);
840 }
841 memcpy(dst, &buf1, 8);
842 memcpy(dst + n - 8, &buf2, 8);
843 } else if (n >= 4) {
844 uint32_t buf1;
845 uint32_t buf2;
846 memcpy(&buf1, src, 4);
847 memcpy(&buf2, src + n - 4, 4);
848 if (nullify_tail) {
849 memset(dst + 4, 0, 4);
850 memset(dst + 8, 0, 8);
851 }
852 memcpy(dst, &buf1, 4);
853 memcpy(dst + n - 4, &buf2, 4);
854 } else {
855 if (n != 0) {
856 dst[0] = src[0];
857 dst[n / 2] = src[n / 2];
858 dst[n - 1] = src[n - 1];
859 }
860 if (nullify_tail) {
861 memset(dst + 8, 0, 8);
862 memset(dst + n, 0, 8);
863 }
864 }
865}
866
867// Does non-template-specific `CordRepExternal` initialization.
868// Expects `data` to be non-empty.
869void InitializeCordRepExternal(absl::string_view data, CordRepExternal* rep);
870
871// Creates a new `CordRep` that owns `data` and `releaser` and returns a pointer
872// to it, or `nullptr` if `data` was empty.
873template <typename Releaser>
874// NOLINTNEXTLINE - suppress clang-tidy raw pointer return.
875CordRep* NewExternalRep(absl::string_view data, Releaser&& releaser) {
876 using ReleaserType = absl::decay_t<Releaser>;
877 if (data.empty()) {
878 // Never create empty external nodes.
879 InvokeReleaser(Rank0{}, ReleaserType(std::forward<Releaser>(releaser)),
880 data);
881 return nullptr;
882 }
883
884 CordRepExternal* rep = new CordRepExternalImpl<ReleaserType>(
885 std::forward<Releaser>(releaser), 0);
886 InitializeCordRepExternal(data, rep);
887 return rep;
888}
889
890// Overload for function reference types that dispatches using a function
891// pointer because there are no `alignof()` or `sizeof()` a function reference.
892// NOLINTNEXTLINE - suppress clang-tidy raw pointer return.
893inline CordRep* NewExternalRep(absl::string_view data,
894 void (&releaser)(absl::string_view)) {
895 return NewExternalRep(data, &releaser);
896}
897
898} // namespace cord_internal
899
900template <typename Releaser>
901Cord MakeCordFromExternal(absl::string_view data, Releaser&& releaser) {
902 Cord cord;
903 cord.contents_.set_tree(::absl::cord_internal::NewExternalRep(
904 data, std::forward<Releaser>(releaser)));
905 return cord;
906}
907
908constexpr Cord::InlineRep::InlineRep(cord_internal::InlineData data)
909 : data_(data) {}
910
911inline Cord::InlineRep::InlineRep(const Cord::InlineRep& src) {
912 data_ = src.data_;
913}
914
915inline Cord::InlineRep::InlineRep(Cord::InlineRep&& src) {
916 data_ = src.data_;
917 src.ResetToEmpty();
918}
919
920inline Cord::InlineRep& Cord::InlineRep::operator=(const Cord::InlineRep& src) {
921 if (this == &src) {
922 return *this;
923 }
924 if (!is_tree() && !src.is_tree()) {
925 data_ = src.data_;
926 return *this;
927 }
928 AssignSlow(src);
929 return *this;
930}
931
932inline Cord::InlineRep& Cord::InlineRep::operator=(
933 Cord::InlineRep&& src) noexcept {
934 if (is_tree()) {
935 ClearSlow();
936 }
937 data_ = src.data_;
938 src.ResetToEmpty();
939 return *this;
940}
941
942inline void Cord::InlineRep::Swap(Cord::InlineRep* rhs) {
943 if (rhs == this) {
944 return;
945 }
946
947 std::swap(data_, rhs->data_);
948}
949
950inline const char* Cord::InlineRep::data() const {
951 return is_tree() ? nullptr : data_.as_chars;
952}
953
954inline absl::cord_internal::CordRep* Cord::InlineRep::tree() const {
955 if (is_tree()) {
956 return data_.as_tree.rep;
957 } else {
958 return nullptr;
959 }
960}
961
962inline bool Cord::InlineRep::empty() const { return tagged_size() == 0; }
963
964inline size_t Cord::InlineRep::size() const {
965 const char tag = tagged_size();
966 if (tag <= kMaxInline) return tag;
967 return static_cast<size_t>(tree()->length);
968}
969
970inline void Cord::InlineRep::set_tree(absl::cord_internal::CordRep* rep) {
971 if (rep == nullptr) {
972 ResetToEmpty();
973 } else {
974 bool was_tree = is_tree();
975 data_.as_tree = {rep, {}, tagged_size()};
976 if (!was_tree) {
977 // If we were not a tree already, set the tag.
978 // Otherwise, leave it alone because it might have the profile bit on.
979 set_tagged_size(kTreeFlag);
980 }
981 }
982}
983
984inline void Cord::InlineRep::replace_tree(absl::cord_internal::CordRep* rep) {
985 ABSL_ASSERT(is_tree());
986 if (ABSL_PREDICT_FALSE(rep == nullptr)) {
987 set_tree(rep);
988 return;
989 }
990 data_.as_tree = {rep, {}, tagged_size()};
991}
992
993inline absl::cord_internal::CordRep* Cord::InlineRep::clear() {
994 absl::cord_internal::CordRep* result = tree();
995 ResetToEmpty();
996 return result;
997}
998
999inline void Cord::InlineRep::CopyToArray(char* dst) const {
1000 assert(!is_tree());
1001 size_t n = tagged_size();
1002 assert(n != 0);
1003 cord_internal::SmallMemmove(dst, data_.as_chars, n);
1004}
1005
1006constexpr inline Cord::Cord() noexcept {}
1007
1008template <typename T>
1009constexpr Cord::Cord(strings_internal::StringConstant<T>)
1010 : contents_(strings_internal::StringConstant<T>::value.size() <=
1011 cord_internal::kMaxInline
1012 ? cord_internal::InlineData(
1013 strings_internal::StringConstant<T>::value)
1014 : cord_internal::InlineData(cord_internal::AsTree{
1015 &cord_internal::ConstInitExternalStorage<
1016 strings_internal::StringConstant<T>>::value,
1017 {},
1018 cord_internal::kTreeFlag})) {}
1019
1020inline Cord& Cord::operator=(const Cord& x) {
1021 contents_ = x.contents_;
1022 return *this;
1023}
1024
1025inline Cord::Cord(Cord&& src) noexcept : contents_(std::move(src.contents_)) {}
1026
1027inline void Cord::swap(Cord& other) noexcept {
1028 contents_.Swap(&other.contents_);
1029}
1030
1031inline Cord& Cord::operator=(Cord&& x) noexcept {
1032 contents_ = std::move(x.contents_);
1033 return *this;
1034}
1035
1036extern template Cord::Cord(std::string&& src);
1037extern template Cord& Cord::operator=(std::string&& src);
1038
1039inline size_t Cord::size() const {
1040 // Length is 1st field in str.rep_
1041 return contents_.size();
1042}
1043
1044inline bool Cord::empty() const { return contents_.empty(); }
1045
1046inline size_t Cord::EstimatedMemoryUsage() const {
1047 size_t result = sizeof(Cord);
1048 if (const absl::cord_internal::CordRep* rep = contents_.tree()) {
1049 result += MemoryUsageAux(rep);
1050 }
1051 return result;
1052}
1053
1054inline absl::optional<absl::string_view> Cord::TryFlat() const {
1055 absl::cord_internal::CordRep* rep = contents_.tree();
1056 if (rep == nullptr) {
1057 return absl::string_view(contents_.data(), contents_.size());
1058 }
1059 absl::string_view fragment;
1060 if (GetFlatAux(rep, &fragment)) {
1061 return fragment;
1062 }
1063 return absl::nullopt;
1064}
1065
1066inline absl::string_view Cord::Flatten() {
1067 absl::cord_internal::CordRep* rep = contents_.tree();
1068 if (rep == nullptr) {
1069 return absl::string_view(contents_.data(), contents_.size());
1070 } else {
1071 absl::string_view already_flat_contents;
1072 if (GetFlatAux(rep, &already_flat_contents)) {
1073 return already_flat_contents;
1074 }
1075 }
1076 return FlattenSlowPath();
1077}
1078
1079inline void Cord::Append(absl::string_view src) {
1080 contents_.AppendArray(src.data(), src.size());
1081}
1082
1083extern template void Cord::Append(std::string&& src);
1084extern template void Cord::Prepend(std::string&& src);
1085
1086inline int Cord::Compare(const Cord& rhs) const {
1087 if (!contents_.is_tree() && !rhs.contents_.is_tree()) {
1088 return contents_.BitwiseCompare(rhs.contents_);
1089 }
1090
1091 return CompareImpl(rhs);
1092}
1093
1094// Does 'this' cord start/end with rhs
1095inline bool Cord::StartsWith(const Cord& rhs) const {
1096 if (contents_.IsSame(rhs.contents_)) return true;
1097 size_t rhs_size = rhs.size();
1098 if (size() < rhs_size) return false;
1099 return EqualsImpl(rhs, rhs_size);
1100}
1101
1102inline bool Cord::StartsWith(absl::string_view rhs) const {
1103 size_t rhs_size = rhs.size();
1104 if (size() < rhs_size) return false;
1105 return EqualsImpl(rhs, rhs_size);
1106}
1107
1108inline Cord::ChunkIterator::ChunkIterator(const Cord* cord)
1109 : bytes_remaining_(cord->size()) {
1110 if (cord->empty()) return;
1111 if (cord->contents_.is_tree()) {
1112 stack_of_right_children_.push_back(cord->contents_.tree());
1113 operator++();
1114 } else {
1115 current_chunk_ = absl::string_view(cord->contents_.data(), cord->size());
1116 }
1117}
1118
1119inline Cord::ChunkIterator& Cord::ChunkIterator::operator++() {
1120 ABSL_HARDENING_ASSERT(bytes_remaining_ > 0 &&
1121 "Attempted to iterate past `end()`");
1122 assert(bytes_remaining_ >= current_chunk_.size());
1123 bytes_remaining_ -= current_chunk_.size();
1124 if (bytes_remaining_ > 0) {
1125 return AdvanceStack();
1126 } else {
1127 current_chunk_ = {};
1128 }
1129 return *this;
1130}
1131
1132inline Cord::ChunkIterator Cord::ChunkIterator::operator++(int) {
1133 ChunkIterator tmp(*this);
1134 operator++();
1135 return tmp;
1136}
1137
1138inline bool Cord::ChunkIterator::operator==(const ChunkIterator& other) const {
1139 return bytes_remaining_ == other.bytes_remaining_;
1140}
1141
1142inline bool Cord::ChunkIterator::operator!=(const ChunkIterator& other) const {
1143 return !(*this == other);
1144}
1145
1146inline Cord::ChunkIterator::reference Cord::ChunkIterator::operator*() const {
1147 ABSL_HARDENING_ASSERT(bytes_remaining_ != 0);
1148 return current_chunk_;
1149}
1150
1151inline Cord::ChunkIterator::pointer Cord::ChunkIterator::operator->() const {
1152 ABSL_HARDENING_ASSERT(bytes_remaining_ != 0);
1153 return &current_chunk_;
1154}
1155
1156inline void Cord::ChunkIterator::RemoveChunkPrefix(size_t n) {
1157 assert(n < current_chunk_.size());
1158 current_chunk_.remove_prefix(n);
1159 bytes_remaining_ -= n;
1160}
1161
1162inline void Cord::ChunkIterator::AdvanceBytes(size_t n) {
1163 if (ABSL_PREDICT_TRUE(n < current_chunk_.size())) {
1164 RemoveChunkPrefix(n);
1165 } else if (n != 0) {
1166 AdvanceBytesSlowPath(n);
1167 }
1168}
1169
1170inline Cord::ChunkIterator Cord::chunk_begin() const {
1171 return ChunkIterator(this);
1172}
1173
1174inline Cord::ChunkIterator Cord::chunk_end() const { return ChunkIterator(); }
1175
1176inline Cord::ChunkIterator Cord::ChunkRange::begin() const {
1177 return cord_->chunk_begin();
1178}
1179
1180inline Cord::ChunkIterator Cord::ChunkRange::end() const {
1181 return cord_->chunk_end();
1182}
1183
1184inline Cord::ChunkRange Cord::Chunks() const { return ChunkRange(this); }
1185
1186inline Cord::CharIterator& Cord::CharIterator::operator++() {
1187 if (ABSL_PREDICT_TRUE(chunk_iterator_->size() > 1)) {
1188 chunk_iterator_.RemoveChunkPrefix(1);
1189 } else {
1190 ++chunk_iterator_;
1191 }
1192 return *this;
1193}
1194
1195inline Cord::CharIterator Cord::CharIterator::operator++(int) {
1196 CharIterator tmp(*this);
1197 operator++();
1198 return tmp;
1199}
1200
1201inline bool Cord::CharIterator::operator==(const CharIterator& other) const {
1202 return chunk_iterator_ == other.chunk_iterator_;
1203}
1204
1205inline bool Cord::CharIterator::operator!=(const CharIterator& other) const {
1206 return !(*this == other);
1207}
1208
1209inline Cord::CharIterator::reference Cord::CharIterator::operator*() const {
1210 return *chunk_iterator_->data();
1211}
1212
1213inline Cord::CharIterator::pointer Cord::CharIterator::operator->() const {
1214 return chunk_iterator_->data();
1215}
1216
1217inline Cord Cord::AdvanceAndRead(CharIterator* it, size_t n_bytes) {
1218 assert(it != nullptr);
1219 return it->chunk_iterator_.AdvanceAndReadBytes(n_bytes);
1220}
1221
1222inline void Cord::Advance(CharIterator* it, size_t n_bytes) {
1223 assert(it != nullptr);
1224 it->chunk_iterator_.AdvanceBytes(n_bytes);
1225}
1226
1227inline absl::string_view Cord::ChunkRemaining(const CharIterator& it) {
1228 return *it.chunk_iterator_;
1229}
1230
1231inline Cord::CharIterator Cord::char_begin() const {
1232 return CharIterator(this);
1233}
1234
1235inline Cord::CharIterator Cord::char_end() const { return CharIterator(); }
1236
1237inline Cord::CharIterator Cord::CharRange::begin() const {
1238 return cord_->char_begin();
1239}
1240
1241inline Cord::CharIterator Cord::CharRange::end() const {
1242 return cord_->char_end();
1243}
1244
1245inline Cord::CharRange Cord::Chars() const { return CharRange(this); }
1246
1247inline void Cord::ForEachChunk(
1248 absl::FunctionRef<void(absl::string_view)> callback) const {
1249 absl::cord_internal::CordRep* rep = contents_.tree();
1250 if (rep == nullptr) {
1251 callback(absl::string_view(contents_.data(), contents_.size()));
1252 } else {
1253 return ForEachChunkAux(rep, callback);
1254 }
1255}
1256
1257// Nonmember Cord-to-Cord relational operarators.
1258inline bool operator==(const Cord& lhs, const Cord& rhs) {
1259 if (lhs.contents_.IsSame(rhs.contents_)) return true;
1260 size_t rhs_size = rhs.size();
1261 if (lhs.size() != rhs_size) return false;
1262 return lhs.EqualsImpl(rhs, rhs_size);
1263}
1264
1265inline bool operator!=(const Cord& x, const Cord& y) { return !(x == y); }
1266inline bool operator<(const Cord& x, const Cord& y) {
1267 return x.Compare(y) < 0;
1268}
1269inline bool operator>(const Cord& x, const Cord& y) {
1270 return x.Compare(y) > 0;
1271}
1272inline bool operator<=(const Cord& x, const Cord& y) {
1273 return x.Compare(y) <= 0;
1274}
1275inline bool operator>=(const Cord& x, const Cord& y) {
1276 return x.Compare(y) >= 0;
1277}
1278
1279// Nonmember Cord-to-absl::string_view relational operators.
1280//
1281// Due to implicit conversions, these also enable comparisons of Cord with
1282// with std::string, ::string, and const char*.
1283inline bool operator==(const Cord& lhs, absl::string_view rhs) {
1284 size_t lhs_size = lhs.size();
1285 size_t rhs_size = rhs.size();
1286 if (lhs_size != rhs_size) return false;
1287 return lhs.EqualsImpl(rhs, rhs_size);
1288}
1289
1290inline bool operator==(absl::string_view x, const Cord& y) { return y == x; }
1291inline bool operator!=(const Cord& x, absl::string_view y) { return !(x == y); }
1292inline bool operator!=(absl::string_view x, const Cord& y) { return !(x == y); }
1293inline bool operator<(const Cord& x, absl::string_view y) {
1294 return x.Compare(y) < 0;
1295}
1296inline bool operator<(absl::string_view x, const Cord& y) {
1297 return y.Compare(x) > 0;
1298}
1299inline bool operator>(const Cord& x, absl::string_view y) { return y < x; }
1300inline bool operator>(absl::string_view x, const Cord& y) { return y < x; }
1301inline bool operator<=(const Cord& x, absl::string_view y) { return !(y < x); }
1302inline bool operator<=(absl::string_view x, const Cord& y) { return !(y < x); }
1303inline bool operator>=(const Cord& x, absl::string_view y) { return !(x < y); }
1304inline bool operator>=(absl::string_view x, const Cord& y) { return !(x < y); }
1305
1306// Some internals exposed to test code.
1307namespace strings_internal {
1308class CordTestAccess {
1309 public:
1310 static size_t FlatOverhead();
1311 static size_t MaxFlatLength();
1312 static size_t SizeofCordRepConcat();
1313 static size_t SizeofCordRepExternal();
1314 static size_t SizeofCordRepSubstring();
1315 static size_t FlatTagToLength(uint8_t tag);
1316 static uint8_t LengthToTag(size_t s);
1317};
1318} // namespace strings_internal
1319ABSL_NAMESPACE_END
1320} // namespace absl
1321
1322#endif // ABSL_STRINGS_CORD_H_