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 #include "absl/strings/cord.h"
16
17 #include <algorithm>
18 #include <atomic>
19 #include <cstddef>
20 #include <cstdio>
21 #include <cstdlib>
22 #include <iomanip>
23 #include <ios>
24 #include <iostream>
25 #include <limits>
26 #include <ostream>
27 #include <sstream>
28 #include <type_traits>
29 #include <unordered_set>
30 #include <vector>
31
32 #include "absl/base/casts.h"
33 #include "absl/base/internal/raw_logging.h"
34 #include "absl/base/macros.h"
35 #include "absl/base/port.h"
36 #include "absl/container/fixed_array.h"
37 #include "absl/container/inlined_vector.h"
38 #include "absl/crc/internal/crc_cord_state.h"
39 #include "absl/strings/cord_buffer.h"
40 #include "absl/strings/escaping.h"
41 #include "absl/strings/internal/cord_data_edge.h"
42 #include "absl/strings/internal/cord_internal.h"
43 #include "absl/strings/internal/cord_rep_btree.h"
44 #include "absl/strings/internal/cord_rep_crc.h"
45 #include "absl/strings/internal/cord_rep_flat.h"
46 #include "absl/strings/internal/cordz_statistics.h"
47 #include "absl/strings/internal/cordz_update_scope.h"
48 #include "absl/strings/internal/cordz_update_tracker.h"
49 #include "absl/strings/internal/resize_uninitialized.h"
50 #include "absl/strings/str_cat.h"
51 #include "absl/strings/str_format.h"
52 #include "absl/strings/str_join.h"
53 #include "absl/strings/string_view.h"
54
55 namespace absl {
56 ABSL_NAMESPACE_BEGIN
57
58 using ::absl::cord_internal::CordRep;
59 using ::absl::cord_internal::CordRepBtree;
60 using ::absl::cord_internal::CordRepCrc;
61 using ::absl::cord_internal::CordRepExternal;
62 using ::absl::cord_internal::CordRepFlat;
63 using ::absl::cord_internal::CordRepSubstring;
64 using ::absl::cord_internal::CordzUpdateTracker;
65 using ::absl::cord_internal::InlineData;
66 using ::absl::cord_internal::kMaxFlatLength;
67 using ::absl::cord_internal::kMinFlatLength;
68
69 using ::absl::cord_internal::kInlinedVectorSize;
70 using ::absl::cord_internal::kMaxBytesToCopy;
71
72 static void DumpNode(CordRep* rep, bool include_data, std::ostream* os,
73 int indent = 0);
74 static bool VerifyNode(CordRep* root, CordRep* start_node,
75 bool full_validation);
76
VerifyTree(CordRep * node)77 static inline CordRep* VerifyTree(CordRep* node) {
78 // Verification is expensive, so only do it in debug mode.
79 // Even in debug mode we normally do only light validation.
80 // If you are debugging Cord itself, you should define the
81 // macro EXTRA_CORD_VALIDATION, e.g. by adding
82 // --copt=-DEXTRA_CORD_VALIDATION to the blaze line.
83 #ifdef EXTRA_CORD_VALIDATION
84 assert(node == nullptr || VerifyNode(node, node, /*full_validation=*/true));
85 #else // EXTRA_CORD_VALIDATION
86 assert(node == nullptr || VerifyNode(node, node, /*full_validation=*/false));
87 #endif // EXTRA_CORD_VALIDATION
88 static_cast<void>(&VerifyNode);
89
90 return node;
91 }
92
CreateFlat(const char * data,size_t length,size_t alloc_hint)93 static CordRepFlat* CreateFlat(const char* data, size_t length,
94 size_t alloc_hint) {
95 CordRepFlat* flat = CordRepFlat::New(length + alloc_hint);
96 flat->length = length;
97 memcpy(flat->Data(), data, length);
98 return flat;
99 }
100
101 // Creates a new flat or Btree out of the specified array.
102 // The returned node has a refcount of 1.
NewBtree(const char * data,size_t length,size_t alloc_hint)103 static CordRep* NewBtree(const char* data, size_t length, size_t alloc_hint) {
104 if (length <= kMaxFlatLength) {
105 return CreateFlat(data, length, alloc_hint);
106 }
107 CordRepFlat* flat = CreateFlat(data, kMaxFlatLength, 0);
108 data += kMaxFlatLength;
109 length -= kMaxFlatLength;
110 auto* root = CordRepBtree::Create(flat);
111 return CordRepBtree::Append(root, {data, length}, alloc_hint);
112 }
113
114 // Create a new tree out of the specified array.
115 // The returned node has a refcount of 1.
NewTree(const char * data,size_t length,size_t alloc_hint)116 static CordRep* NewTree(const char* data, size_t length, size_t alloc_hint) {
117 if (length == 0) return nullptr;
118 return NewBtree(data, length, alloc_hint);
119 }
120
121 namespace cord_internal {
122
InitializeCordRepExternal(absl::string_view data,CordRepExternal * rep)123 void InitializeCordRepExternal(absl::string_view data, CordRepExternal* rep) {
124 assert(!data.empty());
125 rep->length = data.size();
126 rep->tag = EXTERNAL;
127 rep->base = data.data();
128 VerifyTree(rep);
129 }
130
131 } // namespace cord_internal
132
133 // Creates a CordRep from the provided string. If the string is large enough,
134 // and not wasteful, we move the string into an external cord rep, preserving
135 // the already allocated string contents.
136 // Requires the provided string length to be larger than `kMaxInline`.
CordRepFromString(std::string && src)137 static CordRep* CordRepFromString(std::string&& src) {
138 assert(src.length() > cord_internal::kMaxInline);
139 if (
140 // String is short: copy data to avoid external block overhead.
141 src.size() <= kMaxBytesToCopy ||
142 // String is wasteful: copy data to avoid pinning too much unused memory.
143 src.size() < src.capacity() / 2
144 ) {
145 return NewTree(src.data(), src.size(), 0);
146 }
147
148 struct StringReleaser {
149 void operator()(absl::string_view /* data */) {}
150 std::string data;
151 };
152 const absl::string_view original_data = src;
153 auto* rep =
154 static_cast<::absl::cord_internal::CordRepExternalImpl<StringReleaser>*>(
155 absl::cord_internal::NewExternalRep(original_data,
156 StringReleaser{std::move(src)}));
157 // Moving src may have invalidated its data pointer, so adjust it.
158 rep->base = rep->template get<0>().data.data();
159 return rep;
160 }
161
162 // --------------------------------------------------------------------
163 // Cord::InlineRep functions
164
165 #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
166 constexpr unsigned char Cord::InlineRep::kMaxInline;
167 #endif
168
set_data(const char * data,size_t n)169 inline void Cord::InlineRep::set_data(const char* data, size_t n) {
170 static_assert(kMaxInline == 15, "set_data is hard-coded for a length of 15");
171 data_.set_inline_data(data, n);
172 }
173
set_data(size_t n)174 inline char* Cord::InlineRep::set_data(size_t n) {
175 assert(n <= kMaxInline);
176 ResetToEmpty();
177 set_inline_size(n);
178 return data_.as_chars();
179 }
180
reduce_size(size_t n)181 inline void Cord::InlineRep::reduce_size(size_t n) {
182 size_t tag = inline_size();
183 assert(tag <= kMaxInline);
184 assert(tag >= n);
185 tag -= n;
186 memset(data_.as_chars() + tag, 0, n);
187 set_inline_size(tag);
188 }
189
remove_prefix(size_t n)190 inline void Cord::InlineRep::remove_prefix(size_t n) {
191 cord_internal::SmallMemmove(data_.as_chars(), data_.as_chars() + n,
192 inline_size() - n);
193 reduce_size(n);
194 }
195
196 // Returns `rep` converted into a CordRepBtree.
197 // Directly returns `rep` if `rep` is already a CordRepBtree.
ForceBtree(CordRep * rep)198 static CordRepBtree* ForceBtree(CordRep* rep) {
199 return rep->IsBtree()
200 ? rep->btree()
201 : CordRepBtree::Create(cord_internal::RemoveCrcNode(rep));
202 }
203
AppendTreeToInlined(CordRep * tree,MethodIdentifier method)204 void Cord::InlineRep::AppendTreeToInlined(CordRep* tree,
205 MethodIdentifier method) {
206 assert(!is_tree());
207 if (!data_.is_empty()) {
208 CordRepFlat* flat = MakeFlatWithExtraCapacity(0);
209 tree = CordRepBtree::Append(CordRepBtree::Create(flat), tree);
210 }
211 EmplaceTree(tree, method);
212 }
213
AppendTreeToTree(CordRep * tree,MethodIdentifier method)214 void Cord::InlineRep::AppendTreeToTree(CordRep* tree, MethodIdentifier method) {
215 assert(is_tree());
216 const CordzUpdateScope scope(data_.cordz_info(), method);
217 tree = CordRepBtree::Append(ForceBtree(data_.as_tree()), tree);
218 SetTree(tree, scope);
219 }
220
AppendTree(CordRep * tree,MethodIdentifier method)221 void Cord::InlineRep::AppendTree(CordRep* tree, MethodIdentifier method) {
222 assert(tree != nullptr);
223 assert(tree->length != 0);
224 assert(!tree->IsCrc());
225 if (data_.is_tree()) {
226 AppendTreeToTree(tree, method);
227 } else {
228 AppendTreeToInlined(tree, method);
229 }
230 }
231
PrependTreeToInlined(CordRep * tree,MethodIdentifier method)232 void Cord::InlineRep::PrependTreeToInlined(CordRep* tree,
233 MethodIdentifier method) {
234 assert(!is_tree());
235 if (!data_.is_empty()) {
236 CordRepFlat* flat = MakeFlatWithExtraCapacity(0);
237 tree = CordRepBtree::Prepend(CordRepBtree::Create(flat), tree);
238 }
239 EmplaceTree(tree, method);
240 }
241
PrependTreeToTree(CordRep * tree,MethodIdentifier method)242 void Cord::InlineRep::PrependTreeToTree(CordRep* tree,
243 MethodIdentifier method) {
244 assert(is_tree());
245 const CordzUpdateScope scope(data_.cordz_info(), method);
246 tree = CordRepBtree::Prepend(ForceBtree(data_.as_tree()), tree);
247 SetTree(tree, scope);
248 }
249
PrependTree(CordRep * tree,MethodIdentifier method)250 void Cord::InlineRep::PrependTree(CordRep* tree, MethodIdentifier method) {
251 assert(tree != nullptr);
252 assert(tree->length != 0);
253 assert(!tree->IsCrc());
254 if (data_.is_tree()) {
255 PrependTreeToTree(tree, method);
256 } else {
257 PrependTreeToInlined(tree, method);
258 }
259 }
260
261 // Searches for a non-full flat node at the rightmost leaf of the tree. If a
262 // suitable leaf is found, the function will update the length field for all
263 // nodes to account for the size increase. The append region address will be
264 // written to region and the actual size increase will be written to size.
PrepareAppendRegion(CordRep * root,char ** region,size_t * size,size_t max_length)265 static inline bool PrepareAppendRegion(CordRep* root, char** region,
266 size_t* size, size_t max_length) {
267 if (root->IsBtree() && root->refcount.IsOne()) {
268 Span<char> span = root->btree()->GetAppendBuffer(max_length);
269 if (!span.empty()) {
270 *region = span.data();
271 *size = span.size();
272 return true;
273 }
274 }
275
276 CordRep* dst = root;
277 if (!dst->IsFlat() || !dst->refcount.IsOne()) {
278 *region = nullptr;
279 *size = 0;
280 return false;
281 }
282
283 const size_t in_use = dst->length;
284 const size_t capacity = dst->flat()->Capacity();
285 if (in_use == capacity) {
286 *region = nullptr;
287 *size = 0;
288 return false;
289 }
290
291 const size_t size_increase = std::min(capacity - in_use, max_length);
292 dst->length += size_increase;
293
294 *region = dst->flat()->Data() + in_use;
295 *size = size_increase;
296 return true;
297 }
298
AssignSlow(const Cord::InlineRep & src)299 void Cord::InlineRep::AssignSlow(const Cord::InlineRep& src) {
300 assert(&src != this);
301 assert(is_tree() || src.is_tree());
302 auto constexpr method = CordzUpdateTracker::kAssignCord;
303 if (ABSL_PREDICT_TRUE(!is_tree())) {
304 EmplaceTree(CordRep::Ref(src.as_tree()), src.data_, method);
305 return;
306 }
307
308 CordRep* tree = as_tree();
309 if (CordRep* src_tree = src.tree()) {
310 // Leave any existing `cordz_info` in place, and let MaybeTrackCord()
311 // decide if this cord should be (or remains to be) sampled or not.
312 data_.set_tree(CordRep::Ref(src_tree));
313 CordzInfo::MaybeTrackCord(data_, src.data_, method);
314 } else {
315 CordzInfo::MaybeUntrackCord(data_.cordz_info());
316 data_ = src.data_;
317 }
318 CordRep::Unref(tree);
319 }
320
UnrefTree()321 void Cord::InlineRep::UnrefTree() {
322 if (is_tree()) {
323 CordzInfo::MaybeUntrackCord(data_.cordz_info());
324 CordRep::Unref(tree());
325 }
326 }
327
328 // --------------------------------------------------------------------
329 // Constructors and destructors
330
Cord(absl::string_view src,MethodIdentifier method)331 Cord::Cord(absl::string_view src, MethodIdentifier method)
332 : contents_(InlineData::kDefaultInit) {
333 const size_t n = src.size();
334 if (n <= InlineRep::kMaxInline) {
335 contents_.set_data(src.data(), n);
336 } else {
337 CordRep* rep = NewTree(src.data(), n, 0);
338 contents_.EmplaceTree(rep, method);
339 }
340 }
341
342 template <typename T, Cord::EnableIfString<T>>
Cord(T && src)343 Cord::Cord(T&& src) : contents_(InlineData::kDefaultInit) {
344 if (src.size() <= InlineRep::kMaxInline) {
345 contents_.set_data(src.data(), src.size());
346 } else {
347 CordRep* rep = CordRepFromString(std::forward<T>(src));
348 contents_.EmplaceTree(rep, CordzUpdateTracker::kConstructorString);
349 }
350 }
351
352 template Cord::Cord(std::string&& src);
353
354 // The destruction code is separate so that the compiler can determine
355 // that it does not need to call the destructor on a moved-from Cord.
DestroyCordSlow()356 void Cord::DestroyCordSlow() {
357 assert(contents_.is_tree());
358 CordzInfo::MaybeUntrackCord(contents_.cordz_info());
359 CordRep::Unref(VerifyTree(contents_.as_tree()));
360 }
361
362 // --------------------------------------------------------------------
363 // Mutators
364
Clear()365 void Cord::Clear() {
366 if (CordRep* tree = contents_.clear()) {
367 CordRep::Unref(tree);
368 }
369 }
370
AssignLargeString(std::string && src)371 Cord& Cord::AssignLargeString(std::string&& src) {
372 auto constexpr method = CordzUpdateTracker::kAssignString;
373 assert(src.size() > kMaxBytesToCopy);
374 CordRep* rep = CordRepFromString(std::move(src));
375 if (CordRep* tree = contents_.tree()) {
376 CordzUpdateScope scope(contents_.cordz_info(), method);
377 contents_.SetTree(rep, scope);
378 CordRep::Unref(tree);
379 } else {
380 contents_.EmplaceTree(rep, method);
381 }
382 return *this;
383 }
384
operator =(absl::string_view src)385 Cord& Cord::operator=(absl::string_view src) {
386 auto constexpr method = CordzUpdateTracker::kAssignString;
387 const char* data = src.data();
388 size_t length = src.size();
389 CordRep* tree = contents_.tree();
390 if (length <= InlineRep::kMaxInline) {
391 // Embed into this->contents_, which is somewhat subtle:
392 // - MaybeUntrackCord must be called before Unref(tree).
393 // - MaybeUntrackCord must be called before set_data() clobbers cordz_info.
394 // - set_data() must be called before Unref(tree) as it may reference tree.
395 if (tree != nullptr) CordzInfo::MaybeUntrackCord(contents_.cordz_info());
396 contents_.set_data(data, length);
397 if (tree != nullptr) CordRep::Unref(tree);
398 return *this;
399 }
400 if (tree != nullptr) {
401 CordzUpdateScope scope(contents_.cordz_info(), method);
402 if (tree->IsFlat() && tree->flat()->Capacity() >= length &&
403 tree->refcount.IsOne()) {
404 // Copy in place if the existing FLAT node is reusable.
405 memmove(tree->flat()->Data(), data, length);
406 tree->length = length;
407 VerifyTree(tree);
408 return *this;
409 }
410 contents_.SetTree(NewTree(data, length, 0), scope);
411 CordRep::Unref(tree);
412 } else {
413 contents_.EmplaceTree(NewTree(data, length, 0), method);
414 }
415 return *this;
416 }
417
418 // TODO(sanjay): Move to Cord::InlineRep section of file. For now,
419 // we keep it here to make diffs easier.
AppendArray(absl::string_view src,MethodIdentifier method)420 void Cord::InlineRep::AppendArray(absl::string_view src,
421 MethodIdentifier method) {
422 MaybeRemoveEmptyCrcNode();
423 if (src.empty()) return; // memcpy(_, nullptr, 0) is undefined.
424
425 size_t appended = 0;
426 CordRep* rep = tree();
427 const CordRep* const root = rep;
428 CordzUpdateScope scope(root ? cordz_info() : nullptr, method);
429 if (root != nullptr) {
430 rep = cord_internal::RemoveCrcNode(rep);
431 char* region;
432 if (PrepareAppendRegion(rep, ®ion, &appended, src.size())) {
433 memcpy(region, src.data(), appended);
434 }
435 } else {
436 // Try to fit in the inline buffer if possible.
437 size_t inline_length = inline_size();
438 if (src.size() <= kMaxInline - inline_length) {
439 // Append new data to embedded array
440 set_inline_size(inline_length + src.size());
441 memcpy(data_.as_chars() + inline_length, src.data(), src.size());
442 return;
443 }
444
445 // Allocate flat to be a perfect fit on first append exceeding inlined size.
446 // Subsequent growth will use amortized growth until we reach maximum flat
447 // size.
448 rep = CordRepFlat::New(inline_length + src.size());
449 appended = std::min(src.size(), rep->flat()->Capacity() - inline_length);
450 memcpy(rep->flat()->Data(), data_.as_chars(), inline_length);
451 memcpy(rep->flat()->Data() + inline_length, src.data(), appended);
452 rep->length = inline_length + appended;
453 }
454
455 src.remove_prefix(appended);
456 if (src.empty()) {
457 CommitTree(root, rep, scope, method);
458 return;
459 }
460
461 // TODO(b/192061034): keep legacy 10% growth rate: consider other rates.
462 rep = ForceBtree(rep);
463 const size_t min_growth = std::max<size_t>(rep->length / 10, src.size());
464 rep = CordRepBtree::Append(rep->btree(), src, min_growth - src.size());
465
466 CommitTree(root, rep, scope, method);
467 }
468
TakeRep() const469 inline CordRep* Cord::TakeRep() const& {
470 return CordRep::Ref(contents_.tree());
471 }
472
TakeRep()473 inline CordRep* Cord::TakeRep() && {
474 CordRep* rep = contents_.tree();
475 contents_.clear();
476 return rep;
477 }
478
479 template <typename C>
AppendImpl(C && src)480 inline void Cord::AppendImpl(C&& src) {
481 auto constexpr method = CordzUpdateTracker::kAppendCord;
482
483 contents_.MaybeRemoveEmptyCrcNode();
484 if (src.empty()) return;
485
486 if (empty()) {
487 // Since destination is empty, we can avoid allocating a node,
488 if (src.contents_.is_tree()) {
489 // by taking the tree directly
490 CordRep* rep =
491 cord_internal::RemoveCrcNode(std::forward<C>(src).TakeRep());
492 contents_.EmplaceTree(rep, method);
493 } else {
494 // or copying over inline data
495 contents_.data_ = src.contents_.data_;
496 }
497 return;
498 }
499
500 // For short cords, it is faster to copy data if there is room in dst.
501 const size_t src_size = src.contents_.size();
502 if (src_size <= kMaxBytesToCopy) {
503 CordRep* src_tree = src.contents_.tree();
504 if (src_tree == nullptr) {
505 // src has embedded data.
506 contents_.AppendArray({src.contents_.data(), src_size}, method);
507 return;
508 }
509 if (src_tree->IsFlat()) {
510 // src tree just has one flat node.
511 contents_.AppendArray({src_tree->flat()->Data(), src_size}, method);
512 return;
513 }
514 if (&src == this) {
515 // ChunkIterator below assumes that src is not modified during traversal.
516 Append(Cord(src));
517 return;
518 }
519 // TODO(mec): Should we only do this if "dst" has space?
520 for (absl::string_view chunk : src.Chunks()) {
521 Append(chunk);
522 }
523 return;
524 }
525
526 // Guaranteed to be a tree (kMaxBytesToCopy > kInlinedSize)
527 CordRep* rep = cord_internal::RemoveCrcNode(std::forward<C>(src).TakeRep());
528 contents_.AppendTree(rep, CordzUpdateTracker::kAppendCord);
529 }
530
ExtractAppendBuffer(CordRep * rep,size_t min_capacity)531 static CordRep::ExtractResult ExtractAppendBuffer(CordRep* rep,
532 size_t min_capacity) {
533 switch (rep->tag) {
534 case cord_internal::BTREE:
535 return CordRepBtree::ExtractAppendBuffer(rep->btree(), min_capacity);
536 default:
537 if (rep->IsFlat() && rep->refcount.IsOne() &&
538 rep->flat()->Capacity() - rep->length >= min_capacity) {
539 return {nullptr, rep};
540 }
541 return {rep, nullptr};
542 }
543 }
544
CreateAppendBuffer(InlineData & data,size_t block_size,size_t capacity)545 static CordBuffer CreateAppendBuffer(InlineData& data, size_t block_size,
546 size_t capacity) {
547 // Watch out for overflow, people can ask for size_t::max().
548 const size_t size = data.inline_size();
549 const size_t max_capacity = std::numeric_limits<size_t>::max() - size;
550 capacity = (std::min)(max_capacity, capacity) + size;
551 CordBuffer buffer =
552 block_size ? CordBuffer::CreateWithCustomLimit(block_size, capacity)
553 : CordBuffer::CreateWithDefaultLimit(capacity);
554 cord_internal::SmallMemmove(buffer.data(), data.as_chars(), size);
555 buffer.SetLength(size);
556 data = {};
557 return buffer;
558 }
559
GetAppendBufferSlowPath(size_t block_size,size_t capacity,size_t min_capacity)560 CordBuffer Cord::GetAppendBufferSlowPath(size_t block_size, size_t capacity,
561 size_t min_capacity) {
562 auto constexpr method = CordzUpdateTracker::kGetAppendBuffer;
563 CordRep* tree = contents_.tree();
564 if (tree != nullptr) {
565 CordzUpdateScope scope(contents_.cordz_info(), method);
566 CordRep::ExtractResult result = ExtractAppendBuffer(tree, min_capacity);
567 if (result.extracted != nullptr) {
568 contents_.SetTreeOrEmpty(result.tree, scope);
569 return CordBuffer(result.extracted->flat());
570 }
571 return block_size ? CordBuffer::CreateWithCustomLimit(block_size, capacity)
572 : CordBuffer::CreateWithDefaultLimit(capacity);
573 }
574 return CreateAppendBuffer(contents_.data_, block_size, capacity);
575 }
576
Append(const Cord & src)577 void Cord::Append(const Cord& src) {
578 AppendImpl(src);
579 }
580
Append(Cord && src)581 void Cord::Append(Cord&& src) {
582 AppendImpl(std::move(src));
583 }
584
585 template <typename T, Cord::EnableIfString<T>>
Append(T && src)586 void Cord::Append(T&& src) {
587 if (src.size() <= kMaxBytesToCopy) {
588 Append(absl::string_view(src));
589 } else {
590 CordRep* rep = CordRepFromString(std::forward<T>(src));
591 contents_.AppendTree(rep, CordzUpdateTracker::kAppendString);
592 }
593 }
594
595 template void Cord::Append(std::string&& src);
596
Prepend(const Cord & src)597 void Cord::Prepend(const Cord& src) {
598 contents_.MaybeRemoveEmptyCrcNode();
599 if (src.empty()) return;
600
601 CordRep* src_tree = src.contents_.tree();
602 if (src_tree != nullptr) {
603 CordRep::Ref(src_tree);
604 contents_.PrependTree(cord_internal::RemoveCrcNode(src_tree),
605 CordzUpdateTracker::kPrependCord);
606 return;
607 }
608
609 // `src` cord is inlined.
610 absl::string_view src_contents(src.contents_.data(), src.contents_.size());
611 return Prepend(src_contents);
612 }
613
PrependArray(absl::string_view src,MethodIdentifier method)614 void Cord::PrependArray(absl::string_view src, MethodIdentifier method) {
615 contents_.MaybeRemoveEmptyCrcNode();
616 if (src.empty()) return; // memcpy(_, nullptr, 0) is undefined.
617
618 if (!contents_.is_tree()) {
619 size_t cur_size = contents_.inline_size();
620 if (cur_size + src.size() <= InlineRep::kMaxInline) {
621 // Use embedded storage.
622 InlineData data;
623 data.set_inline_size(cur_size + src.size());
624 memcpy(data.as_chars(), src.data(), src.size());
625 memcpy(data.as_chars() + src.size(), contents_.data(), cur_size);
626 contents_.data_ = data;
627 return;
628 }
629 }
630 CordRep* rep = NewTree(src.data(), src.size(), 0);
631 contents_.PrependTree(rep, method);
632 }
633
AppendPrecise(absl::string_view src,MethodIdentifier method)634 void Cord::AppendPrecise(absl::string_view src, MethodIdentifier method) {
635 assert(!src.empty());
636 assert(src.size() <= cord_internal::kMaxFlatLength);
637 if (contents_.remaining_inline_capacity() >= src.size()) {
638 const size_t inline_length = contents_.inline_size();
639 contents_.set_inline_size(inline_length + src.size());
640 memcpy(contents_.data_.as_chars() + inline_length, src.data(), src.size());
641 } else {
642 contents_.AppendTree(CordRepFlat::Create(src), method);
643 }
644 }
645
PrependPrecise(absl::string_view src,MethodIdentifier method)646 void Cord::PrependPrecise(absl::string_view src, MethodIdentifier method) {
647 assert(!src.empty());
648 assert(src.size() <= cord_internal::kMaxFlatLength);
649 if (contents_.remaining_inline_capacity() >= src.size()) {
650 const size_t cur_size = contents_.inline_size();
651 InlineData data;
652 data.set_inline_size(cur_size + src.size());
653 memcpy(data.as_chars(), src.data(), src.size());
654 memcpy(data.as_chars() + src.size(), contents_.data(), cur_size);
655 contents_.data_ = data;
656 } else {
657 contents_.PrependTree(CordRepFlat::Create(src), method);
658 }
659 }
660
661 template <typename T, Cord::EnableIfString<T>>
Prepend(T && src)662 inline void Cord::Prepend(T&& src) {
663 if (src.size() <= kMaxBytesToCopy) {
664 Prepend(absl::string_view(src));
665 } else {
666 CordRep* rep = CordRepFromString(std::forward<T>(src));
667 contents_.PrependTree(rep, CordzUpdateTracker::kPrependString);
668 }
669 }
670
671 template void Cord::Prepend(std::string&& src);
672
RemovePrefix(size_t n)673 void Cord::RemovePrefix(size_t n) {
674 ABSL_INTERNAL_CHECK(n <= size(),
675 absl::StrCat("Requested prefix size ", n,
676 " exceeds Cord's size ", size()));
677 contents_.MaybeRemoveEmptyCrcNode();
678 CordRep* tree = contents_.tree();
679 if (tree == nullptr) {
680 contents_.remove_prefix(n);
681 } else {
682 auto constexpr method = CordzUpdateTracker::kRemovePrefix;
683 CordzUpdateScope scope(contents_.cordz_info(), method);
684 tree = cord_internal::RemoveCrcNode(tree);
685 if (n >= tree->length) {
686 CordRep::Unref(tree);
687 tree = nullptr;
688 } else if (tree->IsBtree()) {
689 CordRep* old = tree;
690 tree = tree->btree()->SubTree(n, tree->length - n);
691 CordRep::Unref(old);
692 } else if (tree->IsSubstring() && tree->refcount.IsOne()) {
693 tree->substring()->start += n;
694 tree->length -= n;
695 } else {
696 CordRep* rep = CordRepSubstring::Substring(tree, n, tree->length - n);
697 CordRep::Unref(tree);
698 tree = rep;
699 }
700 contents_.SetTreeOrEmpty(tree, scope);
701 }
702 }
703
RemoveSuffix(size_t n)704 void Cord::RemoveSuffix(size_t n) {
705 ABSL_INTERNAL_CHECK(n <= size(),
706 absl::StrCat("Requested suffix size ", n,
707 " exceeds Cord's size ", size()));
708 contents_.MaybeRemoveEmptyCrcNode();
709 CordRep* tree = contents_.tree();
710 if (tree == nullptr) {
711 contents_.reduce_size(n);
712 } else {
713 auto constexpr method = CordzUpdateTracker::kRemoveSuffix;
714 CordzUpdateScope scope(contents_.cordz_info(), method);
715 tree = cord_internal::RemoveCrcNode(tree);
716 if (n >= tree->length) {
717 CordRep::Unref(tree);
718 tree = nullptr;
719 } else if (tree->IsBtree()) {
720 tree = CordRepBtree::RemoveSuffix(tree->btree(), n);
721 } else if (!tree->IsExternal() && tree->refcount.IsOne()) {
722 assert(tree->IsFlat() || tree->IsSubstring());
723 tree->length -= n;
724 } else {
725 CordRep* rep = CordRepSubstring::Substring(tree, 0, tree->length - n);
726 CordRep::Unref(tree);
727 tree = rep;
728 }
729 contents_.SetTreeOrEmpty(tree, scope);
730 }
731 }
732
Subcord(size_t pos,size_t new_size) const733 Cord Cord::Subcord(size_t pos, size_t new_size) const {
734 Cord sub_cord;
735 size_t length = size();
736 if (pos > length) pos = length;
737 if (new_size > length - pos) new_size = length - pos;
738 if (new_size == 0) return sub_cord;
739
740 CordRep* tree = contents_.tree();
741 if (tree == nullptr) {
742 sub_cord.contents_.set_data(contents_.data() + pos, new_size);
743 return sub_cord;
744 }
745
746 if (new_size <= InlineRep::kMaxInline) {
747 sub_cord.contents_.set_inline_size(new_size);
748 char* dest = sub_cord.contents_.data_.as_chars();
749 Cord::ChunkIterator it = chunk_begin();
750 it.AdvanceBytes(pos);
751 size_t remaining_size = new_size;
752 while (remaining_size > it->size()) {
753 cord_internal::SmallMemmove(dest, it->data(), it->size());
754 remaining_size -= it->size();
755 dest += it->size();
756 ++it;
757 }
758 cord_internal::SmallMemmove(dest, it->data(), remaining_size);
759 return sub_cord;
760 }
761
762 tree = cord_internal::SkipCrcNode(tree);
763 if (tree->IsBtree()) {
764 tree = tree->btree()->SubTree(pos, new_size);
765 } else {
766 tree = CordRepSubstring::Substring(tree, pos, new_size);
767 }
768 sub_cord.contents_.EmplaceTree(tree, contents_.data_,
769 CordzUpdateTracker::kSubCord);
770 return sub_cord;
771 }
772
773 // --------------------------------------------------------------------
774 // Comparators
775
776 namespace {
777
ClampResult(int memcmp_res)778 int ClampResult(int memcmp_res) {
779 return static_cast<int>(memcmp_res > 0) - static_cast<int>(memcmp_res < 0);
780 }
781
CompareChunks(absl::string_view * lhs,absl::string_view * rhs,size_t * size_to_compare)782 int CompareChunks(absl::string_view* lhs, absl::string_view* rhs,
783 size_t* size_to_compare) {
784 size_t compared_size = std::min(lhs->size(), rhs->size());
785 assert(*size_to_compare >= compared_size);
786 *size_to_compare -= compared_size;
787
788 int memcmp_res = ::memcmp(lhs->data(), rhs->data(), compared_size);
789 if (memcmp_res != 0) return memcmp_res;
790
791 lhs->remove_prefix(compared_size);
792 rhs->remove_prefix(compared_size);
793
794 return 0;
795 }
796
797 // This overload set computes comparison results from memcmp result. This
798 // interface is used inside GenericCompare below. Differet implementations
799 // are specialized for int and bool. For int we clamp result to {-1, 0, 1}
800 // set. For bool we just interested in "value == 0".
801 template <typename ResultType>
ComputeCompareResult(int memcmp_res)802 ResultType ComputeCompareResult(int memcmp_res) {
803 return ClampResult(memcmp_res);
804 }
805 template <>
ComputeCompareResult(int memcmp_res)806 bool ComputeCompareResult<bool>(int memcmp_res) {
807 return memcmp_res == 0;
808 }
809
810 } // namespace
811
812 // Helper routine. Locates the first flat or external chunk of the Cord without
813 // initializing the iterator, and returns a string_view referencing the data.
FindFlatStartPiece() const814 inline absl::string_view Cord::InlineRep::FindFlatStartPiece() const {
815 if (!is_tree()) {
816 return absl::string_view(data_.as_chars(), data_.inline_size());
817 }
818
819 CordRep* node = cord_internal::SkipCrcNode(tree());
820 if (node->IsFlat()) {
821 return absl::string_view(node->flat()->Data(), node->length);
822 }
823
824 if (node->IsExternal()) {
825 return absl::string_view(node->external()->base, node->length);
826 }
827
828 if (node->IsBtree()) {
829 CordRepBtree* tree = node->btree();
830 int height = tree->height();
831 while (--height >= 0) {
832 tree = tree->Edge(CordRepBtree::kFront)->btree();
833 }
834 return tree->Data(tree->begin());
835 }
836
837 // Get the child node if we encounter a SUBSTRING.
838 size_t offset = 0;
839 size_t length = node->length;
840 assert(length != 0);
841
842 if (node->IsSubstring()) {
843 offset = node->substring()->start;
844 node = node->substring()->child;
845 }
846
847 if (node->IsFlat()) {
848 return absl::string_view(node->flat()->Data() + offset, length);
849 }
850
851 assert(node->IsExternal() && "Expect FLAT or EXTERNAL node here");
852
853 return absl::string_view(node->external()->base + offset, length);
854 }
855
SetCrcCordState(crc_internal::CrcCordState state)856 void Cord::SetCrcCordState(crc_internal::CrcCordState state) {
857 auto constexpr method = CordzUpdateTracker::kSetExpectedChecksum;
858 if (empty()) {
859 contents_.MaybeRemoveEmptyCrcNode();
860 CordRep* rep = CordRepCrc::New(nullptr, std::move(state));
861 contents_.EmplaceTree(rep, method);
862 } else if (!contents_.is_tree()) {
863 CordRep* rep = contents_.MakeFlatWithExtraCapacity(0);
864 rep = CordRepCrc::New(rep, std::move(state));
865 contents_.EmplaceTree(rep, method);
866 } else {
867 const CordzUpdateScope scope(contents_.data_.cordz_info(), method);
868 CordRep* rep = CordRepCrc::New(contents_.data_.as_tree(), std::move(state));
869 contents_.SetTree(rep, scope);
870 }
871 }
872
SetExpectedChecksum(uint32_t crc)873 void Cord::SetExpectedChecksum(uint32_t crc) {
874 // Construct a CrcCordState with a single chunk.
875 crc_internal::CrcCordState state;
876 state.mutable_rep()->prefix_crc.push_back(
877 crc_internal::CrcCordState::PrefixCrc(size(), absl::crc32c_t{crc}));
878 SetCrcCordState(std::move(state));
879 }
880
MaybeGetCrcCordState() const881 const crc_internal::CrcCordState* Cord::MaybeGetCrcCordState() const {
882 if (!contents_.is_tree() || !contents_.tree()->IsCrc()) {
883 return nullptr;
884 }
885 return &contents_.tree()->crc()->crc_cord_state;
886 }
887
ExpectedChecksum() const888 absl::optional<uint32_t> Cord::ExpectedChecksum() const {
889 if (!contents_.is_tree() || !contents_.tree()->IsCrc()) {
890 return absl::nullopt;
891 }
892 return static_cast<uint32_t>(
893 contents_.tree()->crc()->crc_cord_state.Checksum());
894 }
895
CompareSlowPath(absl::string_view rhs,size_t compared_size,size_t size_to_compare) const896 inline int Cord::CompareSlowPath(absl::string_view rhs, size_t compared_size,
897 size_t size_to_compare) const {
898 auto advance = [](Cord::ChunkIterator* it, absl::string_view* chunk) {
899 if (!chunk->empty()) return true;
900 ++*it;
901 if (it->bytes_remaining_ == 0) return false;
902 *chunk = **it;
903 return true;
904 };
905
906 Cord::ChunkIterator lhs_it = chunk_begin();
907
908 // compared_size is inside first chunk.
909 absl::string_view lhs_chunk =
910 (lhs_it.bytes_remaining_ != 0) ? *lhs_it : absl::string_view();
911 assert(compared_size <= lhs_chunk.size());
912 assert(compared_size <= rhs.size());
913 lhs_chunk.remove_prefix(compared_size);
914 rhs.remove_prefix(compared_size);
915 size_to_compare -= compared_size; // skip already compared size.
916
917 while (advance(&lhs_it, &lhs_chunk) && !rhs.empty()) {
918 int comparison_result = CompareChunks(&lhs_chunk, &rhs, &size_to_compare);
919 if (comparison_result != 0) return comparison_result;
920 if (size_to_compare == 0) return 0;
921 }
922
923 return static_cast<int>(rhs.empty()) - static_cast<int>(lhs_chunk.empty());
924 }
925
CompareSlowPath(const Cord & rhs,size_t compared_size,size_t size_to_compare) const926 inline int Cord::CompareSlowPath(const Cord& rhs, size_t compared_size,
927 size_t size_to_compare) const {
928 auto advance = [](Cord::ChunkIterator* it, absl::string_view* chunk) {
929 if (!chunk->empty()) return true;
930 ++*it;
931 if (it->bytes_remaining_ == 0) return false;
932 *chunk = **it;
933 return true;
934 };
935
936 Cord::ChunkIterator lhs_it = chunk_begin();
937 Cord::ChunkIterator rhs_it = rhs.chunk_begin();
938
939 // compared_size is inside both first chunks.
940 absl::string_view lhs_chunk =
941 (lhs_it.bytes_remaining_ != 0) ? *lhs_it : absl::string_view();
942 absl::string_view rhs_chunk =
943 (rhs_it.bytes_remaining_ != 0) ? *rhs_it : absl::string_view();
944 assert(compared_size <= lhs_chunk.size());
945 assert(compared_size <= rhs_chunk.size());
946 lhs_chunk.remove_prefix(compared_size);
947 rhs_chunk.remove_prefix(compared_size);
948 size_to_compare -= compared_size; // skip already compared size.
949
950 while (advance(&lhs_it, &lhs_chunk) && advance(&rhs_it, &rhs_chunk)) {
951 int memcmp_res = CompareChunks(&lhs_chunk, &rhs_chunk, &size_to_compare);
952 if (memcmp_res != 0) return memcmp_res;
953 if (size_to_compare == 0) return 0;
954 }
955
956 return static_cast<int>(rhs_chunk.empty()) -
957 static_cast<int>(lhs_chunk.empty());
958 }
959
GetFirstChunk(const Cord & c)960 inline absl::string_view Cord::GetFirstChunk(const Cord& c) {
961 if (c.empty()) return {};
962 return c.contents_.FindFlatStartPiece();
963 }
GetFirstChunk(absl::string_view sv)964 inline absl::string_view Cord::GetFirstChunk(absl::string_view sv) {
965 return sv;
966 }
967
968 // Compares up to 'size_to_compare' bytes of 'lhs' with 'rhs'. It is assumed
969 // that 'size_to_compare' is greater that size of smallest of first chunks.
970 template <typename ResultType, typename RHS>
GenericCompare(const Cord & lhs,const RHS & rhs,size_t size_to_compare)971 ResultType GenericCompare(const Cord& lhs, const RHS& rhs,
972 size_t size_to_compare) {
973 absl::string_view lhs_chunk = Cord::GetFirstChunk(lhs);
974 absl::string_view rhs_chunk = Cord::GetFirstChunk(rhs);
975
976 size_t compared_size = std::min(lhs_chunk.size(), rhs_chunk.size());
977 assert(size_to_compare >= compared_size);
978 int memcmp_res = ::memcmp(lhs_chunk.data(), rhs_chunk.data(), compared_size);
979 if (compared_size == size_to_compare || memcmp_res != 0) {
980 return ComputeCompareResult<ResultType>(memcmp_res);
981 }
982
983 return ComputeCompareResult<ResultType>(
984 lhs.CompareSlowPath(rhs, compared_size, size_to_compare));
985 }
986
EqualsImpl(absl::string_view rhs,size_t size_to_compare) const987 bool Cord::EqualsImpl(absl::string_view rhs, size_t size_to_compare) const {
988 return GenericCompare<bool>(*this, rhs, size_to_compare);
989 }
990
EqualsImpl(const Cord & rhs,size_t size_to_compare) const991 bool Cord::EqualsImpl(const Cord& rhs, size_t size_to_compare) const {
992 return GenericCompare<bool>(*this, rhs, size_to_compare);
993 }
994
995 template <typename RHS>
SharedCompareImpl(const Cord & lhs,const RHS & rhs)996 inline int SharedCompareImpl(const Cord& lhs, const RHS& rhs) {
997 size_t lhs_size = lhs.size();
998 size_t rhs_size = rhs.size();
999 if (lhs_size == rhs_size) {
1000 return GenericCompare<int>(lhs, rhs, lhs_size);
1001 }
1002 if (lhs_size < rhs_size) {
1003 auto data_comp_res = GenericCompare<int>(lhs, rhs, lhs_size);
1004 return data_comp_res == 0 ? -1 : data_comp_res;
1005 }
1006
1007 auto data_comp_res = GenericCompare<int>(lhs, rhs, rhs_size);
1008 return data_comp_res == 0 ? +1 : data_comp_res;
1009 }
1010
Compare(absl::string_view rhs) const1011 int Cord::Compare(absl::string_view rhs) const {
1012 return SharedCompareImpl(*this, rhs);
1013 }
1014
CompareImpl(const Cord & rhs) const1015 int Cord::CompareImpl(const Cord& rhs) const {
1016 return SharedCompareImpl(*this, rhs);
1017 }
1018
EndsWith(absl::string_view rhs) const1019 bool Cord::EndsWith(absl::string_view rhs) const {
1020 size_t my_size = size();
1021 size_t rhs_size = rhs.size();
1022
1023 if (my_size < rhs_size) return false;
1024
1025 Cord tmp(*this);
1026 tmp.RemovePrefix(my_size - rhs_size);
1027 return tmp.EqualsImpl(rhs, rhs_size);
1028 }
1029
EndsWith(const Cord & rhs) const1030 bool Cord::EndsWith(const Cord& rhs) const {
1031 size_t my_size = size();
1032 size_t rhs_size = rhs.size();
1033
1034 if (my_size < rhs_size) return false;
1035
1036 Cord tmp(*this);
1037 tmp.RemovePrefix(my_size - rhs_size);
1038 return tmp.EqualsImpl(rhs, rhs_size);
1039 }
1040
1041 // --------------------------------------------------------------------
1042 // Misc.
1043
operator std::string() const1044 Cord::operator std::string() const {
1045 std::string s;
1046 absl::CopyCordToString(*this, &s);
1047 return s;
1048 }
1049
CopyCordToString(const Cord & src,std::string * dst)1050 void CopyCordToString(const Cord& src, std::string* dst) {
1051 if (!src.contents_.is_tree()) {
1052 src.contents_.CopyTo(dst);
1053 } else {
1054 absl::strings_internal::STLStringResizeUninitialized(dst, src.size());
1055 src.CopyToArraySlowPath(&(*dst)[0]);
1056 }
1057 }
1058
CopyToArraySlowPath(char * dst) const1059 void Cord::CopyToArraySlowPath(char* dst) const {
1060 assert(contents_.is_tree());
1061 absl::string_view fragment;
1062 if (GetFlatAux(contents_.tree(), &fragment)) {
1063 memcpy(dst, fragment.data(), fragment.size());
1064 return;
1065 }
1066 for (absl::string_view chunk : Chunks()) {
1067 memcpy(dst, chunk.data(), chunk.size());
1068 dst += chunk.size();
1069 }
1070 }
1071
AdvanceAndReadBytes(size_t n)1072 Cord Cord::ChunkIterator::AdvanceAndReadBytes(size_t n) {
1073 ABSL_HARDENING_ASSERT(bytes_remaining_ >= n &&
1074 "Attempted to iterate past `end()`");
1075 Cord subcord;
1076 auto constexpr method = CordzUpdateTracker::kCordReader;
1077
1078 if (n <= InlineRep::kMaxInline) {
1079 // Range to read fits in inline data. Flatten it.
1080 char* data = subcord.contents_.set_data(n);
1081 while (n > current_chunk_.size()) {
1082 memcpy(data, current_chunk_.data(), current_chunk_.size());
1083 data += current_chunk_.size();
1084 n -= current_chunk_.size();
1085 ++*this;
1086 }
1087 memcpy(data, current_chunk_.data(), n);
1088 if (n < current_chunk_.size()) {
1089 RemoveChunkPrefix(n);
1090 } else if (n > 0) {
1091 ++*this;
1092 }
1093 return subcord;
1094 }
1095
1096 if (btree_reader_) {
1097 size_t chunk_size = current_chunk_.size();
1098 if (n <= chunk_size && n <= kMaxBytesToCopy) {
1099 subcord = Cord(current_chunk_.substr(0, n), method);
1100 if (n < chunk_size) {
1101 current_chunk_.remove_prefix(n);
1102 } else {
1103 current_chunk_ = btree_reader_.Next();
1104 }
1105 } else {
1106 CordRep* rep;
1107 current_chunk_ = btree_reader_.Read(n, chunk_size, rep);
1108 subcord.contents_.EmplaceTree(rep, method);
1109 }
1110 bytes_remaining_ -= n;
1111 return subcord;
1112 }
1113
1114 // Short circuit if reading the entire data edge.
1115 assert(current_leaf_ != nullptr);
1116 if (n == current_leaf_->length) {
1117 bytes_remaining_ = 0;
1118 current_chunk_ = {};
1119 CordRep* tree = CordRep::Ref(current_leaf_);
1120 subcord.contents_.EmplaceTree(VerifyTree(tree), method);
1121 return subcord;
1122 }
1123
1124 // From this point on, we need a partial substring node.
1125 // Get pointer to the underlying flat or external data payload and
1126 // compute data pointer and offset into current flat or external.
1127 CordRep* payload = current_leaf_->IsSubstring()
1128 ? current_leaf_->substring()->child
1129 : current_leaf_;
1130 const char* data = payload->IsExternal() ? payload->external()->base
1131 : payload->flat()->Data();
1132 const size_t offset = static_cast<size_t>(current_chunk_.data() - data);
1133
1134 auto* tree = CordRepSubstring::Substring(payload, offset, n);
1135 subcord.contents_.EmplaceTree(VerifyTree(tree), method);
1136 bytes_remaining_ -= n;
1137 current_chunk_.remove_prefix(n);
1138 return subcord;
1139 }
1140
operator [](size_t i) const1141 char Cord::operator[](size_t i) const {
1142 ABSL_HARDENING_ASSERT(i < size());
1143 size_t offset = i;
1144 const CordRep* rep = contents_.tree();
1145 if (rep == nullptr) {
1146 return contents_.data()[i];
1147 }
1148 rep = cord_internal::SkipCrcNode(rep);
1149 while (true) {
1150 assert(rep != nullptr);
1151 assert(offset < rep->length);
1152 if (rep->IsFlat()) {
1153 // Get the "i"th character directly from the flat array.
1154 return rep->flat()->Data()[offset];
1155 } else if (rep->IsBtree()) {
1156 return rep->btree()->GetCharacter(offset);
1157 } else if (rep->IsExternal()) {
1158 // Get the "i"th character from the external array.
1159 return rep->external()->base[offset];
1160 } else {
1161 // This must be a substring a node, so bypass it to get to the child.
1162 assert(rep->IsSubstring());
1163 offset += rep->substring()->start;
1164 rep = rep->substring()->child;
1165 }
1166 }
1167 }
1168
FlattenSlowPath()1169 absl::string_view Cord::FlattenSlowPath() {
1170 assert(contents_.is_tree());
1171 size_t total_size = size();
1172 CordRep* new_rep;
1173 char* new_buffer;
1174
1175 // Try to put the contents into a new flat rep. If they won't fit in the
1176 // biggest possible flat node, use an external rep instead.
1177 if (total_size <= kMaxFlatLength) {
1178 new_rep = CordRepFlat::New(total_size);
1179 new_rep->length = total_size;
1180 new_buffer = new_rep->flat()->Data();
1181 CopyToArraySlowPath(new_buffer);
1182 } else {
1183 new_buffer = std::allocator<char>().allocate(total_size);
1184 CopyToArraySlowPath(new_buffer);
1185 new_rep = absl::cord_internal::NewExternalRep(
1186 absl::string_view(new_buffer, total_size), [](absl::string_view s) {
1187 std::allocator<char>().deallocate(const_cast<char*>(s.data()),
1188 s.size());
1189 });
1190 }
1191 CordzUpdateScope scope(contents_.cordz_info(), CordzUpdateTracker::kFlatten);
1192 CordRep::Unref(contents_.as_tree());
1193 contents_.SetTree(new_rep, scope);
1194 return absl::string_view(new_buffer, total_size);
1195 }
1196
GetFlatAux(CordRep * rep,absl::string_view * fragment)1197 /* static */ bool Cord::GetFlatAux(CordRep* rep, absl::string_view* fragment) {
1198 assert(rep != nullptr);
1199 if (rep->length == 0) {
1200 *fragment = absl::string_view();
1201 return true;
1202 }
1203 rep = cord_internal::SkipCrcNode(rep);
1204 if (rep->IsFlat()) {
1205 *fragment = absl::string_view(rep->flat()->Data(), rep->length);
1206 return true;
1207 } else if (rep->IsExternal()) {
1208 *fragment = absl::string_view(rep->external()->base, rep->length);
1209 return true;
1210 } else if (rep->IsBtree()) {
1211 return rep->btree()->IsFlat(fragment);
1212 } else if (rep->IsSubstring()) {
1213 CordRep* child = rep->substring()->child;
1214 if (child->IsFlat()) {
1215 *fragment = absl::string_view(
1216 child->flat()->Data() + rep->substring()->start, rep->length);
1217 return true;
1218 } else if (child->IsExternal()) {
1219 *fragment = absl::string_view(
1220 child->external()->base + rep->substring()->start, rep->length);
1221 return true;
1222 } else if (child->IsBtree()) {
1223 return child->btree()->IsFlat(rep->substring()->start, rep->length,
1224 fragment);
1225 }
1226 }
1227 return false;
1228 }
1229
ForEachChunkAux(absl::cord_internal::CordRep * rep,absl::FunctionRef<void (absl::string_view)> callback)1230 /* static */ void Cord::ForEachChunkAux(
1231 absl::cord_internal::CordRep* rep,
1232 absl::FunctionRef<void(absl::string_view)> callback) {
1233 assert(rep != nullptr);
1234 if (rep->length == 0) return;
1235 rep = cord_internal::SkipCrcNode(rep);
1236
1237 if (rep->IsBtree()) {
1238 ChunkIterator it(rep), end;
1239 while (it != end) {
1240 callback(*it);
1241 ++it;
1242 }
1243 return;
1244 }
1245
1246 // This is a leaf node, so invoke our callback.
1247 absl::cord_internal::CordRep* current_node = cord_internal::SkipCrcNode(rep);
1248 absl::string_view chunk;
1249 bool success = GetFlatAux(current_node, &chunk);
1250 assert(success);
1251 if (success) {
1252 callback(chunk);
1253 }
1254 }
1255
DumpNode(CordRep * rep,bool include_data,std::ostream * os,int indent)1256 static void DumpNode(CordRep* rep, bool include_data, std::ostream* os,
1257 int indent) {
1258 const int kIndentStep = 1;
1259 absl::InlinedVector<CordRep*, kInlinedVectorSize> stack;
1260 absl::InlinedVector<int, kInlinedVectorSize> indents;
1261 for (;;) {
1262 *os << std::setw(3) << rep->refcount.Get();
1263 *os << " " << std::setw(7) << rep->length;
1264 *os << " [";
1265 if (include_data) *os << static_cast<void*>(rep);
1266 *os << "]";
1267 *os << " " << std::setw(indent) << "";
1268 bool leaf = false;
1269 if (rep == nullptr) {
1270 *os << "NULL\n";
1271 leaf = true;
1272 } else if (rep->IsCrc()) {
1273 *os << "CRC crc=" << rep->crc()->crc_cord_state.Checksum() << "\n";
1274 indent += kIndentStep;
1275 rep = rep->crc()->child;
1276 } else if (rep->IsSubstring()) {
1277 *os << "SUBSTRING @ " << rep->substring()->start << "\n";
1278 indent += kIndentStep;
1279 rep = rep->substring()->child;
1280 } else { // Leaf or ring
1281 leaf = true;
1282 if (rep->IsExternal()) {
1283 *os << "EXTERNAL [";
1284 if (include_data)
1285 *os << absl::CEscape(std::string(rep->external()->base, rep->length));
1286 *os << "]\n";
1287 } else if (rep->IsFlat()) {
1288 *os << "FLAT cap=" << rep->flat()->Capacity() << " [";
1289 if (include_data)
1290 *os << absl::CEscape(std::string(rep->flat()->Data(), rep->length));
1291 *os << "]\n";
1292 } else {
1293 CordRepBtree::Dump(rep, /*label=*/ "", include_data, *os);
1294 }
1295 }
1296 if (leaf) {
1297 if (stack.empty()) break;
1298 rep = stack.back();
1299 stack.pop_back();
1300 indent = indents.back();
1301 indents.pop_back();
1302 }
1303 }
1304 ABSL_INTERNAL_CHECK(indents.empty(), "");
1305 }
1306
ReportError(CordRep * root,CordRep * node)1307 static std::string ReportError(CordRep* root, CordRep* node) {
1308 std::ostringstream buf;
1309 buf << "Error at node " << node << " in:";
1310 DumpNode(root, true, &buf);
1311 return buf.str();
1312 }
1313
VerifyNode(CordRep * root,CordRep * start_node,bool)1314 static bool VerifyNode(CordRep* root, CordRep* start_node,
1315 bool /* full_validation */) {
1316 absl::InlinedVector<CordRep*, 2> worklist;
1317 worklist.push_back(start_node);
1318 do {
1319 CordRep* node = worklist.back();
1320 worklist.pop_back();
1321
1322 ABSL_INTERNAL_CHECK(node != nullptr, ReportError(root, node));
1323 if (node != root) {
1324 ABSL_INTERNAL_CHECK(node->length != 0, ReportError(root, node));
1325 ABSL_INTERNAL_CHECK(!node->IsCrc(), ReportError(root, node));
1326 }
1327
1328 if (node->IsFlat()) {
1329 ABSL_INTERNAL_CHECK(node->length <= node->flat()->Capacity(),
1330 ReportError(root, node));
1331 } else if (node->IsExternal()) {
1332 ABSL_INTERNAL_CHECK(node->external()->base != nullptr,
1333 ReportError(root, node));
1334 } else if (node->IsSubstring()) {
1335 ABSL_INTERNAL_CHECK(
1336 node->substring()->start < node->substring()->child->length,
1337 ReportError(root, node));
1338 ABSL_INTERNAL_CHECK(node->substring()->start + node->length <=
1339 node->substring()->child->length,
1340 ReportError(root, node));
1341 } else if (node->IsCrc()) {
1342 ABSL_INTERNAL_CHECK(
1343 node->crc()->child != nullptr || node->crc()->length == 0,
1344 ReportError(root, node));
1345 if (node->crc()->child != nullptr) {
1346 ABSL_INTERNAL_CHECK(node->crc()->length == node->crc()->child->length,
1347 ReportError(root, node));
1348 worklist.push_back(node->crc()->child);
1349 }
1350 }
1351 } while (!worklist.empty());
1352 return true;
1353 }
1354
operator <<(std::ostream & out,const Cord & cord)1355 std::ostream& operator<<(std::ostream& out, const Cord& cord) {
1356 for (absl::string_view chunk : cord.Chunks()) {
1357 out.write(chunk.data(), static_cast<std::streamsize>(chunk.size()));
1358 }
1359 return out;
1360 }
1361
1362 namespace strings_internal {
FlatOverhead()1363 size_t CordTestAccess::FlatOverhead() { return cord_internal::kFlatOverhead; }
MaxFlatLength()1364 size_t CordTestAccess::MaxFlatLength() { return cord_internal::kMaxFlatLength; }
FlatTagToLength(uint8_t tag)1365 size_t CordTestAccess::FlatTagToLength(uint8_t tag) {
1366 return cord_internal::TagToLength(tag);
1367 }
LengthToTag(size_t s)1368 uint8_t CordTestAccess::LengthToTag(size_t s) {
1369 ABSL_INTERNAL_CHECK(s <= kMaxFlatLength, absl::StrCat("Invalid length ", s));
1370 return cord_internal::AllocatedSizeToTag(s + cord_internal::kFlatOverhead);
1371 }
SizeofCordRepExternal()1372 size_t CordTestAccess::SizeofCordRepExternal() {
1373 return sizeof(CordRepExternal);
1374 }
SizeofCordRepSubstring()1375 size_t CordTestAccess::SizeofCordRepSubstring() {
1376 return sizeof(CordRepSubstring);
1377 }
1378 } // namespace strings_internal
1379 ABSL_NAMESPACE_END
1380 } // namespace absl
1381