-
Notifications
You must be signed in to change notification settings - Fork 15.3k
/
repeated_ptr_field.h
2018 lines (1748 loc) · 69.4 KB
/
repeated_ptr_field.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// RepeatedField and RepeatedPtrField are used by generated protocol message
// classes to manipulate repeated fields. These classes are very similar to
// STL's vector, but include a number of optimizations found to be useful
// specifically in the case of Protocol Buffers. RepeatedPtrField is
// particularly different from STL vector as it manages ownership of the
// pointers that it contains.
//
// This header covers RepeatedPtrField.
#ifndef GOOGLE_PROTOBUF_REPEATED_PTR_FIELD_H__
#define GOOGLE_PROTOBUF_REPEATED_PTR_FIELD_H__
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <limits>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/log/absl_check.h"
#include "absl/meta/type_traits.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/internal_visibility.h"
#include "google/protobuf/message_lite.h"
#include "google/protobuf/port.h"
// Must be included last.
#include "google/protobuf/port_def.inc"
#ifdef SWIG
#error "You cannot SWIG proto headers"
#endif
namespace google {
namespace protobuf {
class Message;
class Reflection;
template <typename T>
struct WeakRepeatedPtrField;
namespace internal {
class MergePartialFromCodedStreamHelper;
class SwapFieldHelper;
} // namespace internal
namespace internal {
template <typename It>
class RepeatedPtrIterator;
template <typename It, typename VoidPtr>
class RepeatedPtrOverPtrsIterator;
} // namespace internal
namespace internal {
// Swaps two non-overlapping blocks of memory of size `N`
template <size_t N>
inline void memswap(char* PROTOBUF_RESTRICT a, char* PROTOBUF_RESTRICT b) {
// `PROTOBUF_RESTRICT` tells compiler that blocks do not overlapping which
// allows it to generate optimized code for swap_ranges.
std::swap_ranges(a, a + N, b);
}
template <typename T>
struct IsMovable
: std::integral_constant<bool, std::is_move_constructible<T>::value &&
std::is_move_assignable<T>::value> {};
// A trait that tells offset of `T::arena_`.
//
// Do not use this struct - it exists for internal use only.
template <typename T>
struct ArenaOffsetHelper {
constexpr static size_t value = offsetof(T, arena_);
};
// This is the common base class for RepeatedPtrFields. It deals only in void*
// pointers. Users should not use this interface directly.
//
// The methods of this interface correspond to the methods of RepeatedPtrField,
// but may have a template argument called TypeHandler. Its signature is:
// class TypeHandler {
// public:
// typedef MyType Type;
// static Type* New();
// static Type* NewFromPrototype(const Type* prototype,
// Arena* arena);
// static void Delete(Type*);
// static void Clear(Type*);
// static void Merge(const Type& from, Type* to);
//
// // Only needs to be implemented if SpaceUsedExcludingSelf() is called.
// static int SpaceUsedLong(const Type&);
// };
class PROTOBUF_EXPORT RepeatedPtrFieldBase {
template <typename Handler>
using Value = typename Handler::Type;
static constexpr int kSSOCapacity = 1;
using ElementFactory = void* (*)(Arena*);
protected:
// We use the same Handler for all Message types to deduplicate generated
// code.
template <typename Handler>
using CommonHandler = typename std::conditional<
std::is_base_of<MessageLite, Value<Handler>>::value,
internal::GenericTypeHandler<MessageLite>, Handler>::type;
constexpr RepeatedPtrFieldBase()
: tagged_rep_or_elem_(nullptr),
current_size_(0),
capacity_proxy_(0),
arena_(nullptr) {}
explicit RepeatedPtrFieldBase(Arena* arena)
: tagged_rep_or_elem_(nullptr),
current_size_(0),
capacity_proxy_(0),
arena_(arena) {}
RepeatedPtrFieldBase(const RepeatedPtrFieldBase&) = delete;
RepeatedPtrFieldBase& operator=(const RepeatedPtrFieldBase&) = delete;
~RepeatedPtrFieldBase() {
#ifndef NDEBUG
// Try to trigger segfault / asan failure in non-opt builds. If arena_
// lifetime has ended before the destructor.
if (arena_) (void)arena_->SpaceAllocated();
#endif
}
bool empty() const { return current_size_ == 0; }
int size() const { return current_size_; }
// Returns the size of the buffer with pointers to elements.
//
// Note:
//
// * prefer `SizeAtCapacity()` to `size() == Capacity()`;
// * prefer `AllocatedSizeAtCapacity()` to `allocated_size() == Capacity()`.
int Capacity() const { return capacity_proxy_ + kSSOCapacity; }
template <typename TypeHandler>
const Value<TypeHandler>& at(int index) const {
ABSL_CHECK_GE(index, 0);
ABSL_CHECK_LT(index, current_size_);
return *cast<TypeHandler>(element_at(index));
}
template <typename TypeHandler>
Value<TypeHandler>& at(int index) {
ABSL_CHECK_GE(index, 0);
ABSL_CHECK_LT(index, current_size_);
return *cast<TypeHandler>(element_at(index));
}
template <typename TypeHandler>
Value<TypeHandler>* Mutable(int index) {
ABSL_DCHECK_GE(index, 0);
ABSL_DCHECK_LT(index, current_size_);
return cast<TypeHandler>(element_at(index));
}
template <typename Handler>
Value<Handler>* Add() {
if (std::is_same<Value<Handler>, std::string>{}) {
return cast<Handler>(AddString());
}
return cast<Handler>(AddMessageLite(Handler::GetNewFunc()));
}
template <
typename TypeHandler,
typename std::enable_if<TypeHandler::Movable::value>::type* = nullptr>
inline void Add(Value<TypeHandler>&& value) {
if (current_size_ < allocated_size()) {
*cast<TypeHandler>(element_at(ExchangeCurrentSize(current_size_ + 1))) =
std::move(value);
return;
}
MaybeExtend();
if (!using_sso()) ++rep()->allocated_size;
auto* result = TypeHandler::New(arena_, std::move(value));
element_at(ExchangeCurrentSize(current_size_ + 1)) = result;
}
// Must be called from destructor.
//
// Pre-condition: NeedsDestroy() returns true.
template <typename TypeHandler>
void Destroy() {
ABSL_DCHECK(NeedsDestroy());
// TODO: arena check is redundant once all `RepeatedPtrField`s
// with non-null arena are owned by the arena.
if (PROTOBUF_PREDICT_FALSE(arena_ != nullptr)) return;
using H = CommonHandler<TypeHandler>;
int n = allocated_size();
void** elems = elements();
for (int i = 0; i < n; i++) {
Delete<H>(elems[i], nullptr);
}
if (!using_sso()) {
internal::SizedDelete(rep(),
Capacity() * sizeof(elems[0]) + kRepHeaderSize);
}
}
inline bool NeedsDestroy() const {
// Either there is an allocated element in SSO buffer or there is an
// allocated Rep.
return tagged_rep_or_elem_ != nullptr;
}
void DestroyProtos();
public:
// The next few methods are public so that they can be called from generated
// code when implicit weak fields are used, but they should never be called by
// application code.
template <typename TypeHandler>
const Value<TypeHandler>& Get(int index) const {
ABSL_DCHECK_GE(index, 0);
ABSL_DCHECK_LT(index, current_size_);
return *cast<TypeHandler>(element_at(index));
}
// Creates and adds an element using the given prototype, without introducing
// a link-time dependency on the concrete message type.
//
// Pre-condition: prototype must not be nullptr.
MessageLite* AddMessage(const MessageLite* prototype);
template <typename TypeHandler>
void Clear() {
const int n = current_size_;
ABSL_DCHECK_GE(n, 0);
if (n > 0) {
using H = CommonHandler<TypeHandler>;
ClearNonEmpty<H>();
}
}
// Appends all message values from `from` to this instance.
template <typename T>
void MergeFrom(const RepeatedPtrFieldBase& from) {
static_assert(std::is_base_of<MessageLite, T>::value, "");
#ifdef __cpp_if_constexpr
if constexpr (!std::is_base_of<Message, T>::value) {
// For LITE objects we use the generic MergeFrom to save on binary size.
return MergeFrom<MessageLite>(from);
}
#endif
MergeFromConcreteMessage(from, Arena::CopyConstruct<T>);
}
inline void InternalSwap(RepeatedPtrFieldBase* PROTOBUF_RESTRICT rhs) {
ABSL_DCHECK(this != rhs);
// Swap all fields except arena pointer at once.
internal::memswap<ArenaOffsetHelper<RepeatedPtrFieldBase>::value>(
reinterpret_cast<char*>(this), reinterpret_cast<char*>(rhs));
}
// Returns true if there are no preallocated elements in the array.
bool PrepareForParse() { return allocated_size() == current_size_; }
// Similar to `AddAllocated` but faster.
//
// Pre-condition: PrepareForParse() is true.
void AddAllocatedForParse(void* value) {
ABSL_DCHECK(PrepareForParse());
if (PROTOBUF_PREDICT_FALSE(SizeAtCapacity())) {
*InternalExtend(1) = value;
++rep()->allocated_size;
} else {
if (using_sso()) {
tagged_rep_or_elem_ = value;
} else {
rep()->elements[current_size_] = value;
++rep()->allocated_size;
}
}
ExchangeCurrentSize(current_size_ + 1);
}
protected:
template <typename TypeHandler>
void RemoveLast() {
ABSL_DCHECK_GT(current_size_, 0);
ExchangeCurrentSize(current_size_ - 1);
using H = CommonHandler<TypeHandler>;
H::Clear(cast<H>(element_at(current_size_)));
}
template <typename TypeHandler>
void CopyFrom(const RepeatedPtrFieldBase& other) {
if (&other == this) return;
RepeatedPtrFieldBase::Clear<TypeHandler>();
if (other.empty()) return;
RepeatedPtrFieldBase::MergeFrom<typename TypeHandler::Type>(other);
}
void CloseGap(int start, int num);
void Reserve(int capacity);
template <typename TypeHandler>
static inline Value<TypeHandler>* copy(const Value<TypeHandler>* value) {
using H = CommonHandler<TypeHandler>;
auto* new_value = H::NewFromPrototype(value, nullptr);
H::Merge(*value, new_value);
return cast<TypeHandler>(new_value);
}
// Used for constructing iterators.
void* const* raw_data() const { return elements(); }
void** raw_mutable_data() { return elements(); }
template <typename TypeHandler>
Value<TypeHandler>** mutable_data() {
// TODO: Breaks C++ aliasing rules. We should probably remove this
// method entirely.
return reinterpret_cast<Value<TypeHandler>**>(raw_mutable_data());
}
template <typename TypeHandler>
const Value<TypeHandler>* const* data() const {
// TODO: Breaks C++ aliasing rules. We should probably remove this
// method entirely.
return reinterpret_cast<const Value<TypeHandler>* const*>(raw_data());
}
template <typename TypeHandler>
PROTOBUF_NDEBUG_INLINE void Swap(RepeatedPtrFieldBase* other) {
#ifdef PROTOBUF_FORCE_COPY_IN_SWAP
if (GetArena() != nullptr && GetArena() == other->GetArena())
#else // PROTOBUF_FORCE_COPY_IN_SWAP
if (GetArena() == other->GetArena())
#endif // !PROTOBUF_FORCE_COPY_IN_SWAP
{
InternalSwap(other);
} else {
SwapFallback<TypeHandler>(other);
}
}
void SwapElements(int index1, int index2) {
using std::swap; // enable ADL with fallback
swap(element_at(index1), element_at(index2));
}
template <typename TypeHandler>
PROTOBUF_NOINLINE size_t SpaceUsedExcludingSelfLong() const {
size_t allocated_bytes =
using_sso()
? 0
: static_cast<size_t>(Capacity()) * sizeof(void*) + kRepHeaderSize;
const int n = allocated_size();
void* const* elems = elements();
for (int i = 0; i < n; ++i) {
allocated_bytes +=
TypeHandler::SpaceUsedLong(*cast<TypeHandler>(elems[i]));
}
return allocated_bytes;
}
// Advanced memory management --------------------------------------
// Like Add(), but if there are no cleared objects to use, returns nullptr.
template <typename TypeHandler>
Value<TypeHandler>* AddFromCleared() {
if (current_size_ < allocated_size()) {
return cast<TypeHandler>(
element_at(ExchangeCurrentSize(current_size_ + 1)));
} else {
return nullptr;
}
}
template <typename TypeHandler>
void AddAllocated(Value<TypeHandler>* value) {
ABSL_DCHECK_NE(value, nullptr);
Arena* element_arena = TypeHandler::GetArena(value);
Arena* arena = GetArena();
if (arena != element_arena || AllocatedSizeAtCapacity()) {
AddAllocatedSlowWithCopy<TypeHandler>(value, element_arena, arena);
return;
}
// Fast path: underlying arena representation (tagged pointer) is equal to
// our arena pointer, and we can add to array without resizing it (at
// least one slot that is not allocated).
void** elems = elements();
if (current_size_ < allocated_size()) {
// Make space at [current] by moving first allocated element to end of
// allocated list.
elems[allocated_size()] = elems[current_size_];
}
elems[ExchangeCurrentSize(current_size_ + 1)] = value;
if (!using_sso()) ++rep()->allocated_size;
}
template <typename TypeHandler>
void UnsafeArenaAddAllocated(Value<TypeHandler>* value) {
ABSL_DCHECK_NE(value, nullptr);
// Make room for the new pointer.
if (SizeAtCapacity()) {
// The array is completely full with no cleared objects, so grow it.
InternalExtend(1);
++rep()->allocated_size;
} else if (AllocatedSizeAtCapacity()) {
// There is no more space in the pointer array because it contains some
// cleared objects awaiting reuse. We don't want to grow the array in
// this case because otherwise a loop calling AddAllocated() followed by
// Clear() would leak memory.
using H = CommonHandler<TypeHandler>;
Delete<H>(element_at(current_size_), arena_);
} else if (current_size_ < allocated_size()) {
// We have some cleared objects. We don't care about their order, so we
// can just move the first one to the end to make space.
element_at(allocated_size()) = element_at(current_size_);
++rep()->allocated_size;
} else {
// There are no cleared objects.
if (!using_sso()) ++rep()->allocated_size;
}
element_at(ExchangeCurrentSize(current_size_ + 1)) = value;
}
template <typename TypeHandler>
PROTOBUF_NODISCARD Value<TypeHandler>* ReleaseLast() {
Value<TypeHandler>* result = UnsafeArenaReleaseLast<TypeHandler>();
// Now perform a copy if we're on an arena.
Arena* arena = GetArena();
#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE
auto* new_result = copy<TypeHandler>(result);
if (arena == nullptr) delete result;
#else // PROTOBUF_FORCE_COPY_IN_RELEASE
auto* new_result = (arena == nullptr) ? result : copy<TypeHandler>(result);
#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE
return new_result;
}
// Releases and returns the last element, but does not do out-of-arena copy.
// Instead, just returns the raw pointer to the contained element in the
// arena.
template <typename TypeHandler>
Value<TypeHandler>* UnsafeArenaReleaseLast() {
ABSL_DCHECK_GT(current_size_, 0);
ExchangeCurrentSize(current_size_ - 1);
auto* result = cast<TypeHandler>(element_at(current_size_));
if (using_sso()) {
tagged_rep_or_elem_ = nullptr;
} else {
--rep()->allocated_size;
if (current_size_ < allocated_size()) {
// There are cleared elements on the end; replace the removed element
// with the last allocated element.
element_at(current_size_) = element_at(allocated_size());
}
}
return result;
}
int ClearedCount() const { return allocated_size() - current_size_; }
// Slowpath handles all cases, copying if necessary.
template <typename TypeHandler>
PROTOBUF_NOINLINE void AddAllocatedSlowWithCopy(
// Pass value_arena and my_arena to avoid duplicate virtual call (value)
// or load (mine).
Value<TypeHandler>* value, Arena* value_arena, Arena* my_arena) {
using H = CommonHandler<TypeHandler>;
// Ensure that either the value is in the same arena, or if not, we do the
// appropriate thing: Own() it (if it's on heap and we're in an arena) or
// copy it to our arena/heap (otherwise).
if (my_arena != nullptr && value_arena == nullptr) {
my_arena->Own(value);
} else if (my_arena != value_arena) {
ABSL_DCHECK(value_arena != nullptr);
auto* new_value = TypeHandler::NewFromPrototype(value, my_arena);
H::Merge(*value, new_value);
value = new_value;
}
UnsafeArenaAddAllocated<H>(value);
}
template <typename TypeHandler>
PROTOBUF_NOINLINE void SwapFallback(RepeatedPtrFieldBase* other) {
#ifdef PROTOBUF_FORCE_COPY_IN_SWAP
ABSL_DCHECK(GetArena() == nullptr || other->GetArena() != GetArena());
#else // PROTOBUF_FORCE_COPY_IN_SWAP
ABSL_DCHECK(other->GetArena() != GetArena());
#endif // !PROTOBUF_FORCE_COPY_IN_SWAP
// Copy semantics in this case. We try to improve efficiency by placing the
// temporary on |other|'s arena so that messages are copied twice rather
// than three times.
RepeatedPtrFieldBase temp(other->GetArena());
if (!this->empty()) {
temp.MergeFrom<typename TypeHandler::Type>(*this);
}
this->CopyFrom<TypeHandler>(*other);
other->InternalSwap(&temp);
if (temp.NeedsDestroy()) {
temp.Destroy<TypeHandler>();
}
}
// Gets the Arena on which this RepeatedPtrField stores its elements.
inline Arena* GetArena() const { return arena_; }
private:
using InternalArenaConstructable_ = void;
using DestructorSkippable_ = void;
template <typename T>
friend class Arena::InternalHelper;
// ExtensionSet stores repeated message extensions as
// RepeatedPtrField<MessageLite>, but non-lite ExtensionSets need to implement
// SpaceUsedLong(), and thus need to call SpaceUsedExcludingSelfLong()
// reinterpreting MessageLite as Message. ExtensionSet also needs to make use
// of AddFromCleared(), which is not part of the public interface.
friend class ExtensionSet;
// The MapFieldBase implementation needs to call protected methods directly,
// reinterpreting pointers as being to Message instead of a specific Message
// subclass.
friend class MapFieldBase;
friend struct MapFieldTestPeer;
// The table-driven MergePartialFromCodedStream implementation needs to
// operate on RepeatedPtrField<MessageLite>.
friend class MergePartialFromCodedStreamHelper;
friend class AccessorHelper;
template <typename T>
friend struct google::protobuf::WeakRepeatedPtrField;
friend class internal::TcParser; // TODO: Remove this friend.
// Expose offset of `arena_` without exposing the member itself.
// Used to optimize code size of `InternalSwap` method.
template <typename T>
friend struct ArenaOffsetHelper;
// The reflection implementation needs to call protected methods directly,
// reinterpreting pointers as being to Message instead of a specific Message
// subclass.
friend class google::protobuf::Reflection;
friend class internal::SwapFieldHelper;
// Concrete Arena enabled copy function used to copy messages instances.
// This follows the `Arena::CopyConstruct` signature so that the compiler
// can have the inlined call into the out of line copy function(s) simply pass
// the address of `Arena::CopyConstruct` 'as is'.
using CopyFn = void* (*)(Arena*, const void*);
struct Rep {
int allocated_size;
// Here we declare a huge array as a way of approximating C's "flexible
// array member" feature without relying on undefined behavior.
void* elements[(std::numeric_limits<int>::max() - 2 * sizeof(int)) /
sizeof(void*)];
};
static constexpr size_t kRepHeaderSize = offsetof(Rep, elements);
// Replaces current_size_ with new_size and returns the previous value of
// current_size_. This function is intended to be the only place where
// current_size_ is modified.
inline int ExchangeCurrentSize(int new_size) {
return std::exchange(current_size_, new_size);
}
inline bool SizeAtCapacity() const {
// Harden invariant size() <= allocated_size() <= Capacity().
ABSL_DCHECK_LE(size(), allocated_size());
ABSL_DCHECK_LE(allocated_size(), Capacity());
// This is equivalent to `current_size_ == Capacity()`.
// Assuming `Capacity()` function is inlined, compiler is likely to optimize
// away "+ kSSOCapacity" and reduce it to "current_size_ > capacity_proxy_"
// which is an instruction less than "current_size_ == capacity_proxy_ + 1".
return current_size_ >= Capacity();
}
inline bool AllocatedSizeAtCapacity() const {
// Harden invariant size() <= allocated_size() <= Capacity().
ABSL_DCHECK_LE(size(), allocated_size());
ABSL_DCHECK_LE(allocated_size(), Capacity());
// This combines optimization mentioned in `SizeAtCapacity()` and simplifies
// `allocated_size()` in sso case.
return using_sso() ? (tagged_rep_or_elem_ != nullptr)
: rep()->allocated_size >= Capacity();
}
void* const* elements() const {
return using_sso() ? &tagged_rep_or_elem_ : +rep()->elements;
}
void** elements() {
return using_sso() ? &tagged_rep_or_elem_ : +rep()->elements;
}
void*& element_at(int index) {
if (using_sso()) {
ABSL_DCHECK_EQ(index, 0);
return tagged_rep_or_elem_;
}
return rep()->elements[index];
}
const void* element_at(int index) const {
return const_cast<RepeatedPtrFieldBase*>(this)->element_at(index);
}
int allocated_size() const {
return using_sso() ? (tagged_rep_or_elem_ != nullptr ? 1 : 0)
: rep()->allocated_size;
}
Rep* rep() {
ABSL_DCHECK(!using_sso());
return reinterpret_cast<Rep*>(
reinterpret_cast<uintptr_t>(tagged_rep_or_elem_) - 1);
}
const Rep* rep() const {
return const_cast<RepeatedPtrFieldBase*>(this)->rep();
}
bool using_sso() const {
return (reinterpret_cast<uintptr_t>(tagged_rep_or_elem_) & 1) == 0;
}
template <typename TypeHandler>
static inline Value<TypeHandler>* cast(void* element) {
return reinterpret_cast<Value<TypeHandler>*>(element);
}
template <typename TypeHandler>
static inline const Value<TypeHandler>* cast(const void* element) {
return reinterpret_cast<const Value<TypeHandler>*>(element);
}
template <typename TypeHandler>
static inline void Delete(void* obj, Arena* arena) {
TypeHandler::Delete(cast<TypeHandler>(obj), arena);
}
// Out-of-line helper routine for Clear() once the inlined check has
// determined the container is non-empty
template <typename TypeHandler>
PROTOBUF_NOINLINE void ClearNonEmpty() {
const int n = current_size_;
void* const* elems = elements();
int i = 0;
ABSL_DCHECK_GT(n, 0);
// do/while loop to avoid initial test because we know n > 0
do {
TypeHandler::Clear(cast<TypeHandler>(elems[i++]));
} while (i < n);
ExchangeCurrentSize(0);
}
// Merges messages from `from` into available, cleared messages sitting in the
// range `[size(), allocated_size())`. Returns the number of message merged
// which is `ClearedCount(), from.size())`.
// Note that this function does explicitly NOT update `current_size_`.
// This function is out of line as it should be the slow path: this scenario
// only happens when a caller constructs and fills a repeated field, then
// shrinks it, and then merges additional messages into it.
int MergeIntoClearedMessages(const RepeatedPtrFieldBase& from);
// Appends all messages from `from` to this instance, using the
// provided `copy_fn` copy function to copy existing messages.
void MergeFromConcreteMessage(const RepeatedPtrFieldBase& from,
CopyFn copy_fn);
// Extends capacity by at least |extend_amount|.
//
// Pre-condition: |extend_amount| must be > 0.
void** InternalExtend(int extend_amount);
// Ensures that capacity is big enough to store one more allocated element.
inline void MaybeExtend() {
if (AllocatedSizeAtCapacity()) {
ABSL_DCHECK_EQ(allocated_size(), Capacity());
InternalExtend(1);
} else {
ABSL_DCHECK_NE(allocated_size(), Capacity());
}
}
// Ensures that capacity is at least `n` elements.
// Returns a pointer to the element directly beyond the last element.
inline void** InternalReserve(int n) {
if (n <= Capacity()) {
void** elements = using_sso() ? &tagged_rep_or_elem_ : rep()->elements;
return elements + current_size_;
}
return InternalExtend(n - Capacity());
}
// Internal helpers for Add that keep definition out-of-line.
void* AddMessageLite(ElementFactory factory);
void* AddString();
// Common implementation used by various Add* methods. `factory` is an object
// used to construct a new element unless there are spare cleared elements
// ready for reuse. Returns pointer to the new element.
//
// Note: avoid inlining this function in methods such as `Add()` as this would
// drastically increase binary size due to template instantiation and implicit
// inlining.
template <typename Factory>
void* AddInternal(Factory factory);
// A few notes on internal representation:
//
// We use an indirected approach, with struct Rep, to keep
// sizeof(RepeatedPtrFieldBase) equivalent to what it was before arena support
// was added; namely, 3 8-byte machine words on x86-64. An instance of Rep is
// allocated only when the repeated field is non-empty, and it is a
// dynamically-sized struct (the header is directly followed by elements[]).
// We place arena_ and current_size_ directly in the object to avoid cache
// misses due to the indirection, because these fields are checked frequently.
// Placing all fields directly in the RepeatedPtrFieldBase instance would cost
// significant performance for memory-sensitive workloads.
void* tagged_rep_or_elem_;
int current_size_;
int capacity_proxy_; // we store `capacity - kSSOCapacity` as an optimization
Arena* arena_;
};
// Appends all message values from `from` to this instance using the abstract
// message interface. This overload is used in places like reflection and
// other locations where the underlying type is unavailable
template <>
void RepeatedPtrFieldBase::MergeFrom<MessageLite>(
const RepeatedPtrFieldBase& from);
template <>
inline void RepeatedPtrFieldBase::MergeFrom<Message>(
const RepeatedPtrFieldBase& from) {
return MergeFrom<MessageLite>(from);
}
// Appends all `std::string` values from `from` to this instance.
template <>
void RepeatedPtrFieldBase::MergeFrom<std::string>(
const RepeatedPtrFieldBase& from);
PROTOBUF_EXPORT void InternalOutOfLineDeleteMessageLite(MessageLite* message);
template <typename GenericType>
class GenericTypeHandler {
public:
typedef GenericType Type;
using Movable = IsMovable<GenericType>;
static constexpr auto GetNewFunc() { return Arena::DefaultConstruct<Type>; }
static inline GenericType* New(Arena* arena) {
return static_cast<GenericType*>(Arena::DefaultConstruct<Type>(arena));
}
static inline GenericType* New(Arena* arena, GenericType&& value) {
return Arena::Create<GenericType>(arena, std::move(value));
}
static inline GenericType* NewFromPrototype(const GenericType* /*prototype*/,
Arena* arena = nullptr) {
return New(arena);
}
static inline void Delete(GenericType* value, Arena* arena) {
if (arena != nullptr) return;
#ifdef __cpp_if_constexpr
if constexpr (std::is_base_of<MessageLite, GenericType>::value) {
// Using virtual destructor to reduce generated code size that would have
// happened otherwise due to inlined `~GenericType`.
InternalOutOfLineDeleteMessageLite(value);
} else {
delete value;
}
#else
delete value;
#endif
}
static inline Arena* GetArena(GenericType* value) {
return Arena::InternalGetArena(value);
}
static inline void Clear(GenericType* value) { value->Clear(); }
static void Merge(const GenericType& from, GenericType* to);
static inline size_t SpaceUsedLong(const GenericType& value) {
return value.SpaceUsedLong();
}
};
// NewFromPrototypeHelper() is not defined inline here, as we will need to do a
// virtual function dispatch anyways to go from Message* to call New/Merge. (The
// additional helper is needed as a workaround for MSVC.)
PROTOBUF_EXPORT MessageLite* NewFromPrototypeHelper(
const MessageLite* prototype, Arena* arena);
template <>
inline MessageLite* GenericTypeHandler<MessageLite>::NewFromPrototype(
const MessageLite* prototype, Arena* arena) {
return NewFromPrototypeHelper(prototype, arena);
}
template <>
inline Arena* GenericTypeHandler<MessageLite>::GetArena(MessageLite* value) {
return value->GetArena();
}
template <typename GenericType>
PROTOBUF_NOINLINE inline void GenericTypeHandler<GenericType>::Merge(
const GenericType& from, GenericType* to) {
to->MergeFrom(from);
}
template <>
PROTOBUF_EXPORT void GenericTypeHandler<MessageLite>::Merge(
const MessageLite& from, MessageLite* to);
// Message specialization bodies defined in message.cc. This split is necessary
// to allow proto2-lite (which includes this header) to be independent of
// Message.
template <>
PROTOBUF_EXPORT Message* GenericTypeHandler<Message>::NewFromPrototype(
const Message* prototype, Arena* arena);
template <>
PROTOBUF_EXPORT Arena* GenericTypeHandler<Message>::GetArena(Message* value);
PROTOBUF_EXPORT void* NewStringElement(Arena* arena);
template <>
class GenericTypeHandler<std::string> {
public:
typedef std::string Type;
using Movable = IsMovable<Type>;
static constexpr auto GetNewFunc() { return NewStringElement; }
static PROTOBUF_NOINLINE std::string* New(Arena* arena) {
return Arena::Create<std::string>(arena);
}
static PROTOBUF_NOINLINE std::string* New(Arena* arena, std::string&& value) {
return Arena::Create<std::string>(arena, std::move(value));
}
static inline std::string* NewFromPrototype(const std::string*,
Arena* arena) {
return New(arena);
}
static inline Arena* GetArena(std::string*) { return nullptr; }
static inline void Delete(std::string* value, Arena* arena) {
if (arena == nullptr) {
delete value;
}
}
static inline void Clear(std::string* value) { value->clear(); }
static inline void Merge(const std::string& from, std::string* to) {
*to = from;
}
static size_t SpaceUsedLong(const std::string& value) {
return sizeof(value) + StringSpaceUsedExcludingSelfLong(value);
}
};
} // namespace internal
// RepeatedPtrField is like RepeatedField, but used for repeated strings or
// Messages.
template <typename Element>
class RepeatedPtrField final : private internal::RepeatedPtrFieldBase {
static_assert(!std::is_const<Element>::value,
"We do not support const value types.");
static_assert(!std::is_volatile<Element>::value,
"We do not support volatile value types.");
static_assert(!std::is_pointer<Element>::value,
"We do not support pointer value types.");
static_assert(!std::is_reference<Element>::value,
"We do not support reference value types.");
static constexpr PROTOBUF_ALWAYS_INLINE void StaticValidityCheck() {
static_assert(
absl::disjunction<
internal::is_supported_string_type<Element>,
internal::is_supported_message_type<Element>>::value,
"We only support string and Message types in RepeatedPtrField.");
}
public:
using value_type = Element;
using size_type = int;
using difference_type = ptrdiff_t;
using reference = Element&;
using const_reference = const Element&;
using pointer = Element*;
using const_pointer = const Element*;
using iterator = internal::RepeatedPtrIterator<Element>;
using const_iterator = internal::RepeatedPtrIterator<const Element>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
// Custom STL-like iterator that iterates over and returns the underlying
// pointers to Element rather than Element itself.
using pointer_iterator =
internal::RepeatedPtrOverPtrsIterator<Element*, void*>;
using const_pointer_iterator =
internal::RepeatedPtrOverPtrsIterator<const Element* const,
const void* const>;
constexpr RepeatedPtrField();
// Arena enabled constructors: for internal use only.
RepeatedPtrField(internal::InternalVisibility, Arena* arena)
: RepeatedPtrField(arena) {}
RepeatedPtrField(internal::InternalVisibility, Arena* arena,
const RepeatedPtrField& rhs)
: RepeatedPtrField(arena, rhs) {}
// TODO: make constructor private
explicit RepeatedPtrField(Arena* arena);
template <typename Iter,
typename = typename std::enable_if<std::is_constructible<
Element, decltype(*std::declval<Iter>())>::value>::type>
RepeatedPtrField(Iter begin, Iter end);
RepeatedPtrField(const RepeatedPtrField& rhs)
: RepeatedPtrField(nullptr, rhs) {}
RepeatedPtrField& operator=(const RepeatedPtrField& other)
ABSL_ATTRIBUTE_LIFETIME_BOUND;
RepeatedPtrField(RepeatedPtrField&& rhs) noexcept
: RepeatedPtrField(nullptr, std::move(rhs)) {}
RepeatedPtrField& operator=(RepeatedPtrField&& other) noexcept
ABSL_ATTRIBUTE_LIFETIME_BOUND;
~RepeatedPtrField();
bool empty() const;
int size() const;
const_reference Get(int index) const ABSL_ATTRIBUTE_LIFETIME_BOUND;
pointer Mutable(int index) ABSL_ATTRIBUTE_LIFETIME_BOUND;
// Unlike std::vector, adding an element to a RepeatedPtrField doesn't always
// make a new element; it might re-use an element left over from when the
// field was Clear()'d or resize()'d smaller. For this reason, Add() is the
// fastest API for adding a new element.
pointer Add() ABSL_ATTRIBUTE_LIFETIME_BOUND;
// `Add(std::move(value));` is equivalent to `*Add() = std::move(value);`
// It will either move-construct to the end of this field, or swap value
// with the new-or-recycled element at the end of this field. Note that
// this operation is very slow if this RepeatedPtrField is not on the
// same Arena, if any, as `value`.
void Add(Element&& value);
// Copying to the end of this RepeatedPtrField is slowest of all; it can't
// reliably copy-construct to the last element of this RepeatedPtrField, for
// example (unlike std::vector).
// We currently block this API. The right way to add to the end is to call
// Add() and modify the element it points to.
// If you must add an existing value, call `*Add() = value;`
void Add(const Element& value) = delete;
// Append elements in the range [begin, end) after reserving
// the appropriate number of elements.
template <typename Iter>
void Add(Iter begin, Iter end);
const_reference operator[](int index) const ABSL_ATTRIBUTE_LIFETIME_BOUND {
return Get(index);
}
reference operator[](int index) ABSL_ATTRIBUTE_LIFETIME_BOUND {
return *Mutable(index);
}
const_reference at(int index) const ABSL_ATTRIBUTE_LIFETIME_BOUND;
reference at(int index) ABSL_ATTRIBUTE_LIFETIME_BOUND;
// Removes the last element in the array.