Coverage Report

Created: 2026-07-25 06:24

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