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