Coverage Report

Created: 2026-11-12 06:42

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/proc/self/cwd/common/internal/byte_string.cc
Line
Count
Source
1
// Copyright 2024 Google LLC
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 "common/internal/byte_string.h"
16
17
#include <algorithm>
18
#include <cstddef>
19
#include <cstring>
20
#include <optional>
21
#include <string>
22
#include <utility>
23
24
#include "absl/base/nullability.h"
25
#include "absl/base/optimization.h"
26
#include "absl/functional/overload.h"
27
#include "absl/log/absl_check.h"
28
#include "absl/strings/cord.h"
29
#include "absl/strings/resize_and_overwrite.h"
30
#include "absl/strings/string_view.h"
31
#include "absl/types/optional.h"
32
#include "common/internal/value_arena_ptr.h"
33
#include "common/internal/value_arena_ptr_tag.h"
34
#include "google/protobuf/arena.h"
35
36
namespace cel::common_internal {
37
38
ByteString ByteString::From(absl::string_view value,
39
13.1k
                            google::protobuf::Arena* absl_nonnull arena) {
40
13.1k
  ABSL_DCHECK(arena != nullptr);
41
13.1k
  ByteString result(UninitializedTag{});
42
13.1k
  if (value.size() <= kSmallByteStringCapacity) {
43
11.4k
    result.SetSmall(value);
44
11.4k
  } else {
45
1.72k
    char* arena_value =
46
1.72k
        reinterpret_cast<char*>(arena->AllocateAligned(value.size()));
47
1.72k
    std::memcpy(arena_value, value.data(), value.size());
48
1.72k
    result.SetMedium(arena, absl::string_view(arena_value, value.size()));
49
1.72k
  }
50
13.1k
  return result;
51
13.1k
}
52
53
ByteString ByteString::From(absl::Cord value,
54
0
                            google::protobuf::Arena* absl_nonnull arena) {
55
0
  ABSL_DCHECK(arena != nullptr);
56
0
  ByteString result(UninitializedTag{});
57
0
  if (value.size() <= kSmallByteStringCapacity) {
58
0
    result.SetSmall(value);
59
0
  } else {
60
0
    result.SetLarge(arena,
61
0
                    google::protobuf::Arena::Create<absl::Cord>(arena, std::move(value)));
62
0
  }
63
0
  return result;
64
0
}
65
66
ByteString ByteString::From(std::string&& value,
67
1.44k
                            google::protobuf::Arena* absl_nonnull arena) {
68
1.44k
  ABSL_DCHECK(arena != nullptr);
69
1.44k
  ByteString result(UninitializedTag{});
70
1.44k
  if (value.size() <= kSmallByteStringCapacity) {
71
1.44k
    result.SetSmall(value);
72
1.44k
  } else if (value.size() > sizeof(std::string)) {
73
0
    value.shrink_to_fit();
74
0
    result.SetMedium(
75
0
        arena, google::protobuf::Arena::Create<std::string>(arena, std::move(value)));
76
0
  } else {
77
0
    char* arena_value =
78
0
        reinterpret_cast<char*>(arena->AllocateAligned(value.size()));
79
0
    std::memcpy(arena_value, value.data(), value.size());
80
0
    result.SetMedium(arena, absl::string_view(arena_value, value.size()));
81
0
  }
82
1.44k
  return result;
83
1.44k
}
84
85
ByteString ByteString::Concat(const ByteString& lhs, const ByteString& rhs,
86
5.73k
                              google::protobuf::Arena* absl_nonnull arena) {
87
5.73k
  ABSL_DCHECK(arena != nullptr);
88
89
5.73k
  if (lhs.empty()) {
90
939
    return rhs;
91
939
  }
92
4.79k
  if (rhs.empty()) {
93
825
    return lhs;
94
825
  }
95
96
3.97k
  if (lhs.GetKind() == ByteStringKind::kLarge ||
97
3.97k
      rhs.GetKind() == ByteStringKind::kLarge) {
98
    // If either the left or right are absl::Cord, use absl::Cord.
99
0
    absl::Cord result;
100
0
    lhs.AppendToCord(&result);
101
0
    rhs.AppendToCord(&result);
102
0
    return From(result, arena);
103
0
  }
104
105
3.97k
  const size_t lhs_size = lhs.size();
106
3.97k
  const size_t rhs_size = rhs.size();
107
3.97k
  const size_t result_size = lhs_size + rhs_size;
108
3.97k
  ByteString result(UninitializedTag{});
109
3.97k
  if (result_size <= kSmallByteStringCapacity) {
110
    // If the resulting string fits in inline storage, do it.
111
3.02k
    result.rep_.header.kind = ByteStringKind::kSmall;
112
3.02k
    result.rep_.small.size = result_size;
113
3.02k
    lhs.CopyToArray(result.rep_.small.data);
114
3.02k
    rhs.CopyToArray(result.rep_.small.data + lhs_size);
115
3.02k
  } else {
116
    // Otherwise allocate on the arena.
117
945
    char* result_data =
118
945
        reinterpret_cast<char*>(arena->AllocateAligned(result_size));
119
945
    lhs.CopyToArray(result_data);
120
945
    rhs.CopyToArray(result_data + lhs_size);
121
945
    result.rep_.header.kind = ByteStringKind::kMedium;
122
945
    result.rep_.medium.data = result_data;
123
945
    result.rep_.medium.size = result_size;
124
945
    result.rep_.medium.arena = arena;
125
945
  }
126
3.97k
  return result;
127
3.97k
}
128
129
0
absl::optional<absl::string_view> ByteString::TryFlat() const {
130
0
  switch (GetKind()) {
131
0
    case ByteStringKind::kSmall:
132
0
      return GetSmall();
133
0
    case ByteStringKind::kMedium:
134
0
      return GetMedium();
135
0
    case ByteStringKind::kLarge: {
136
0
      if (auto flat = rep_.large.data->TryFlat(); flat.has_value()) {
137
0
        return flat->substr(rep_.large.offset, rep_.large.size);
138
0
      }
139
0
      return std::nullopt;
140
0
    }
141
0
  }
142
0
}
143
144
absl::optional<size_t> ByteString::Find(absl::string_view needle,
145
0
                                        size_t pos) const {
146
0
  ABSL_DCHECK_LE(pos, size());
147
148
0
  return Visit(absl::Overload(
149
0
      [&needle, pos](absl::string_view lhs) -> absl::optional<size_t> {
150
0
        absl::string_view::size_type i = lhs.find(needle, pos);
151
0
        if (i == absl::string_view::npos) {
152
0
          return std::nullopt;
153
0
        }
154
0
        return i;
155
0
      },
156
0
      [&needle, pos](const absl::Cord& lhs) -> absl::optional<size_t> {
157
0
        absl::Cord cord = lhs.Subcord(pos, lhs.size() - pos);
158
0
        absl::Cord::CharIterator it = cord.Find(needle);
159
0
        if (it == cord.char_end()) {
160
0
          return std::nullopt;
161
0
        }
162
0
        return pos +
163
0
               static_cast<size_t>(absl::Cord::Distance(cord.char_begin(), it));
164
0
      }));
165
0
}
166
167
absl::optional<size_t> ByteString::Find(const absl::Cord& needle,
168
0
                                        size_t pos) const {
169
0
  ABSL_DCHECK_LE(pos, size());
170
171
0
  return Visit(absl::Overload(
172
0
      [&needle, pos](absl::string_view lhs) -> absl::optional<size_t> {
173
0
        if (auto flat_needle = needle.TryFlat(); flat_needle) {
174
0
          absl::string_view::size_type i = lhs.find(*flat_needle, pos);
175
0
          if (i == absl::string_view::npos) {
176
0
            return std::nullopt;
177
0
          }
178
0
          return i;
179
0
        }
180
        // Needle is fragmented, we have to do a linear scan.
181
0
        const size_t needle_size = needle.size();
182
0
        if (pos + needle_size > lhs.size()) {
183
0
          return std::nullopt;
184
0
        }
185
0
        if (ABSL_PREDICT_FALSE(needle_size == 0)) {
186
0
          return pos;
187
0
        }
188
        // Optimization: find the first chunk of the needle, then compare the
189
        // rest. If the first chunk is empty, `lhs.find` will return
190
        // `current_pos`, which correctly degrades to a linear scan.
191
0
        absl::string_view first_chunk = *needle.Chunks().begin();
192
0
        absl::Cord rest_of_needle = needle.Subcord(
193
0
            first_chunk.size(), needle_size - first_chunk.size());
194
0
        size_t current_pos = pos;
195
0
        while (true) {
196
0
          size_t found_pos = lhs.find(first_chunk, current_pos);
197
0
          if (found_pos == absl::string_view::npos ||
198
0
              found_pos > lhs.size() - needle_size) {
199
0
            return std::nullopt;
200
0
          }
201
0
          if (lhs.substr(found_pos + first_chunk.size(),
202
0
                         rest_of_needle.size()) == rest_of_needle) {
203
0
            return found_pos;
204
0
          }
205
0
          current_pos = found_pos + 1;
206
0
        }
207
0
      },
208
0
      [&needle, pos](const absl::Cord& lhs) -> absl::optional<size_t> {
209
0
        absl::Cord cord = lhs.Subcord(pos, lhs.size() - pos);
210
0
        absl::Cord::CharIterator it = cord.Find(needle);
211
0
        if (it == cord.char_end()) {
212
0
          return std::nullopt;
213
0
        }
214
0
        return pos +
215
0
               static_cast<size_t>(absl::Cord::Distance(cord.char_begin(), it));
216
0
      }));
217
0
}
218
219
0
ByteString ByteString::Substring(size_t pos, size_t npos) const {
220
0
  ABSL_DCHECK_LE(npos, size());
221
0
  ABSL_DCHECK_LE(pos, npos);
222
223
0
  switch (GetKind()) {
224
0
    case ByteStringKind::kSmall: {
225
0
      ByteString result(UninitializedTag{});
226
0
      result.SetSmall(GetSmall().substr(pos, npos - pos));
227
0
      return result;
228
0
    }
229
0
    case ByteStringKind::kMedium: {
230
0
      ByteString result(UninitializedTag{});
231
0
      result.SetMedium(GetMediumArena(), GetMedium().substr(pos, npos - pos));
232
0
      return result;
233
0
    }
234
0
    case ByteStringKind::kLarge:
235
0
      ByteString result(UninitializedTag{});
236
0
      result.SetLarge(GetLargeArena(), rep_.large.data, rep_.large.offset + pos,
237
0
                      npos - pos);
238
0
      return result;
239
0
  }
240
0
}
241
242
0
void ByteString::RemovePrefix(size_t n) {
243
0
  ABSL_DCHECK_LE(n, size());
244
0
  if (n == 0) {
245
0
    return;
246
0
  }
247
0
  switch (GetKind()) {
248
0
    case ByteStringKind::kSmall:
249
0
      std::memmove(rep_.small.data, rep_.small.data + n, rep_.small.size - n);
250
0
      rep_.small.size = rep_.small.size - n;
251
0
      break;
252
0
    case ByteStringKind::kMedium:
253
0
      rep_.medium.data = rep_.medium.data + n;
254
0
      rep_.medium.size = rep_.medium.size - n;
255
0
      break;
256
0
    case ByteStringKind::kLarge:
257
0
      rep_.large.offset = rep_.large.offset + n;
258
0
      rep_.large.size = rep_.large.size - n;
259
0
      break;
260
0
  }
261
0
}
262
263
0
void ByteString::RemoveSuffix(size_t n) {
264
0
  ABSL_DCHECK_LE(n, size());
265
0
  if (n == 0) {
266
0
    return;
267
0
  }
268
0
  switch (GetKind()) {
269
0
    case ByteStringKind::kSmall:
270
0
      rep_.small.size = rep_.small.size - n;
271
0
      break;
272
0
    case ByteStringKind::kMedium:
273
0
      rep_.medium.size = rep_.medium.size - n;
274
0
      break;
275
0
    case ByteStringKind::kLarge:
276
0
      rep_.large.size = rep_.large.size - n;
277
0
      break;
278
0
  }
279
0
}
280
281
7.94k
void ByteString::CopyToArray(char* absl_nonnull out) const {
282
7.94k
  ABSL_DCHECK(out != nullptr);
283
7.94k
  switch (GetKind()) {
284
6.95k
    case ByteStringKind::kSmall: {
285
6.95k
      absl::string_view small = GetSmall();
286
6.95k
      std::memcpy(out, small.data(), small.size());
287
6.95k
    } break;
288
986
    case ByteStringKind::kMedium: {
289
986
      absl::string_view medium = GetMedium();
290
986
      std::memcpy(out, medium.data(), medium.size());
291
986
    } break;
292
0
    case ByteStringKind::kLarge: {
293
0
      (CopyCordToArray)(*rep_.large.data, rep_.large.offset, rep_.large.size,
294
0
                        out);
295
0
    } break;
296
7.94k
  }
297
7.94k
}
298
299
384k
std::string ByteString::ToString() const {
300
384k
  switch (GetKind()) {
301
317k
    case ByteStringKind::kSmall:
302
317k
      return std::string(GetSmall());
303
66.8k
    case ByteStringKind::kMedium:
304
66.8k
      return std::string(GetMedium());
305
0
    case ByteStringKind::kLarge: {
306
0
      std::string result;
307
0
      absl::StringResizeAndOverwrite(
308
0
          result, rep_.large.size,
309
0
          [this](char* buffer, size_t buffer_size) -> size_t {
310
0
            (CopyCordToArray)(*rep_.large.data, rep_.large.offset,
311
0
                              rep_.large.size, buffer);
312
0
            return rep_.large.size;
313
0
          });
314
0
      return result;
315
0
    }
316
384k
  }
317
384k
}
318
319
0
void ByteString::CopyToString(std::string* absl_nonnull out) const {
320
0
  ABSL_DCHECK(out != nullptr);
321
0
  switch (GetKind()) {
322
0
    case ByteStringKind::kSmall:
323
0
      out->assign(GetSmall());
324
0
      break;
325
0
    case ByteStringKind::kMedium:
326
0
      out->assign(GetMedium());
327
0
      break;
328
0
    case ByteStringKind::kLarge:
329
0
      absl::StringResizeAndOverwrite(
330
0
          *out, rep_.large.size,
331
0
          [this](char* buffer, size_t buffer_size) -> size_t {
332
0
            CopyCordToArray(*rep_.large.data, rep_.large.offset,
333
0
                            rep_.large.size, buffer);
334
0
            return rep_.large.size;
335
0
          });
336
0
      break;
337
0
  }
338
0
}
339
340
0
void ByteString::AppendToString(std::string* absl_nonnull out) const {
341
0
  ABSL_DCHECK(out != nullptr);
342
0
  switch (GetKind()) {
343
0
    case ByteStringKind::kSmall:
344
0
      out->append(GetSmall());
345
0
      break;
346
0
    case ByteStringKind::kMedium:
347
0
      out->append(GetMedium());
348
0
      break;
349
0
    case ByteStringKind::kLarge:
350
0
      AppendCordToString(*rep_.large.data, rep_.large.offset, rep_.large.size,
351
0
                         *out);
352
0
      break;
353
0
  }
354
0
}
355
356
0
absl::Cord ByteString::ToCord() const {
357
0
  switch (GetKind()) {
358
0
    case ByteStringKind::kSmall:
359
0
      return absl::Cord(GetSmall());
360
0
    case ByteStringKind::kMedium:
361
0
      return absl::Cord(GetMedium());
362
0
    case ByteStringKind::kLarge:
363
0
      return GetLarge();
364
0
  }
365
0
}
366
367
0
void ByteString::CopyToCord(absl::Cord* absl_nonnull out) const {
368
0
  ABSL_DCHECK(out != nullptr);
369
0
  switch (GetKind()) {
370
0
    case ByteStringKind::kSmall:
371
0
      *out = absl::Cord(GetSmall());
372
0
      break;
373
0
    case ByteStringKind::kMedium:
374
0
      *out = absl::Cord(GetMedium());
375
0
      break;
376
0
    case ByteStringKind::kLarge:
377
0
      *out = GetLarge();
378
0
      break;
379
0
  }
380
0
}
381
382
0
void ByteString::AppendToCord(absl::Cord* absl_nonnull out) const {
383
0
  ABSL_DCHECK(out != nullptr);
384
0
  switch (GetKind()) {
385
0
    case ByteStringKind::kSmall:
386
0
      out->Append(GetSmall());
387
0
      break;
388
0
    case ByteStringKind::kMedium:
389
0
      out->Append(GetMedium());
390
0
      break;
391
0
    case ByteStringKind::kLarge:
392
0
      out->Append(GetLarge());
393
0
      break;
394
0
  }
395
0
}
396
397
absl::string_view ByteString::ToStringView(
398
9.89k
    std::string* absl_nonnull scratch) const {
399
9.89k
  ABSL_DCHECK(scratch != nullptr);
400
9.89k
  switch (GetKind()) {
401
417
    case ByteStringKind::kSmall:
402
417
      return GetSmall();
403
9.48k
    case ByteStringKind::kMedium:
404
9.48k
      return GetMedium();
405
0
    case ByteStringKind::kLarge:
406
0
      if (auto flat = rep_.large.data->TryFlat(); flat.has_value()) {
407
0
        return flat->substr(rep_.large.offset, rep_.large.size);
408
0
      }
409
0
      absl::StringResizeAndOverwrite(
410
0
          *scratch, rep_.large.size,
411
0
          [this](char* buffer, size_t buffer_size) -> size_t {
412
0
            CopyCordToArray(*rep_.large.data, rep_.large.offset,
413
0
                            rep_.large.size, buffer);
414
0
            return rep_.large.size;
415
0
          });
416
0
      return absl::string_view(*scratch);
417
9.89k
  }
418
9.89k
}
419
420
0
ByteString ByteString::Clone(google::protobuf::Arena* absl_nonnull arena) const {
421
0
  ABSL_DCHECK(arena != nullptr);
422
0
  switch (GetKind()) {
423
0
    case ByteStringKind::kSmall: {
424
0
      ByteString result(UninitializedTag{});
425
0
      result.SetSmall(GetSmall());
426
0
      return result;
427
0
    }
428
0
    case ByteStringKind::kMedium: {
429
0
      ValueArenaPtr other_arena = GetTaggedMediumArena();
430
0
      if (!common_internal::ValueArenaPtrTagIsStaticLifetime(
431
0
              other_arena.tag()) &&
432
0
          other_arena != arena) {
433
0
        return From(GetMedium(), arena);
434
0
      }
435
0
      return *this;
436
0
    }
437
0
    case ByteStringKind::kLarge: {
438
0
      ValueArenaPtr other_arena = GetTaggedLargeArena();
439
0
      if (!common_internal::ValueArenaPtrTagIsStaticLifetime(
440
0
              other_arena.tag()) &&
441
0
          other_arena != arena) {
442
0
        return From(GetLarge(), arena);
443
0
      }
444
0
      return *this;
445
0
    }
446
0
  }
447
0
}
448
449
void ByteString::CopyCordToArray(const absl::Cord& cord, size_t offset,
450
0
                                 size_t size, char* data) {
451
0
  for (auto chunk : cord.Chunks()) {
452
0
    if (size == 0) {
453
0
      break;
454
0
    }
455
0
    if (offset > 0) {
456
0
      size_t min_offset = std::min(chunk.size(), offset);
457
0
      offset -= min_offset;
458
0
      if (offset > 0) {
459
0
        continue;
460
0
      }
461
0
      chunk.remove_prefix(min_offset);
462
0
    }
463
0
    size_t min_size = std::min(size, chunk.size());
464
0
    std::memcpy(data, chunk.data(), min_size);
465
0
    data += min_size;
466
0
    size -= min_size;
467
0
  }
468
0
}
469
470
void ByteString::AppendCordToString(const absl::Cord& cord, size_t offset,
471
0
                                    size_t size, std::string& data) {
472
0
  size_t original_size = data.size();
473
0
  size_t target_size = original_size + size;
474
0
  absl::StringResizeAndOverwrite(
475
0
      data, original_size + size,
476
0
      [&cord, offset, size, original_size, target_size](
477
0
          char* buf, size_t buf_size) -> size_t {
478
0
        CopyCordToArray(cord, offset, size, buf + original_size);
479
0
        return target_size;
480
0
      });
481
0
}
482
483
absl::string_view LegacyByteString(const ByteString& string, bool stable,
484
560
                                   google::protobuf::Arena* absl_nonnull arena) {
485
560
  ABSL_DCHECK(arena != nullptr);
486
560
  if (string.empty()) {
487
37
    return absl::string_view();
488
37
  }
489
523
  const ByteStringKind kind = string.GetKind();
490
523
  if (kind == ByteStringKind::kMedium && string.GetMediumArena() == arena) {
491
14
    google::protobuf::Arena* absl_nullable other_arena = string.GetMediumArena();
492
14
    if (other_arena == arena || other_arena == nullptr) {
493
      // Legacy values do not preserve arena. For speed, we assume the arena is
494
      // compatible.
495
14
      return string.GetMedium();
496
14
    }
497
14
  }
498
509
  if (stable && kind == ByteStringKind::kSmall) {
499
0
    return string.GetSmall();
500
0
  }
501
509
  std::string* absl_nonnull result = google::protobuf::Arena::Create<std::string>(arena);
502
509
  switch (kind) {
503
428
    case ByteStringKind::kSmall:
504
428
      result->assign(string.GetSmall());
505
428
      break;
506
81
    case ByteStringKind::kMedium:
507
81
      result->assign(string.GetMedium());
508
81
      break;
509
0
    case ByteStringKind::kLarge:
510
0
      absl::CopyCordToString(string.GetLarge(), result);
511
0
      break;
512
509
  }
513
509
  return absl::string_view(*result);
514
509
}
515
516
}  // namespace cel::common_internal