• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 // Author: kenton@google.com (Kenton Varda)
32 //  Based on original Protocol Buffers design by
33 //  Sanjay Ghemawat, Jeff Dean, and others.
34 //
35 // RepeatedField and RepeatedPtrField are used by generated protocol message
36 // classes to manipulate repeated fields.  These classes are very similar to
37 // STL's vector, but include a number of optimizations found to be useful
38 // specifically in the case of Protocol Buffers.  RepeatedPtrField is
39 // particularly different from STL vector as it manages ownership of the
40 // pointers that it contains.
41 //
42 // Typically, clients should not need to access RepeatedField objects directly,
43 // but should instead use the accessor functions generated automatically by the
44 // protocol compiler.
45 
46 #ifndef GOOGLE_PROTOBUF_REPEATED_FIELD_H__
47 #define GOOGLE_PROTOBUF_REPEATED_FIELD_H__
48 
49 #include <utility>
50 #ifdef _MSC_VER
51 // This is required for min/max on VS2013 only.
52 #include <algorithm>
53 #endif
54 
55 #include <iterator>
56 #include <limits>
57 #include <string>
58 #include <type_traits>
59 
60 #include <google/protobuf/stubs/logging.h>
61 #include <google/protobuf/stubs/common.h>
62 #include <google/protobuf/arena.h>
63 #include <google/protobuf/message_lite.h>
64 #include <google/protobuf/port.h>
65 #include <google/protobuf/stubs/casts.h>
66 #include <type_traits>
67 
68 
69 // Must be included last.
70 #include <google/protobuf/port_def.inc>
71 
72 #ifdef SWIG
73 #error "You cannot SWIG proto headers"
74 #endif
75 
76 namespace google {
77 namespace protobuf {
78 
79 class Message;
80 class Reflection;
81 
82 template <typename T>
83 struct WeakRepeatedPtrField;
84 
85 namespace internal {
86 
87 class MergePartialFromCodedStreamHelper;
88 
89 // kRepeatedFieldLowerClampLimit is the smallest size that will be allocated
90 // when growing a repeated field.
91 constexpr int kRepeatedFieldLowerClampLimit = 4;
92 
93 // kRepeatedFieldUpperClampLimit is the lowest signed integer value that
94 // overflows when multiplied by 2 (which is undefined behavior). Sizes above
95 // this will clamp to the maximum int value instead of following exponential
96 // growth when growing a repeated field.
97 constexpr int kRepeatedFieldUpperClampLimit =
98     (std::numeric_limits<int>::max() / 2) + 1;
99 
100 // A utility function for logging that doesn't need any template types.
101 void LogIndexOutOfBounds(int index, int size);
102 
103 template <typename Iter>
CalculateReserve(Iter begin,Iter end,std::forward_iterator_tag)104 inline int CalculateReserve(Iter begin, Iter end, std::forward_iterator_tag) {
105   return static_cast<int>(std::distance(begin, end));
106 }
107 
108 template <typename Iter>
CalculateReserve(Iter,Iter,std::input_iterator_tag)109 inline int CalculateReserve(Iter /*begin*/, Iter /*end*/,
110                             std::input_iterator_tag /*unused*/) {
111   return -1;
112 }
113 
114 template <typename Iter>
CalculateReserve(Iter begin,Iter end)115 inline int CalculateReserve(Iter begin, Iter end) {
116   typedef typename std::iterator_traits<Iter>::iterator_category Category;
117   return CalculateReserve(begin, end, Category());
118 }
119 
120 // Swaps two blocks of memory of size sizeof(T).
121 template <typename T>
SwapBlock(char * p,char * q)122 inline void SwapBlock(char* p, char* q) {
123   T tmp;
124   memcpy(&tmp, p, sizeof(T));
125   memcpy(p, q, sizeof(T));
126   memcpy(q, &tmp, sizeof(T));
127 }
128 
129 // Swaps two blocks of memory of size kSize:
130 //  template <int kSize> void memswap(char* p, char* q);
131 
132 template <int kSize>
memswap(char *,char *)133 inline typename std::enable_if<(kSize == 0), void>::type memswap(char*, char*) {
134 }
135 
136 #define PROTO_MEMSWAP_DEF_SIZE(reg_type, max_size)                           \
137   template <int kSize>                                                       \
138   typename std::enable_if<(kSize >= sizeof(reg_type) && kSize < (max_size)), \
139                           void>::type                                        \
140   memswap(char* p, char* q) {                                                \
141     SwapBlock<reg_type>(p, q);                                               \
142     memswap<kSize - sizeof(reg_type)>(p + sizeof(reg_type),                  \
143                                       q + sizeof(reg_type));                 \
144   }
145 
146 PROTO_MEMSWAP_DEF_SIZE(uint8, 2)
147 PROTO_MEMSWAP_DEF_SIZE(uint16, 4)
148 PROTO_MEMSWAP_DEF_SIZE(uint32, 8)
149 
150 #ifdef __SIZEOF_INT128__
151 PROTO_MEMSWAP_DEF_SIZE(uint64, 16)
152 PROTO_MEMSWAP_DEF_SIZE(__uint128_t, (1u << 31))
153 #else
154 PROTO_MEMSWAP_DEF_SIZE(uint64, (1u << 31))
155 #endif
156 
157 #undef PROTO_MEMSWAP_DEF_SIZE
158 
159 }  // namespace internal
160 
161 // RepeatedField is used to represent repeated fields of a primitive type (in
162 // other words, everything except strings and nested Messages).  Most users will
163 // not ever use a RepeatedField directly; they will use the get-by-index,
164 // set-by-index, and add accessors that are generated for all repeated fields.
165 template <typename Element>
166 class RepeatedField final {
167   static_assert(
168       alignof(Arena) >= alignof(Element),
169       "We only support types that have an alignment smaller than Arena");
170 
171  public:
172   constexpr RepeatedField();
173   explicit RepeatedField(Arena* arena);
174   RepeatedField(const RepeatedField& other);
175   template <typename Iter>
176   RepeatedField(Iter begin, const Iter& end);
177   ~RepeatedField();
178 
179   RepeatedField& operator=(const RepeatedField& other);
180 
181   RepeatedField(RepeatedField&& other) noexcept;
182   RepeatedField& operator=(RepeatedField&& other) noexcept;
183 
184   bool empty() const;
185   int size() const;
186 
187   const Element& Get(int index) const;
188   Element* Mutable(int index);
189 
190   const Element& operator[](int index) const { return Get(index); }
191   Element& operator[](int index) { return *Mutable(index); }
192 
193   const Element& at(int index) const;
194   Element& at(int index);
195 
196   void Set(int index, const Element& value);
197   void Add(const Element& value);
198   // Appends a new element and return a pointer to it.
199   // The new element is uninitialized if |Element| is a POD type.
200   Element* Add();
201   // Append elements in the range [begin, end) after reserving
202   // the appropriate number of elements.
203   template <typename Iter>
204   void Add(Iter begin, Iter end);
205 
206   // Remove the last element in the array.
207   void RemoveLast();
208 
209   // Extract elements with indices in "[start .. start+num-1]".
210   // Copy them into "elements[0 .. num-1]" if "elements" is not NULL.
211   // Caution: implementation also moves elements with indices [start+num ..].
212   // Calling this routine inside a loop can cause quadratic behavior.
213   void ExtractSubrange(int start, int num, Element* elements);
214 
215   void Clear();
216   void MergeFrom(const RepeatedField& other);
217   void CopyFrom(const RepeatedField& other);
218 
219   // Reserve space to expand the field to at least the given size.  If the
220   // array is grown, it will always be at least doubled in size.
221   void Reserve(int new_size);
222 
223   // Resize the RepeatedField to a new, smaller size.  This is O(1).
224   void Truncate(int new_size);
225 
226   void AddAlreadyReserved(const Element& value);
227   // Appends a new element and return a pointer to it.
228   // The new element is uninitialized if |Element| is a POD type.
229   // Should be called only if Capacity() > Size().
230   Element* AddAlreadyReserved();
231   Element* AddNAlreadyReserved(int elements);
232   int Capacity() const;
233 
234   // Like STL resize.  Uses value to fill appended elements.
235   // Like Truncate() if new_size <= size(), otherwise this is
236   // O(new_size - size()).
237   void Resize(int new_size, const Element& value);
238 
239   // Gets the underlying array.  This pointer is possibly invalidated by
240   // any add or remove operation.
241   Element* mutable_data();
242   const Element* data() const;
243 
244   // Swap entire contents with "other". If they are separate arenas then, copies
245   // data between each other.
246   void Swap(RepeatedField* other);
247 
248   // Swap entire contents with "other". Should be called only if the caller can
249   // guarantee that both repeated fields are on the same arena or are on the
250   // heap. Swapping between different arenas is disallowed and caught by a
251   // GOOGLE_DCHECK (see API docs for details).
252   void UnsafeArenaSwap(RepeatedField* other);
253 
254   // Swap two elements.
255   void SwapElements(int index1, int index2);
256 
257   // STL-like iterator support
258   typedef Element* iterator;
259   typedef const Element* const_iterator;
260   typedef Element value_type;
261   typedef value_type& reference;
262   typedef const value_type& const_reference;
263   typedef value_type* pointer;
264   typedef const value_type* const_pointer;
265   typedef int size_type;
266   typedef ptrdiff_t difference_type;
267 
268   iterator begin();
269   const_iterator begin() const;
270   const_iterator cbegin() const;
271   iterator end();
272   const_iterator end() const;
273   const_iterator cend() const;
274 
275   // Reverse iterator support
276   typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
277   typedef std::reverse_iterator<iterator> reverse_iterator;
rbegin()278   reverse_iterator rbegin() { return reverse_iterator(end()); }
rbegin()279   const_reverse_iterator rbegin() const {
280     return const_reverse_iterator(end());
281   }
rend()282   reverse_iterator rend() { return reverse_iterator(begin()); }
rend()283   const_reverse_iterator rend() const {
284     return const_reverse_iterator(begin());
285   }
286 
287   // Returns the number of bytes used by the repeated field, excluding
288   // sizeof(*this)
289   size_t SpaceUsedExcludingSelfLong() const;
290 
SpaceUsedExcludingSelf()291   int SpaceUsedExcludingSelf() const {
292     return internal::ToIntSize(SpaceUsedExcludingSelfLong());
293   }
294 
295   // Removes the element referenced by position.
296   //
297   // Returns an iterator to the element immediately following the removed
298   // element.
299   //
300   // Invalidates all iterators at or after the removed element, including end().
301   iterator erase(const_iterator position);
302 
303   // Removes the elements in the range [first, last).
304   //
305   // Returns an iterator to the element immediately following the removed range.
306   //
307   // Invalidates all iterators at or after the removed range, including end().
308   iterator erase(const_iterator first, const_iterator last);
309 
310   // Get the Arena on which this RepeatedField stores its elements.
GetArena()311   inline Arena* GetArena() const {
312     return (total_size_ == 0) ? static_cast<Arena*>(arena_or_elements_)
313                               : rep()->arena;
314   }
315 
316   // For internal use only.
317   //
318   // This is public due to it being called by generated code.
319   inline void InternalSwap(RepeatedField* other);
320 
321  private:
322   static constexpr int kInitialSize = 0;
323   // A note on the representation here (see also comment below for
324   // RepeatedPtrFieldBase's struct Rep):
325   //
326   // We maintain the same sizeof(RepeatedField) as before we added arena support
327   // so that we do not degrade performance by bloating memory usage. Directly
328   // adding an arena_ element to RepeatedField is quite costly. By using
329   // indirection in this way, we keep the same size when the RepeatedField is
330   // empty (common case), and add only an 8-byte header to the elements array
331   // when non-empty. We make sure to place the size fields directly in the
332   // RepeatedField class to avoid costly cache misses due to the indirection.
333   int current_size_;
334   int total_size_;
335   struct Rep {
336     Arena* arena;
337     // Here we declare a huge array as a way of approximating C's "flexible
338     // array member" feature without relying on undefined behavior.
339     Element elements[(std::numeric_limits<int>::max() - 2 * sizeof(Arena*)) /
340                      sizeof(Element)];
341   };
342   static constexpr size_t kRepHeaderSize = offsetof(Rep, elements);
343 
344   // If total_size_ == 0 this points to an Arena otherwise it points to the
345   // elements member of a Rep struct. Using this invariant allows the storage of
346   // the arena pointer without an extra allocation in the constructor.
347   void* arena_or_elements_;
348 
349   // Return pointer to elements array.
350   // pre-condition: the array must have been allocated.
elements()351   Element* elements() const {
352     GOOGLE_DCHECK_GT(total_size_, 0);
353     // Because of above pre-condition this cast is safe.
354     return unsafe_elements();
355   }
356 
357   // Return pointer to elements array if it exists otherwise either null or
358   // a invalid pointer is returned. This only happens for empty repeated fields,
359   // where you can't dereference this pointer anyway (it's empty).
unsafe_elements()360   Element* unsafe_elements() const {
361     return static_cast<Element*>(arena_or_elements_);
362   }
363 
364   // Return pointer to the Rep struct.
365   // pre-condition: the Rep must have been allocated, ie elements() is safe.
rep()366   Rep* rep() const {
367     char* addr = reinterpret_cast<char*>(elements()) - offsetof(Rep, elements);
368     return reinterpret_cast<Rep*>(addr);
369   }
370 
371   friend class Arena;
372   typedef void InternalArenaConstructable_;
373 
374   // Move the contents of |from| into |to|, possibly clobbering |from| in the
375   // process.  For primitive types this is just a memcpy(), but it could be
376   // specialized for non-primitive types to, say, swap each element instead.
377   void MoveArray(Element* to, Element* from, int size);
378 
379   // Copy the elements of |from| into |to|.
380   void CopyArray(Element* to, const Element* from, int size);
381 
382   // Internal helper to delete all elements and deallocate the storage.
InternalDeallocate(Rep * rep,int size)383   void InternalDeallocate(Rep* rep, int size) {
384     if (rep != NULL) {
385       Element* e = &rep->elements[0];
386       if (!std::is_trivial<Element>::value) {
387         Element* limit = &rep->elements[size];
388         for (; e < limit; e++) {
389           e->~Element();
390         }
391       }
392       if (rep->arena == NULL) {
393 #if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
394         const size_t bytes = size * sizeof(*e) + kRepHeaderSize;
395         ::operator delete(static_cast<void*>(rep), bytes);
396 #else
397         ::operator delete(static_cast<void*>(rep));
398 #endif
399       }
400     }
401   }
402 
403   // This class is a performance wrapper around RepeatedField::Add(const T&)
404   // function. In general unless a RepeatedField is a local stack variable LLVM
405   // has a hard time optimizing Add. The machine code tends to be
406   // loop:
407   // mov %size, dword ptr [%repeated_field]       // load
408   // cmp %size, dword ptr [%repeated_field + 4]
409   // jae fallback
410   // mov %buffer, qword ptr [%repeated_field + 8]
411   // mov dword [%buffer + %size * 4], %value
412   // inc %size                                    // increment
413   // mov dword ptr [%repeated_field], %size       // store
414   // jmp loop
415   //
416   // This puts a load/store in each iteration of the important loop variable
417   // size. It's a pretty bad compile that happens even in simple cases, but
418   // largely the presence of the fallback path disturbs the compilers mem-to-reg
419   // analysis.
420   //
421   // This class takes ownership of a repeated field for the duration of it's
422   // lifetime. The repeated field should not be accessed during this time, ie.
423   // only access through this class is allowed. This class should always be a
424   // function local stack variable. Intended use
425   //
426   // void AddSequence(const int* begin, const int* end, RepeatedField<int>* out)
427   // {
428   //   RepeatedFieldAdder<int> adder(out);  // Take ownership of out
429   //   for (auto it = begin; it != end; ++it) {
430   //     adder.Add(*it);
431   //   }
432   // }
433   //
434   // Typically due to the fact adder is a local stack variable. The compiler
435   // will be successful in mem-to-reg transformation and the machine code will
436   // be loop: cmp %size, %capacity jae fallback mov dword ptr [%buffer + %size *
437   // 4], %val inc %size jmp loop
438   //
439   // The first version executes at 7 cycles per iteration while the second
440   // version near 1 or 2 cycles.
441   template <int = 0, bool = std::is_pod<Element>::value>
442   class FastAdderImpl {
443    public:
FastAdderImpl(RepeatedField * rf)444     explicit FastAdderImpl(RepeatedField* rf) : repeated_field_(rf) {
445       index_ = repeated_field_->current_size_;
446       capacity_ = repeated_field_->total_size_;
447       buffer_ = repeated_field_->unsafe_elements();
448     }
~FastAdderImpl()449     ~FastAdderImpl() { repeated_field_->current_size_ = index_; }
450 
Add(Element val)451     void Add(Element val) {
452       if (index_ == capacity_) {
453         repeated_field_->current_size_ = index_;
454         repeated_field_->Reserve(index_ + 1);
455         capacity_ = repeated_field_->total_size_;
456         buffer_ = repeated_field_->unsafe_elements();
457       }
458       buffer_[index_++] = val;
459     }
460 
461    private:
462     RepeatedField* repeated_field_;
463     int index_;
464     int capacity_;
465     Element* buffer_;
466 
467     GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FastAdderImpl);
468   };
469 
470   // FastAdder is a wrapper for adding fields. The specialization above handles
471   // POD types more efficiently than RepeatedField.
472   template <int I>
473   class FastAdderImpl<I, false> {
474    public:
FastAdderImpl(RepeatedField * rf)475     explicit FastAdderImpl(RepeatedField* rf) : repeated_field_(rf) {}
Add(const Element & val)476     void Add(const Element& val) { repeated_field_->Add(val); }
477 
478    private:
479     RepeatedField* repeated_field_;
480     GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FastAdderImpl);
481   };
482 
483   using FastAdder = FastAdderImpl<>;
484 
485   friend class TestRepeatedFieldHelper;
486   friend class ::google::protobuf::internal::ParseContext;
487 };
488 
489 namespace internal {
490 template <typename It>
491 class RepeatedPtrIterator;
492 template <typename It, typename VoidPtr>
493 class RepeatedPtrOverPtrsIterator;
494 }  // namespace internal
495 
496 namespace internal {
497 
498 // This is a helper template to copy an array of elements efficiently when they
499 // have a trivial copy constructor, and correctly otherwise. This really
500 // shouldn't be necessary, but our compiler doesn't optimize std::copy very
501 // effectively.
502 template <typename Element,
503           bool HasTrivialCopy =
504               std::is_pod<Element>::value>
505 struct ElementCopier {
506   void operator()(Element* to, const Element* from, int array_size);
507 };
508 
509 }  // namespace internal
510 
511 namespace internal {
512 
513 // type-traits helper for RepeatedPtrFieldBase: we only want to invoke
514 // arena-related "copy if on different arena" behavior if the necessary methods
515 // exist on the contained type. In particular, we rely on MergeFrom() existing
516 // as a general proxy for the fact that a copy will work, and we also provide a
517 // specific override for std::string*.
518 template <typename T>
519 struct TypeImplementsMergeBehaviorProbeForMergeFrom {
520   typedef char HasMerge;
521   typedef long HasNoMerge;
522 
523   // We accept either of:
524   // - void MergeFrom(const T& other)
525   // - bool MergeFrom(const T& other)
526   //
527   // We mangle these names a bit to avoid compatibility issues in 'unclean'
528   // include environments that may have, e.g., "#define test ..." (yes, this
529   // exists).
530   template <typename U, typename RetType, RetType (U::*)(const U& arg)>
531   struct CheckType;
532   template <typename U>
533   static HasMerge Check(CheckType<U, void, &U::MergeFrom>*);
534   template <typename U>
535   static HasMerge Check(CheckType<U, bool, &U::MergeFrom>*);
536   template <typename U>
537   static HasNoMerge Check(...);
538 
539   // Resolves to either std::true_type or std::false_type.
540   typedef std::integral_constant<bool,
541                                  (sizeof(Check<T>(0)) == sizeof(HasMerge))>
542       type;
543 };
544 
545 template <typename T, typename = void>
546 struct TypeImplementsMergeBehavior
547     : TypeImplementsMergeBehaviorProbeForMergeFrom<T> {};
548 
549 
550 template <>
551 struct TypeImplementsMergeBehavior<std::string> {
552   typedef std::true_type type;
553 };
554 
555 template <typename T>
556 struct IsMovable
557     : std::integral_constant<bool, std::is_move_constructible<T>::value &&
558                                        std::is_move_assignable<T>::value> {};
559 
560 // This is the common base class for RepeatedPtrFields.  It deals only in void*
561 // pointers.  Users should not use this interface directly.
562 //
563 // The methods of this interface correspond to the methods of RepeatedPtrField,
564 // but may have a template argument called TypeHandler.  Its signature is:
565 //   class TypeHandler {
566 //    public:
567 //     typedef MyType Type;
568 //     static Type* New();
569 //     static Type* NewFromPrototype(const Type* prototype,
570 //                                       Arena* arena);
571 //     static void Delete(Type*);
572 //     static void Clear(Type*);
573 //     static void Merge(const Type& from, Type* to);
574 //
575 //     // Only needs to be implemented if SpaceUsedExcludingSelf() is called.
576 //     static int SpaceUsedLong(const Type&);
577 //   };
578 class PROTOBUF_EXPORT RepeatedPtrFieldBase {
579  protected:
580   constexpr RepeatedPtrFieldBase();
581   explicit RepeatedPtrFieldBase(Arena* arena);
582   ~RepeatedPtrFieldBase() {
583 #ifndef NDEBUG
584     // Try to trigger segfault / asan failure in non-opt builds. If arena_
585     // lifetime has ended before the destructor.
586     if (arena_) (void)arena_->SpaceAllocated();
587 #endif
588   }
589 
590  public:
591   // Must be called from destructor.
592   template <typename TypeHandler>
593   void Destroy();
594 
595  protected:
596   bool empty() const;
597   int size() const;
598 
599   template <typename TypeHandler>
600   const typename TypeHandler::Type& at(int index) const;
601   template <typename TypeHandler>
602   typename TypeHandler::Type& at(int index);
603 
604   template <typename TypeHandler>
605   typename TypeHandler::Type* Mutable(int index);
606   template <typename TypeHandler>
607   void Delete(int index);
608   template <typename TypeHandler>
609   typename TypeHandler::Type* Add(typename TypeHandler::Type* prototype = NULL);
610 
611  public:
612   // The next few methods are public so that they can be called from generated
613   // code when implicit weak fields are used, but they should never be called by
614   // application code.
615 
616   template <typename TypeHandler>
617   const typename TypeHandler::Type& Get(int index) const;
618 
619   // Creates and adds an element using the given prototype, without introducing
620   // a link-time dependency on the concrete message type. This method is used to
621   // implement implicit weak fields. The prototype may be NULL, in which case an
622   // ImplicitWeakMessage will be used as a placeholder.
623   MessageLite* AddWeak(const MessageLite* prototype);
624 
625   template <typename TypeHandler>
626   void Clear();
627 
628   template <typename TypeHandler>
629   void MergeFrom(const RepeatedPtrFieldBase& other);
630 
631   inline void InternalSwap(RepeatedPtrFieldBase* other);
632 
633  protected:
634   template <
635       typename TypeHandler,
636       typename std::enable_if<TypeHandler::Movable::value>::type* = nullptr>
637   void Add(typename TypeHandler::Type&& value);
638 
639   template <typename TypeHandler>
640   void RemoveLast();
641   template <typename TypeHandler>
642   void CopyFrom(const RepeatedPtrFieldBase& other);
643 
644   void CloseGap(int start, int num);
645 
646   void Reserve(int new_size);
647 
648   int Capacity() const;
649 
650   // Used for constructing iterators.
651   void* const* raw_data() const;
652   void** raw_mutable_data() const;
653 
654   template <typename TypeHandler>
655   typename TypeHandler::Type** mutable_data();
656   template <typename TypeHandler>
657   const typename TypeHandler::Type* const* data() const;
658 
659   template <typename TypeHandler>
660   PROTOBUF_ALWAYS_INLINE void Swap(RepeatedPtrFieldBase* other);
661 
662   void SwapElements(int index1, int index2);
663 
664   template <typename TypeHandler>
665   size_t SpaceUsedExcludingSelfLong() const;
666 
667   // Advanced memory management --------------------------------------
668 
669   // Like Add(), but if there are no cleared objects to use, returns NULL.
670   template <typename TypeHandler>
671   typename TypeHandler::Type* AddFromCleared();
672 
673   template <typename TypeHandler>
674   void AddAllocated(typename TypeHandler::Type* value) {
675     typename TypeImplementsMergeBehavior<typename TypeHandler::Type>::type t;
676     AddAllocatedInternal<TypeHandler>(value, t);
677   }
678 
679   template <typename TypeHandler>
680   void UnsafeArenaAddAllocated(typename TypeHandler::Type* value);
681 
682   template <typename TypeHandler>
683   typename TypeHandler::Type* ReleaseLast() {
684     typename TypeImplementsMergeBehavior<typename TypeHandler::Type>::type t;
685     return ReleaseLastInternal<TypeHandler>(t);
686   }
687 
688   // Releases last element and returns it, but does not do out-of-arena copy.
689   // And just returns the raw pointer to the contained element in the arena.
690   template <typename TypeHandler>
691   typename TypeHandler::Type* UnsafeArenaReleaseLast();
692 
693   int ClearedCount() const;
694   template <typename TypeHandler>
695   void AddCleared(typename TypeHandler::Type* value);
696   template <typename TypeHandler>
697   typename TypeHandler::Type* ReleaseCleared();
698 
699   template <typename TypeHandler>
700   void AddAllocatedInternal(typename TypeHandler::Type* value, std::true_type);
701   template <typename TypeHandler>
702   void AddAllocatedInternal(typename TypeHandler::Type* value, std::false_type);
703 
704   template <typename TypeHandler>
705   PROTOBUF_NOINLINE void AddAllocatedSlowWithCopy(
706       typename TypeHandler::Type* value, Arena* value_arena, Arena* my_arena);
707   template <typename TypeHandler>
708   PROTOBUF_NOINLINE void AddAllocatedSlowWithoutCopy(
709       typename TypeHandler::Type* value);
710 
711   template <typename TypeHandler>
712   typename TypeHandler::Type* ReleaseLastInternal(std::true_type);
713   template <typename TypeHandler>
714   typename TypeHandler::Type* ReleaseLastInternal(std::false_type);
715 
716   template <typename TypeHandler>
717   PROTOBUF_NOINLINE void SwapFallback(RepeatedPtrFieldBase* other);
718 
719   inline Arena* GetArena() const { return arena_; }
720 
721  private:
722   static constexpr int kInitialSize = 0;
723   // A few notes on internal representation:
724   //
725   // We use an indirected approach, with struct Rep, to keep
726   // sizeof(RepeatedPtrFieldBase) equivalent to what it was before arena support
727   // was added, namely, 3 8-byte machine words on x86-64. An instance of Rep is
728   // allocated only when the repeated field is non-empty, and it is a
729   // dynamically-sized struct (the header is directly followed by elements[]).
730   // We place arena_ and current_size_ directly in the object to avoid cache
731   // misses due to the indirection, because these fields are checked frequently.
732   // Placing all fields directly in the RepeatedPtrFieldBase instance costs
733   // significant performance for memory-sensitive workloads.
734   Arena* arena_;
735   int current_size_;
736   int total_size_;
737   struct Rep {
738     int allocated_size;
739     // Here we declare a huge array as a way of approximating C's "flexible
740     // array member" feature without relying on undefined behavior.
741     void* elements[(std::numeric_limits<int>::max() - 2 * sizeof(int)) /
742                    sizeof(void*)];
743   };
744   static constexpr size_t kRepHeaderSize = offsetof(Rep, elements);
745   Rep* rep_;
746 
747   template <typename TypeHandler>
748   static inline typename TypeHandler::Type* cast(void* element) {
749     return reinterpret_cast<typename TypeHandler::Type*>(element);
750   }
751   template <typename TypeHandler>
752   static inline const typename TypeHandler::Type* cast(const void* element) {
753     return reinterpret_cast<const typename TypeHandler::Type*>(element);
754   }
755 
756   // Non-templated inner function to avoid code duplication. Takes a function
757   // pointer to the type-specific (templated) inner allocate/merge loop.
758   void MergeFromInternal(const RepeatedPtrFieldBase& other,
759                          void (RepeatedPtrFieldBase::*inner_loop)(void**,
760                                                                   void**, int,
761                                                                   int));
762 
763   template <typename TypeHandler>
764   void MergeFromInnerLoop(void** our_elems, void** other_elems, int length,
765                           int already_allocated);
766 
767   // Internal helper: extend array space if necessary to contain |extend_amount|
768   // more elements, and return a pointer to the element immediately following
769   // the old list of elements.  This interface factors out common behavior from
770   // Reserve() and MergeFrom() to reduce code size. |extend_amount| must be > 0.
771   void** InternalExtend(int extend_amount);
772 
773   // The reflection implementation needs to call protected methods directly,
774   // reinterpreting pointers as being to Message instead of a specific Message
775   // subclass.
776   friend class ::PROTOBUF_NAMESPACE_ID::Reflection;
777 
778   // ExtensionSet stores repeated message extensions as
779   // RepeatedPtrField<MessageLite>, but non-lite ExtensionSets need to implement
780   // SpaceUsedLong(), and thus need to call SpaceUsedExcludingSelfLong()
781   // reinterpreting MessageLite as Message.  ExtensionSet also needs to make use
782   // of AddFromCleared(), which is not part of the public interface.
783   friend class ExtensionSet;
784 
785   // The MapFieldBase implementation needs to call protected methods directly,
786   // reinterpreting pointers as being to Message instead of a specific Message
787   // subclass.
788   friend class MapFieldBase;
789 
790   // The table-driven MergePartialFromCodedStream implementation needs to
791   // operate on RepeatedPtrField<MessageLite>.
792   friend class MergePartialFromCodedStreamHelper;
793   friend class AccessorHelper;
794   template <typename T>
795   friend struct google::protobuf::WeakRepeatedPtrField;
796 
797   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPtrFieldBase);
798 };
799 
800 template <typename GenericType>
801 class GenericTypeHandler {
802  public:
803   typedef GenericType Type;
804   using Movable = IsMovable<GenericType>;
805 
806   static inline GenericType* New(Arena* arena) {
807     return Arena::CreateMaybeMessage<Type>(arena);
808   }
809   static inline GenericType* New(Arena* arena, GenericType&& value) {
810     return Arena::Create<GenericType>(arena, std::move(value));
811   }
812   static inline GenericType* NewFromPrototype(const GenericType* prototype,
813                                               Arena* arena = NULL);
814   static inline void Delete(GenericType* value, Arena* arena) {
815     if (arena == NULL) {
816       delete value;
817     }
818   }
819   static inline Arena* GetArena(GenericType* value) {
820     return Arena::GetArena<Type>(value);
821   }
822   static inline void* GetMaybeArenaPointer(GenericType* value) {
823     return Arena::GetArena<Type>(value);
824   }
825 
826   static inline void Clear(GenericType* value) { value->Clear(); }
827   PROTOBUF_NOINLINE
828   static void Merge(const GenericType& from, GenericType* to);
829   static inline size_t SpaceUsedLong(const GenericType& value) {
830     return value.SpaceUsedLong();
831   }
832 };
833 
834 template <typename GenericType>
835 GenericType* GenericTypeHandler<GenericType>::NewFromPrototype(
836     const GenericType* /* prototype */, Arena* arena) {
837   return New(arena);
838 }
839 template <typename GenericType>
840 void GenericTypeHandler<GenericType>::Merge(const GenericType& from,
841                                             GenericType* to) {
842   to->MergeFrom(from);
843 }
844 
845 // NewFromPrototype() and Merge() are not defined inline here, as we will need
846 // to do a virtual function dispatch anyways to go from Message* to call
847 // New/Merge.
848 template <>
849 MessageLite* GenericTypeHandler<MessageLite>::NewFromPrototype(
850     const MessageLite* prototype, Arena* arena);
851 template <>
852 inline Arena* GenericTypeHandler<MessageLite>::GetArena(MessageLite* value) {
853   return value->GetArena();
854 }
855 template <>
856 inline void* GenericTypeHandler<MessageLite>::GetMaybeArenaPointer(
857     MessageLite* value) {
858   return value->GetMaybeArenaPointer();
859 }
860 template <>
861 void GenericTypeHandler<MessageLite>::Merge(const MessageLite& from,
862                                             MessageLite* to);
863 template <>
864 inline void GenericTypeHandler<std::string>::Clear(std::string* value) {
865   value->clear();
866 }
867 template <>
868 void GenericTypeHandler<std::string>::Merge(const std::string& from,
869                                             std::string* to);
870 
871 // Message specialization bodies defined in message.cc. This split is necessary
872 // to allow proto2-lite (which includes this header) to be independent of
873 // Message.
874 template <>
875 PROTOBUF_EXPORT Message* GenericTypeHandler<Message>::NewFromPrototype(
876     const Message* prototype, Arena* arena);
877 template <>
878 PROTOBUF_EXPORT Arena* GenericTypeHandler<Message>::GetArena(Message* value);
879 template <>
880 PROTOBUF_EXPORT void* GenericTypeHandler<Message>::GetMaybeArenaPointer(
881     Message* value);
882 
883 class StringTypeHandler {
884  public:
885   typedef std::string Type;
886   using Movable = IsMovable<Type>;
887 
888   static inline std::string* New(Arena* arena) {
889     return Arena::Create<std::string>(arena);
890   }
891   static inline std::string* New(Arena* arena, std::string&& value) {
892     return Arena::Create<std::string>(arena, std::move(value));
893   }
894   static inline std::string* NewFromPrototype(const std::string*,
895                                               Arena* arena) {
896     return New(arena);
897   }
898   static inline Arena* GetArena(std::string*) { return NULL; }
899   static inline void* GetMaybeArenaPointer(std::string* /* value */) {
900     return NULL;
901   }
902   static inline void Delete(std::string* value, Arena* arena) {
903     if (arena == NULL) {
904       delete value;
905     }
906   }
907   static inline void Clear(std::string* value) { value->clear(); }
908   static inline void Merge(const std::string& from, std::string* to) {
909     *to = from;
910   }
911   static size_t SpaceUsedLong(const std::string& value) {
912     return sizeof(value) + StringSpaceUsedExcludingSelfLong(value);
913   }
914 };
915 
916 }  // namespace internal
917 
918 // RepeatedPtrField is like RepeatedField, but used for repeated strings or
919 // Messages.
920 template <typename Element>
921 class RepeatedPtrField final : private internal::RepeatedPtrFieldBase {
922  public:
923   constexpr RepeatedPtrField();
924   explicit RepeatedPtrField(Arena* arena);
925 
926   RepeatedPtrField(const RepeatedPtrField& other);
927   template <typename Iter>
928   RepeatedPtrField(Iter begin, const Iter& end);
929   ~RepeatedPtrField();
930 
931   RepeatedPtrField& operator=(const RepeatedPtrField& other);
932 
933   RepeatedPtrField(RepeatedPtrField&& other) noexcept;
934   RepeatedPtrField& operator=(RepeatedPtrField&& other) noexcept;
935 
936   bool empty() const;
937   int size() const;
938 
939   const Element& Get(int index) const;
940   Element* Mutable(int index);
941   Element* Add();
942   void Add(Element&& value);
943 
944   const Element& operator[](int index) const { return Get(index); }
945   Element& operator[](int index) { return *Mutable(index); }
946 
947   const Element& at(int index) const;
948   Element& at(int index);
949 
950   // Remove the last element in the array.
951   // Ownership of the element is retained by the array.
952   void RemoveLast();
953 
954   // Delete elements with indices in the range [start .. start+num-1].
955   // Caution: implementation moves all elements with indices [start+num .. ].
956   // Calling this routine inside a loop can cause quadratic behavior.
957   void DeleteSubrange(int start, int num);
958 
959   void Clear();
960   void MergeFrom(const RepeatedPtrField& other);
961   void CopyFrom(const RepeatedPtrField& other);
962 
963   // Reserve space to expand the field to at least the given size.  This only
964   // resizes the pointer array; it doesn't allocate any objects.  If the
965   // array is grown, it will always be at least doubled in size.
966   void Reserve(int new_size);
967 
968   int Capacity() const;
969 
970   // Gets the underlying array.  This pointer is possibly invalidated by
971   // any add or remove operation.
972   Element** mutable_data();
973   const Element* const* data() const;
974 
975   // Swap entire contents with "other". If they are on separate arenas, then
976   // copies data.
977   void Swap(RepeatedPtrField* other);
978 
979   // Swap entire contents with "other". Caller should guarantee that either both
980   // fields are on the same arena or both are on the heap. Swapping between
981   // different arenas with this function is disallowed and is caught via
982   // GOOGLE_DCHECK.
983   void UnsafeArenaSwap(RepeatedPtrField* other);
984 
985   // Swap two elements.
986   void SwapElements(int index1, int index2);
987 
988   // STL-like iterator support
989   typedef internal::RepeatedPtrIterator<Element> iterator;
990   typedef internal::RepeatedPtrIterator<const Element> const_iterator;
991   typedef Element value_type;
992   typedef value_type& reference;
993   typedef const value_type& const_reference;
994   typedef value_type* pointer;
995   typedef const value_type* const_pointer;
996   typedef int size_type;
997   typedef ptrdiff_t difference_type;
998 
999   iterator begin();
1000   const_iterator begin() const;
1001   const_iterator cbegin() const;
1002   iterator end();
1003   const_iterator end() const;
1004   const_iterator cend() const;
1005 
1006   // Reverse iterator support
1007   typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
1008   typedef std::reverse_iterator<iterator> reverse_iterator;
1009   reverse_iterator rbegin() { return reverse_iterator(end()); }
1010   const_reverse_iterator rbegin() const {
1011     return const_reverse_iterator(end());
1012   }
1013   reverse_iterator rend() { return reverse_iterator(begin()); }
1014   const_reverse_iterator rend() const {
1015     return const_reverse_iterator(begin());
1016   }
1017 
1018   // Custom STL-like iterator that iterates over and returns the underlying
1019   // pointers to Element rather than Element itself.
1020   typedef internal::RepeatedPtrOverPtrsIterator<Element*, void*>
1021       pointer_iterator;
1022   typedef internal::RepeatedPtrOverPtrsIterator<const Element* const,
1023                                                 const void* const>
1024       const_pointer_iterator;
1025   pointer_iterator pointer_begin();
1026   const_pointer_iterator pointer_begin() const;
1027   pointer_iterator pointer_end();
1028   const_pointer_iterator pointer_end() const;
1029 
1030   // Returns (an estimate of) the number of bytes used by the repeated field,
1031   // excluding sizeof(*this).
1032   size_t SpaceUsedExcludingSelfLong() const;
1033 
1034   int SpaceUsedExcludingSelf() const {
1035     return internal::ToIntSize(SpaceUsedExcludingSelfLong());
1036   }
1037 
1038   // Advanced memory management --------------------------------------
1039   // When hardcore memory management becomes necessary -- as it sometimes
1040   // does here at Google -- the following methods may be useful.
1041 
1042   // Add an already-allocated object, passing ownership to the
1043   // RepeatedPtrField.
1044   //
1045   // Note that some special behavior occurs with respect to arenas:
1046   //
1047   //   (i) if this field holds submessages, the new submessage will be copied if
1048   //   the original is in an arena and this RepeatedPtrField is either in a
1049   //   different arena, or on the heap.
1050   //   (ii) if this field holds strings, the passed-in string *must* be
1051   //   heap-allocated, not arena-allocated. There is no way to dynamically check
1052   //   this at runtime, so User Beware.
1053   void AddAllocated(Element* value);
1054 
1055   // Remove the last element and return it, passing ownership to the caller.
1056   // Requires:  size() > 0
1057   //
1058   // If this RepeatedPtrField is on an arena, an object copy is required to pass
1059   // ownership back to the user (for compatible semantics). Use
1060   // UnsafeArenaReleaseLast() if this behavior is undesired.
1061   Element* ReleaseLast();
1062 
1063   // Add an already-allocated object, skipping arena-ownership checks. The user
1064   // must guarantee that the given object is in the same arena as this
1065   // RepeatedPtrField.
1066   // It is also useful in legacy code that uses temporary ownership to avoid
1067   // copies. Example:
1068   //   RepeatedPtrField<T> temp_field;
1069   //   temp_field.AddAllocated(new T);
1070   //   ... // Do something with temp_field
1071   //   temp_field.ExtractSubrange(0, temp_field.size(), nullptr);
1072   // If you put temp_field on the arena this fails, because the ownership
1073   // transfers to the arena at the "AddAllocated" call and is not released
1074   // anymore causing a double delete. UnsafeArenaAddAllocated prevents this.
1075   void UnsafeArenaAddAllocated(Element* value);
1076 
1077   // Remove the last element and return it.  Works only when operating on an
1078   // arena. The returned pointer is to the original object in the arena, hence
1079   // has the arena's lifetime.
1080   // Requires:  current_size_ > 0
1081   Element* UnsafeArenaReleaseLast();
1082 
1083   // Extract elements with indices in the range "[start .. start+num-1]".
1084   // The caller assumes ownership of the extracted elements and is responsible
1085   // for deleting them when they are no longer needed.
1086   // If "elements" is non-NULL, then pointers to the extracted elements
1087   // are stored in "elements[0 .. num-1]" for the convenience of the caller.
1088   // If "elements" is NULL, then the caller must use some other mechanism
1089   // to perform any further operations (like deletion) on these elements.
1090   // Caution: implementation also moves elements with indices [start+num ..].
1091   // Calling this routine inside a loop can cause quadratic behavior.
1092   //
1093   // Memory copying behavior is identical to ReleaseLast(), described above: if
1094   // this RepeatedPtrField is on an arena, an object copy is performed for each
1095   // returned element, so that all returned element pointers are to
1096   // heap-allocated copies. If this copy is not desired, the user should call
1097   // UnsafeArenaExtractSubrange().
1098   void ExtractSubrange(int start, int num, Element** elements);
1099 
1100   // Identical to ExtractSubrange() described above, except that when this
1101   // repeated field is on an arena, no object copies are performed. Instead, the
1102   // raw object pointers are returned. Thus, if on an arena, the returned
1103   // objects must not be freed, because they will not be heap-allocated objects.
1104   void UnsafeArenaExtractSubrange(int start, int num, Element** elements);
1105 
1106   // When elements are removed by calls to RemoveLast() or Clear(), they
1107   // are not actually freed.  Instead, they are cleared and kept so that
1108   // they can be reused later.  This can save lots of CPU time when
1109   // repeatedly reusing a protocol message for similar purposes.
1110   //
1111   // Hardcore programs may choose to manipulate these cleared objects
1112   // to better optimize memory management using the following routines.
1113 
1114   // Get the number of cleared objects that are currently being kept
1115   // around for reuse.
1116   int ClearedCount() const;
1117   // Add an element to the pool of cleared objects, passing ownership to
1118   // the RepeatedPtrField.  The element must be cleared prior to calling
1119   // this method.
1120   //
1121   // This method cannot be called when the repeated field is on an arena or when
1122   // |value| is; both cases will trigger a GOOGLE_DCHECK-failure.
1123   void AddCleared(Element* value);
1124   // Remove a single element from the cleared pool and return it, passing
1125   // ownership to the caller.  The element is guaranteed to be cleared.
1126   // Requires:  ClearedCount() > 0
1127   //
1128   //
1129   // This method cannot be called when the repeated field is on an arena; doing
1130   // so will trigger a GOOGLE_DCHECK-failure.
1131   Element* ReleaseCleared();
1132 
1133   // Removes the element referenced by position.
1134   //
1135   // Returns an iterator to the element immediately following the removed
1136   // element.
1137   //
1138   // Invalidates all iterators at or after the removed element, including end().
1139   iterator erase(const_iterator position);
1140 
1141   // Removes the elements in the range [first, last).
1142   //
1143   // Returns an iterator to the element immediately following the removed range.
1144   //
1145   // Invalidates all iterators at or after the removed range, including end().
1146   iterator erase(const_iterator first, const_iterator last);
1147 
1148   // Gets the arena on which this RepeatedPtrField stores its elements.
1149   inline Arena* GetArena() const;
1150 
1151   // For internal use only.
1152   //
1153   // This is public due to it being called by generated code.
1154   void InternalSwap(RepeatedPtrField* other) {
1155     internal::RepeatedPtrFieldBase::InternalSwap(other);
1156   }
1157 
1158  private:
1159   // Note:  RepeatedPtrField SHOULD NOT be subclassed by users.
1160   class TypeHandler;
1161 
1162   // Implementations for ExtractSubrange(). The copying behavior must be
1163   // included only if the type supports the necessary operations (e.g.,
1164   // MergeFrom()), so we must resolve this at compile time. ExtractSubrange()
1165   // uses SFINAE to choose one of the below implementations.
1166   void ExtractSubrangeInternal(int start, int num, Element** elements,
1167                                std::true_type);
1168   void ExtractSubrangeInternal(int start, int num, Element** elements,
1169                                std::false_type);
1170 
1171   friend class Arena;
1172 
1173   template <typename T>
1174   friend struct WeakRepeatedPtrField;
1175 
1176   typedef void InternalArenaConstructable_;
1177 
1178 };
1179 
1180 // implementation ====================================================
1181 
1182 template <typename Element>
1183 constexpr RepeatedField<Element>::RepeatedField()
1184     : current_size_(0), total_size_(0), arena_or_elements_(nullptr) {}
1185 
1186 template <typename Element>
1187 inline RepeatedField<Element>::RepeatedField(Arena* arena)
1188     : current_size_(0), total_size_(0), arena_or_elements_(arena) {}
1189 
1190 template <typename Element>
1191 inline RepeatedField<Element>::RepeatedField(const RepeatedField& other)
1192     : current_size_(0), total_size_(0), arena_or_elements_(nullptr) {
1193   if (other.current_size_ != 0) {
1194     Reserve(other.size());
1195     AddNAlreadyReserved(other.size());
1196     CopyArray(Mutable(0), &other.Get(0), other.size());
1197   }
1198 }
1199 
1200 template <typename Element>
1201 template <typename Iter>
1202 RepeatedField<Element>::RepeatedField(Iter begin, const Iter& end)
1203     : current_size_(0), total_size_(0), arena_or_elements_(nullptr) {
1204   Add(begin, end);
1205 }
1206 
1207 template <typename Element>
1208 RepeatedField<Element>::~RepeatedField() {
1209   if (total_size_ > 0) {
1210     InternalDeallocate(rep(), total_size_);
1211   }
1212 }
1213 
1214 template <typename Element>
1215 inline RepeatedField<Element>& RepeatedField<Element>::operator=(
1216     const RepeatedField& other) {
1217   if (this != &other) CopyFrom(other);
1218   return *this;
1219 }
1220 
1221 template <typename Element>
1222 inline RepeatedField<Element>::RepeatedField(RepeatedField&& other) noexcept
1223     : RepeatedField() {
1224   // We don't just call Swap(&other) here because it would perform 3 copies if
1225   // other is on an arena. This field can't be on an arena because arena
1226   // construction always uses the Arena* accepting constructor.
1227   if (other.GetArena()) {
1228     CopyFrom(other);
1229   } else {
1230     InternalSwap(&other);
1231   }
1232 }
1233 
1234 template <typename Element>
1235 inline RepeatedField<Element>& RepeatedField<Element>::operator=(
1236     RepeatedField&& other) noexcept {
1237   // We don't just call Swap(&other) here because it would perform 3 copies if
1238   // the two fields are on different arenas.
1239   if (this != &other) {
1240     if (this->GetArena() != other.GetArena()) {
1241       CopyFrom(other);
1242     } else {
1243       InternalSwap(&other);
1244     }
1245   }
1246   return *this;
1247 }
1248 
1249 template <typename Element>
1250 inline bool RepeatedField<Element>::empty() const {
1251   return current_size_ == 0;
1252 }
1253 
1254 template <typename Element>
1255 inline int RepeatedField<Element>::size() const {
1256   return current_size_;
1257 }
1258 
1259 template <typename Element>
1260 inline int RepeatedField<Element>::Capacity() const {
1261   return total_size_;
1262 }
1263 
1264 template <typename Element>
1265 inline void RepeatedField<Element>::AddAlreadyReserved(const Element& value) {
1266   GOOGLE_DCHECK_LT(current_size_, total_size_);
1267   elements()[current_size_++] = value;
1268 }
1269 
1270 template <typename Element>
1271 inline Element* RepeatedField<Element>::AddAlreadyReserved() {
1272   GOOGLE_DCHECK_LT(current_size_, total_size_);
1273   return &elements()[current_size_++];
1274 }
1275 
1276 template <typename Element>
1277 inline Element* RepeatedField<Element>::AddNAlreadyReserved(int n) {
1278   GOOGLE_DCHECK_GE(total_size_ - current_size_, n)
1279       << total_size_ << ", " << current_size_;
1280   // Warning: sometimes people call this when n == 0 and total_size_ == 0. In
1281   // this case the return pointer points to a zero size array (n == 0). Hence
1282   // we can just use unsafe_elements(), because the user cannot dereference the
1283   // pointer anyway.
1284   Element* ret = unsafe_elements() + current_size_;
1285   current_size_ += n;
1286   return ret;
1287 }
1288 
1289 template <typename Element>
1290 inline void RepeatedField<Element>::Resize(int new_size, const Element& value) {
1291   GOOGLE_DCHECK_GE(new_size, 0);
1292   if (new_size > current_size_) {
1293     Reserve(new_size);
1294     std::fill(&elements()[current_size_], &elements()[new_size], value);
1295   }
1296   current_size_ = new_size;
1297 }
1298 
1299 template <typename Element>
1300 inline const Element& RepeatedField<Element>::Get(int index) const {
1301   GOOGLE_DCHECK_GE(index, 0);
1302   GOOGLE_DCHECK_LT(index, current_size_);
1303   return elements()[index];
1304 }
1305 
1306 template <typename Element>
1307 inline const Element& RepeatedField<Element>::at(int index) const {
1308   GOOGLE_CHECK_GE(index, 0);
1309   GOOGLE_CHECK_LT(index, current_size_);
1310   return elements()[index];
1311 }
1312 
1313 template <typename Element>
1314 inline Element& RepeatedField<Element>::at(int index) {
1315   GOOGLE_CHECK_GE(index, 0);
1316   GOOGLE_CHECK_LT(index, current_size_);
1317   return elements()[index];
1318 }
1319 
1320 template <typename Element>
1321 inline Element* RepeatedField<Element>::Mutable(int index) {
1322   GOOGLE_DCHECK_GE(index, 0);
1323   GOOGLE_DCHECK_LT(index, current_size_);
1324   return &elements()[index];
1325 }
1326 
1327 template <typename Element>
1328 inline void RepeatedField<Element>::Set(int index, const Element& value) {
1329   GOOGLE_DCHECK_GE(index, 0);
1330   GOOGLE_DCHECK_LT(index, current_size_);
1331   elements()[index] = value;
1332 }
1333 
1334 template <typename Element>
1335 inline void RepeatedField<Element>::Add(const Element& value) {
1336   uint32 size = current_size_;
1337   if (static_cast<int>(size) == total_size_) {
1338     // value could reference an element of the array. Reserving new space will
1339     // invalidate the reference. So we must make a copy first.
1340     auto tmp = value;
1341     Reserve(total_size_ + 1);
1342     elements()[size] = std::move(tmp);
1343   } else {
1344     elements()[size] = value;
1345   }
1346   current_size_ = size + 1;
1347 }
1348 
1349 template <typename Element>
1350 inline Element* RepeatedField<Element>::Add() {
1351   uint32 size = current_size_;
1352   if (static_cast<int>(size) == total_size_) Reserve(total_size_ + 1);
1353   auto ptr = &elements()[size];
1354   current_size_ = size + 1;
1355   return ptr;
1356 }
1357 
1358 template <typename Element>
1359 template <typename Iter>
1360 inline void RepeatedField<Element>::Add(Iter begin, Iter end) {
1361   int reserve = internal::CalculateReserve(begin, end);
1362   if (reserve != -1) {
1363     if (reserve == 0) {
1364       return;
1365     }
1366 
1367     Reserve(reserve + size());
1368     // TODO(ckennelly):  The compiler loses track of the buffer freshly
1369     // allocated by Reserve() by the time we call elements, so it cannot
1370     // guarantee that elements does not alias [begin(), end()).
1371     //
1372     // If restrict is available, annotating the pointer obtained from elements()
1373     // causes this to lower to memcpy instead of memmove.
1374     std::copy(begin, end, elements() + size());
1375     current_size_ = reserve + size();
1376   } else {
1377     FastAdder fast_adder(this);
1378     for (; begin != end; ++begin) fast_adder.Add(*begin);
1379   }
1380 }
1381 
1382 template <typename Element>
1383 inline void RepeatedField<Element>::RemoveLast() {
1384   GOOGLE_DCHECK_GT(current_size_, 0);
1385   current_size_--;
1386 }
1387 
1388 template <typename Element>
1389 void RepeatedField<Element>::ExtractSubrange(int start, int num,
1390                                              Element* elements) {
1391   GOOGLE_DCHECK_GE(start, 0);
1392   GOOGLE_DCHECK_GE(num, 0);
1393   GOOGLE_DCHECK_LE(start + num, this->current_size_);
1394 
1395   // Save the values of the removed elements if requested.
1396   if (elements != NULL) {
1397     for (int i = 0; i < num; ++i) elements[i] = this->Get(i + start);
1398   }
1399 
1400   // Slide remaining elements down to fill the gap.
1401   if (num > 0) {
1402     for (int i = start + num; i < this->current_size_; ++i)
1403       this->Set(i - num, this->Get(i));
1404     this->Truncate(this->current_size_ - num);
1405   }
1406 }
1407 
1408 template <typename Element>
1409 inline void RepeatedField<Element>::Clear() {
1410   current_size_ = 0;
1411 }
1412 
1413 template <typename Element>
1414 inline void RepeatedField<Element>::MergeFrom(const RepeatedField& other) {
1415   GOOGLE_DCHECK_NE(&other, this);
1416   if (other.current_size_ != 0) {
1417     int existing_size = size();
1418     Reserve(existing_size + other.size());
1419     AddNAlreadyReserved(other.size());
1420     CopyArray(Mutable(existing_size), &other.Get(0), other.size());
1421   }
1422 }
1423 
1424 template <typename Element>
1425 inline void RepeatedField<Element>::CopyFrom(const RepeatedField& other) {
1426   if (&other == this) return;
1427   Clear();
1428   MergeFrom(other);
1429 }
1430 
1431 template <typename Element>
1432 inline typename RepeatedField<Element>::iterator RepeatedField<Element>::erase(
1433     const_iterator position) {
1434   return erase(position, position + 1);
1435 }
1436 
1437 template <typename Element>
1438 inline typename RepeatedField<Element>::iterator RepeatedField<Element>::erase(
1439     const_iterator first, const_iterator last) {
1440   size_type first_offset = first - cbegin();
1441   if (first != last) {
1442     Truncate(std::copy(last, cend(), begin() + first_offset) - cbegin());
1443   }
1444   return begin() + first_offset;
1445 }
1446 
1447 template <typename Element>
1448 inline Element* RepeatedField<Element>::mutable_data() {
1449   return unsafe_elements();
1450 }
1451 
1452 template <typename Element>
1453 inline const Element* RepeatedField<Element>::data() const {
1454   return unsafe_elements();
1455 }
1456 
1457 template <typename Element>
1458 inline void RepeatedField<Element>::InternalSwap(RepeatedField* other) {
1459   GOOGLE_DCHECK(this != other);
1460   GOOGLE_DCHECK(GetArena() == other->GetArena());
1461 
1462   // Swap all fields at once.
1463   static_assert(std::is_standard_layout<RepeatedField<Element>>::value,
1464                 "offsetof() requires standard layout before c++17");
1465   internal::memswap<offsetof(RepeatedField, arena_or_elements_) +
1466                     sizeof(this->arena_or_elements_) -
1467                     offsetof(RepeatedField, current_size_)>(
1468       reinterpret_cast<char*>(this) + offsetof(RepeatedField, current_size_),
1469       reinterpret_cast<char*>(other) + offsetof(RepeatedField, current_size_));
1470 }
1471 
1472 template <typename Element>
1473 void RepeatedField<Element>::Swap(RepeatedField* other) {
1474   if (this == other) return;
1475   if (GetArena() == other->GetArena()) {
1476     InternalSwap(other);
1477   } else {
1478     RepeatedField<Element> temp(other->GetArena());
1479     temp.MergeFrom(*this);
1480     CopyFrom(*other);
1481     other->UnsafeArenaSwap(&temp);
1482   }
1483 }
1484 
1485 template <typename Element>
1486 void RepeatedField<Element>::UnsafeArenaSwap(RepeatedField* other) {
1487   if (this == other) return;
1488   InternalSwap(other);
1489 }
1490 
1491 template <typename Element>
1492 void RepeatedField<Element>::SwapElements(int index1, int index2) {
1493   using std::swap;  // enable ADL with fallback
1494   swap(elements()[index1], elements()[index2]);
1495 }
1496 
1497 template <typename Element>
1498 inline typename RepeatedField<Element>::iterator
1499 RepeatedField<Element>::begin() {
1500   return unsafe_elements();
1501 }
1502 template <typename Element>
1503 inline typename RepeatedField<Element>::const_iterator
1504 RepeatedField<Element>::begin() const {
1505   return unsafe_elements();
1506 }
1507 template <typename Element>
1508 inline typename RepeatedField<Element>::const_iterator
1509 RepeatedField<Element>::cbegin() const {
1510   return unsafe_elements();
1511 }
1512 template <typename Element>
1513 inline typename RepeatedField<Element>::iterator RepeatedField<Element>::end() {
1514   return unsafe_elements() + current_size_;
1515 }
1516 template <typename Element>
1517 inline typename RepeatedField<Element>::const_iterator
1518 RepeatedField<Element>::end() const {
1519   return unsafe_elements() + current_size_;
1520 }
1521 template <typename Element>
1522 inline typename RepeatedField<Element>::const_iterator
1523 RepeatedField<Element>::cend() const {
1524   return unsafe_elements() + current_size_;
1525 }
1526 
1527 template <typename Element>
1528 inline size_t RepeatedField<Element>::SpaceUsedExcludingSelfLong() const {
1529   return total_size_ > 0 ? (total_size_ * sizeof(Element) + kRepHeaderSize) : 0;
1530 }
1531 
1532 namespace internal {
1533 // Returns the new size for a reserved field based on its 'total_size' and the
1534 // requested 'new_size'. The result is clamped to the closed interval:
1535 //   [internal::kMinRepeatedFieldAllocationSize,
1536 //    std::numeric_limits<int>::max()]
1537 // Requires:
1538 //     new_size > total_size &&
1539 //     (total_size == 0 ||
1540 //      total_size >= kRepeatedFieldLowerClampLimit)
1541 inline int CalculateReserveSize(int total_size, int new_size) {
1542   if (new_size < kRepeatedFieldLowerClampLimit) {
1543     // Clamp to smallest allowed size.
1544     return kRepeatedFieldLowerClampLimit;
1545   }
1546   if (total_size < kRepeatedFieldUpperClampLimit) {
1547     return std::max(total_size * 2, new_size);
1548   } else {
1549     // Clamp to largest allowed size.
1550     GOOGLE_DCHECK_GT(new_size, kRepeatedFieldUpperClampLimit);
1551     return std::numeric_limits<int>::max();
1552   }
1553 }
1554 }  // namespace internal
1555 
1556 // Avoid inlining of Reserve(): new, copy, and delete[] lead to a significant
1557 // amount of code bloat.
1558 template <typename Element>
1559 void RepeatedField<Element>::Reserve(int new_size) {
1560   if (total_size_ >= new_size) return;
1561   Rep* old_rep = total_size_ > 0 ? rep() : NULL;
1562   Rep* new_rep;
1563   Arena* arena = GetArena();
1564   new_size = internal::CalculateReserveSize(total_size_, new_size);
1565   GOOGLE_DCHECK_LE(
1566       static_cast<size_t>(new_size),
1567       (std::numeric_limits<size_t>::max() - kRepHeaderSize) / sizeof(Element))
1568       << "Requested size is too large to fit into size_t.";
1569   size_t bytes =
1570       kRepHeaderSize + sizeof(Element) * static_cast<size_t>(new_size);
1571   if (arena == NULL) {
1572     new_rep = static_cast<Rep*>(::operator new(bytes));
1573   } else {
1574     new_rep = reinterpret_cast<Rep*>(Arena::CreateArray<char>(arena, bytes));
1575   }
1576   new_rep->arena = arena;
1577   int old_total_size = total_size_;
1578   // Already known: new_size >= internal::kMinRepeatedFieldAllocationSize
1579   // Maintain invariant:
1580   //     total_size_ == 0 ||
1581   //     total_size_ >= internal::kMinRepeatedFieldAllocationSize
1582   total_size_ = new_size;
1583   arena_or_elements_ = new_rep->elements;
1584   // Invoke placement-new on newly allocated elements. We shouldn't have to do
1585   // this, since Element is supposed to be POD, but a previous version of this
1586   // code allocated storage with "new Element[size]" and some code uses
1587   // RepeatedField with non-POD types, relying on constructor invocation. If
1588   // Element has a trivial constructor (e.g., int32), gcc (tested with -O2)
1589   // completely removes this loop because the loop body is empty, so this has no
1590   // effect unless its side-effects are required for correctness.
1591   // Note that we do this before MoveArray() below because Element's copy
1592   // assignment implementation will want an initialized instance first.
1593   Element* e = &elements()[0];
1594   Element* limit = e + total_size_;
1595   for (; e < limit; e++) {
1596     new (e) Element;
1597   }
1598   if (current_size_ > 0) {
1599     MoveArray(&elements()[0], old_rep->elements, current_size_);
1600   }
1601 
1602   // Likewise, we need to invoke destructors on the old array.
1603   InternalDeallocate(old_rep, old_total_size);
1604 
1605 }
1606 
1607 template <typename Element>
1608 inline void RepeatedField<Element>::Truncate(int new_size) {
1609   GOOGLE_DCHECK_LE(new_size, current_size_);
1610   if (current_size_ > 0) {
1611     current_size_ = new_size;
1612   }
1613 }
1614 
1615 template <typename Element>
1616 inline void RepeatedField<Element>::MoveArray(Element* to, Element* from,
1617                                               int array_size) {
1618   CopyArray(to, from, array_size);
1619 }
1620 
1621 template <typename Element>
1622 inline void RepeatedField<Element>::CopyArray(Element* to, const Element* from,
1623                                               int array_size) {
1624   internal::ElementCopier<Element>()(to, from, array_size);
1625 }
1626 
1627 namespace internal {
1628 
1629 template <typename Element, bool HasTrivialCopy>
1630 void ElementCopier<Element, HasTrivialCopy>::operator()(Element* to,
1631                                                         const Element* from,
1632                                                         int array_size) {
1633   std::copy(from, from + array_size, to);
1634 }
1635 
1636 template <typename Element>
1637 struct ElementCopier<Element, true> {
1638   void operator()(Element* to, const Element* from, int array_size) {
1639     memcpy(to, from, static_cast<size_t>(array_size) * sizeof(Element));
1640   }
1641 };
1642 
1643 }  // namespace internal
1644 
1645 
1646 // -------------------------------------------------------------------
1647 
1648 namespace internal {
1649 
1650 constexpr RepeatedPtrFieldBase::RepeatedPtrFieldBase()
1651     : arena_(NULL), current_size_(0), total_size_(0), rep_(NULL) {}
1652 
1653 inline RepeatedPtrFieldBase::RepeatedPtrFieldBase(Arena* arena)
1654     : arena_(arena), current_size_(0), total_size_(0), rep_(NULL) {}
1655 
1656 template <typename TypeHandler>
1657 void RepeatedPtrFieldBase::Destroy() {
1658   if (rep_ != NULL && arena_ == NULL) {
1659     int n = rep_->allocated_size;
1660     void* const* elements = rep_->elements;
1661     for (int i = 0; i < n; i++) {
1662       TypeHandler::Delete(cast<TypeHandler>(elements[i]), NULL);
1663     }
1664 #if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
1665     const size_t size = total_size_ * sizeof(elements[0]) + kRepHeaderSize;
1666     ::operator delete(static_cast<void*>(rep_), size);
1667 #else
1668     ::operator delete(static_cast<void*>(rep_));
1669 #endif
1670   }
1671   rep_ = NULL;
1672 }
1673 
1674 template <typename TypeHandler>
1675 inline void RepeatedPtrFieldBase::Swap(RepeatedPtrFieldBase* other) {
1676   if (other->GetArena() == GetArena()) {
1677     InternalSwap(other);
1678   } else {
1679     SwapFallback<TypeHandler>(other);
1680   }
1681 }
1682 
1683 template <typename TypeHandler>
1684 void RepeatedPtrFieldBase::SwapFallback(RepeatedPtrFieldBase* other) {
1685   GOOGLE_DCHECK(other->GetArena() != GetArena());
1686 
1687   // Copy semantics in this case. We try to improve efficiency by placing the
1688   // temporary on |other|'s arena so that messages are copied twice rather than
1689   // three times.
1690   RepeatedPtrFieldBase temp(other->GetArena());
1691   temp.MergeFrom<TypeHandler>(*this);
1692   this->Clear<TypeHandler>();
1693   this->MergeFrom<TypeHandler>(*other);
1694   other->InternalSwap(&temp);
1695   temp.Destroy<TypeHandler>();  // Frees rep_ if `other` had no arena.
1696 }
1697 
1698 inline bool RepeatedPtrFieldBase::empty() const { return current_size_ == 0; }
1699 
1700 inline int RepeatedPtrFieldBase::size() const { return current_size_; }
1701 
1702 template <typename TypeHandler>
1703 inline const typename TypeHandler::Type& RepeatedPtrFieldBase::Get(
1704     int index) const {
1705   GOOGLE_DCHECK_GE(index, 0);
1706   GOOGLE_DCHECK_LT(index, current_size_);
1707   return *cast<TypeHandler>(rep_->elements[index]);
1708 }
1709 
1710 template <typename TypeHandler>
1711 inline const typename TypeHandler::Type& RepeatedPtrFieldBase::at(
1712     int index) const {
1713   GOOGLE_CHECK_GE(index, 0);
1714   GOOGLE_CHECK_LT(index, current_size_);
1715   return *cast<TypeHandler>(rep_->elements[index]);
1716 }
1717 
1718 template <typename TypeHandler>
1719 inline typename TypeHandler::Type& RepeatedPtrFieldBase::at(int index) {
1720   GOOGLE_CHECK_GE(index, 0);
1721   GOOGLE_CHECK_LT(index, current_size_);
1722   return *cast<TypeHandler>(rep_->elements[index]);
1723 }
1724 
1725 template <typename TypeHandler>
1726 inline typename TypeHandler::Type* RepeatedPtrFieldBase::Mutable(int index) {
1727   GOOGLE_DCHECK_GE(index, 0);
1728   GOOGLE_DCHECK_LT(index, current_size_);
1729   return cast<TypeHandler>(rep_->elements[index]);
1730 }
1731 
1732 template <typename TypeHandler>
1733 inline void RepeatedPtrFieldBase::Delete(int index) {
1734   GOOGLE_DCHECK_GE(index, 0);
1735   GOOGLE_DCHECK_LT(index, current_size_);
1736   TypeHandler::Delete(cast<TypeHandler>(rep_->elements[index]), arena_);
1737 }
1738 
1739 template <typename TypeHandler>
1740 inline typename TypeHandler::Type* RepeatedPtrFieldBase::Add(
1741     typename TypeHandler::Type* prototype) {
1742   if (rep_ != NULL && current_size_ < rep_->allocated_size) {
1743     return cast<TypeHandler>(rep_->elements[current_size_++]);
1744   }
1745   if (!rep_ || rep_->allocated_size == total_size_) {
1746     Reserve(total_size_ + 1);
1747   }
1748   ++rep_->allocated_size;
1749   typename TypeHandler::Type* result =
1750       TypeHandler::NewFromPrototype(prototype, arena_);
1751   rep_->elements[current_size_++] = result;
1752   return result;
1753 }
1754 
1755 template <typename TypeHandler,
1756           typename std::enable_if<TypeHandler::Movable::value>::type*>
1757 inline void RepeatedPtrFieldBase::Add(typename TypeHandler::Type&& value) {
1758   if (rep_ != NULL && current_size_ < rep_->allocated_size) {
1759     *cast<TypeHandler>(rep_->elements[current_size_++]) = std::move(value);
1760     return;
1761   }
1762   if (!rep_ || rep_->allocated_size == total_size_) {
1763     Reserve(total_size_ + 1);
1764   }
1765   ++rep_->allocated_size;
1766   typename TypeHandler::Type* result =
1767       TypeHandler::New(arena_, std::move(value));
1768   rep_->elements[current_size_++] = result;
1769 }
1770 
1771 template <typename TypeHandler>
1772 inline void RepeatedPtrFieldBase::RemoveLast() {
1773   GOOGLE_DCHECK_GT(current_size_, 0);
1774   TypeHandler::Clear(cast<TypeHandler>(rep_->elements[--current_size_]));
1775 }
1776 
1777 template <typename TypeHandler>
1778 void RepeatedPtrFieldBase::Clear() {
1779   const int n = current_size_;
1780   GOOGLE_DCHECK_GE(n, 0);
1781   if (n > 0) {
1782     void* const* elements = rep_->elements;
1783     int i = 0;
1784     do {
1785       TypeHandler::Clear(cast<TypeHandler>(elements[i++]));
1786     } while (i < n);
1787     current_size_ = 0;
1788   }
1789 }
1790 
1791 // To avoid unnecessary code duplication and reduce binary size, we use a
1792 // layered approach to implementing MergeFrom(). The toplevel method is
1793 // templated, so we get a small thunk per concrete message type in the binary.
1794 // This calls a shared implementation with most of the logic, passing a function
1795 // pointer to another type-specific piece of code that calls the object-allocate
1796 // and merge handlers.
1797 template <typename TypeHandler>
1798 inline void RepeatedPtrFieldBase::MergeFrom(const RepeatedPtrFieldBase& other) {
1799   GOOGLE_DCHECK_NE(&other, this);
1800   if (other.current_size_ == 0) return;
1801   MergeFromInternal(other,
1802                     &RepeatedPtrFieldBase::MergeFromInnerLoop<TypeHandler>);
1803 }
1804 
1805 inline void RepeatedPtrFieldBase::MergeFromInternal(
1806     const RepeatedPtrFieldBase& other,
1807     void (RepeatedPtrFieldBase::*inner_loop)(void**, void**, int, int)) {
1808   // Note: wrapper has already guaranteed that other.rep_ != NULL here.
1809   int other_size = other.current_size_;
1810   void** other_elements = other.rep_->elements;
1811   void** new_elements = InternalExtend(other_size);
1812   int allocated_elems = rep_->allocated_size - current_size_;
1813   (this->*inner_loop)(new_elements, other_elements, other_size,
1814                       allocated_elems);
1815   current_size_ += other_size;
1816   if (rep_->allocated_size < current_size_) {
1817     rep_->allocated_size = current_size_;
1818   }
1819 }
1820 
1821 // Merges other_elems to our_elems.
1822 template <typename TypeHandler>
1823 void RepeatedPtrFieldBase::MergeFromInnerLoop(void** our_elems,
1824                                               void** other_elems, int length,
1825                                               int already_allocated) {
1826   // Split into two loops, over ranges [0, allocated) and [allocated, length),
1827   // to avoid a branch within the loop.
1828   for (int i = 0; i < already_allocated && i < length; i++) {
1829     // Already allocated: use existing element.
1830     typename TypeHandler::Type* other_elem =
1831         reinterpret_cast<typename TypeHandler::Type*>(other_elems[i]);
1832     typename TypeHandler::Type* new_elem =
1833         reinterpret_cast<typename TypeHandler::Type*>(our_elems[i]);
1834     TypeHandler::Merge(*other_elem, new_elem);
1835   }
1836   Arena* arena = GetArena();
1837   for (int i = already_allocated; i < length; i++) {
1838     // Not allocated: alloc a new element first, then merge it.
1839     typename TypeHandler::Type* other_elem =
1840         reinterpret_cast<typename TypeHandler::Type*>(other_elems[i]);
1841     typename TypeHandler::Type* new_elem =
1842         TypeHandler::NewFromPrototype(other_elem, arena);
1843     TypeHandler::Merge(*other_elem, new_elem);
1844     our_elems[i] = new_elem;
1845   }
1846 }
1847 
1848 template <typename TypeHandler>
1849 inline void RepeatedPtrFieldBase::CopyFrom(const RepeatedPtrFieldBase& other) {
1850   if (&other == this) return;
1851   RepeatedPtrFieldBase::Clear<TypeHandler>();
1852   RepeatedPtrFieldBase::MergeFrom<TypeHandler>(other);
1853 }
1854 
1855 inline int RepeatedPtrFieldBase::Capacity() const { return total_size_; }
1856 
1857 inline void* const* RepeatedPtrFieldBase::raw_data() const {
1858   return rep_ ? rep_->elements : NULL;
1859 }
1860 
1861 inline void** RepeatedPtrFieldBase::raw_mutable_data() const {
1862   return rep_ ? const_cast<void**>(rep_->elements) : NULL;
1863 }
1864 
1865 template <typename TypeHandler>
1866 inline typename TypeHandler::Type** RepeatedPtrFieldBase::mutable_data() {
1867   // TODO(kenton):  Breaks C++ aliasing rules.  We should probably remove this
1868   //   method entirely.
1869   return reinterpret_cast<typename TypeHandler::Type**>(raw_mutable_data());
1870 }
1871 
1872 template <typename TypeHandler>
1873 inline const typename TypeHandler::Type* const* RepeatedPtrFieldBase::data()
1874     const {
1875   // TODO(kenton):  Breaks C++ aliasing rules.  We should probably remove this
1876   //   method entirely.
1877   return reinterpret_cast<const typename TypeHandler::Type* const*>(raw_data());
1878 }
1879 
1880 inline void RepeatedPtrFieldBase::SwapElements(int index1, int index2) {
1881   using std::swap;  // enable ADL with fallback
1882   swap(rep_->elements[index1], rep_->elements[index2]);
1883 }
1884 
1885 template <typename TypeHandler>
1886 inline size_t RepeatedPtrFieldBase::SpaceUsedExcludingSelfLong() const {
1887   size_t allocated_bytes = static_cast<size_t>(total_size_) * sizeof(void*);
1888   if (rep_ != NULL) {
1889     for (int i = 0; i < rep_->allocated_size; ++i) {
1890       allocated_bytes +=
1891           TypeHandler::SpaceUsedLong(*cast<TypeHandler>(rep_->elements[i]));
1892     }
1893     allocated_bytes += kRepHeaderSize;
1894   }
1895   return allocated_bytes;
1896 }
1897 
1898 template <typename TypeHandler>
1899 inline typename TypeHandler::Type* RepeatedPtrFieldBase::AddFromCleared() {
1900   if (rep_ != NULL && current_size_ < rep_->allocated_size) {
1901     return cast<TypeHandler>(rep_->elements[current_size_++]);
1902   } else {
1903     return NULL;
1904   }
1905 }
1906 
1907 // AddAllocated version that implements arena-safe copying behavior.
1908 template <typename TypeHandler>
1909 void RepeatedPtrFieldBase::AddAllocatedInternal(
1910     typename TypeHandler::Type* value, std::true_type) {
1911   Arena* element_arena =
1912       reinterpret_cast<Arena*>(TypeHandler::GetMaybeArenaPointer(value));
1913   Arena* arena = GetArena();
1914   if (arena == element_arena && rep_ && rep_->allocated_size < total_size_) {
1915     // Fast path: underlying arena representation (tagged pointer) is equal to
1916     // our arena pointer, and we can add to array without resizing it (at least
1917     // one slot that is not allocated).
1918     void** elems = rep_->elements;
1919     if (current_size_ < rep_->allocated_size) {
1920       // Make space at [current] by moving first allocated element to end of
1921       // allocated list.
1922       elems[rep_->allocated_size] = elems[current_size_];
1923     }
1924     elems[current_size_] = value;
1925     current_size_ = current_size_ + 1;
1926     rep_->allocated_size = rep_->allocated_size + 1;
1927   } else {
1928     AddAllocatedSlowWithCopy<TypeHandler>(value, TypeHandler::GetArena(value),
1929                                           arena);
1930   }
1931 }
1932 
1933 // Slowpath handles all cases, copying if necessary.
1934 template <typename TypeHandler>
1935 void RepeatedPtrFieldBase::AddAllocatedSlowWithCopy(
1936     // Pass value_arena and my_arena to avoid duplicate virtual call (value) or
1937     // load (mine).
1938     typename TypeHandler::Type* value, Arena* value_arena, Arena* my_arena) {
1939   // Ensure that either the value is in the same arena, or if not, we do the
1940   // appropriate thing: Own() it (if it's on heap and we're in an arena) or copy
1941   // it to our arena/heap (otherwise).
1942   if (my_arena != NULL && value_arena == NULL) {
1943     my_arena->Own(value);
1944   } else if (my_arena != value_arena) {
1945     typename TypeHandler::Type* new_value =
1946         TypeHandler::NewFromPrototype(value, my_arena);
1947     TypeHandler::Merge(*value, new_value);
1948     TypeHandler::Delete(value, value_arena);
1949     value = new_value;
1950   }
1951 
1952   UnsafeArenaAddAllocated<TypeHandler>(value);
1953 }
1954 
1955 // AddAllocated version that does not implement arena-safe copying behavior.
1956 template <typename TypeHandler>
1957 void RepeatedPtrFieldBase::AddAllocatedInternal(
1958     typename TypeHandler::Type* value, std::false_type) {
1959   if (rep_ && rep_->allocated_size < total_size_) {
1960     // Fast path: underlying arena representation (tagged pointer) is equal to
1961     // our arena pointer, and we can add to array without resizing it (at least
1962     // one slot that is not allocated).
1963     void** elems = rep_->elements;
1964     if (current_size_ < rep_->allocated_size) {
1965       // Make space at [current] by moving first allocated element to end of
1966       // allocated list.
1967       elems[rep_->allocated_size] = elems[current_size_];
1968     }
1969     elems[current_size_] = value;
1970     current_size_ = current_size_ + 1;
1971     ++rep_->allocated_size;
1972   } else {
1973     UnsafeArenaAddAllocated<TypeHandler>(value);
1974   }
1975 }
1976 
1977 template <typename TypeHandler>
1978 void RepeatedPtrFieldBase::UnsafeArenaAddAllocated(
1979     typename TypeHandler::Type* value) {
1980   // Make room for the new pointer.
1981   if (!rep_ || current_size_ == total_size_) {
1982     // The array is completely full with no cleared objects, so grow it.
1983     Reserve(total_size_ + 1);
1984     ++rep_->allocated_size;
1985   } else if (rep_->allocated_size == total_size_) {
1986     // There is no more space in the pointer array because it contains some
1987     // cleared objects awaiting reuse.  We don't want to grow the array in this
1988     // case because otherwise a loop calling AddAllocated() followed by Clear()
1989     // would leak memory.
1990     TypeHandler::Delete(cast<TypeHandler>(rep_->elements[current_size_]),
1991                         arena_);
1992   } else if (current_size_ < rep_->allocated_size) {
1993     // We have some cleared objects.  We don't care about their order, so we
1994     // can just move the first one to the end to make space.
1995     rep_->elements[rep_->allocated_size] = rep_->elements[current_size_];
1996     ++rep_->allocated_size;
1997   } else {
1998     // There are no cleared objects.
1999     ++rep_->allocated_size;
2000   }
2001 
2002   rep_->elements[current_size_++] = value;
2003 }
2004 
2005 // ReleaseLast() for types that implement merge/copy behavior.
2006 template <typename TypeHandler>
2007 inline typename TypeHandler::Type* RepeatedPtrFieldBase::ReleaseLastInternal(
2008     std::true_type) {
2009   // First, release an element.
2010   typename TypeHandler::Type* result = UnsafeArenaReleaseLast<TypeHandler>();
2011   // Now perform a copy if we're on an arena.
2012   Arena* arena = GetArena();
2013   if (arena == NULL) {
2014     return result;
2015   } else {
2016     typename TypeHandler::Type* new_result =
2017         TypeHandler::NewFromPrototype(result, NULL);
2018     TypeHandler::Merge(*result, new_result);
2019     return new_result;
2020   }
2021 }
2022 
2023 // ReleaseLast() for types that *do not* implement merge/copy behavior -- this
2024 // is the same as UnsafeArenaReleaseLast(). Note that we GOOGLE_DCHECK-fail if we're on
2025 // an arena, since the user really should implement the copy operation in this
2026 // case.
2027 template <typename TypeHandler>
2028 inline typename TypeHandler::Type* RepeatedPtrFieldBase::ReleaseLastInternal(
2029     std::false_type) {
2030   GOOGLE_DCHECK(GetArena() == NULL)
2031       << "ReleaseLast() called on a RepeatedPtrField that is on an arena, "
2032       << "with a type that does not implement MergeFrom. This is unsafe; "
2033       << "please implement MergeFrom for your type.";
2034   return UnsafeArenaReleaseLast<TypeHandler>();
2035 }
2036 
2037 template <typename TypeHandler>
2038 inline typename TypeHandler::Type*
2039 RepeatedPtrFieldBase::UnsafeArenaReleaseLast() {
2040   GOOGLE_DCHECK_GT(current_size_, 0);
2041   typename TypeHandler::Type* result =
2042       cast<TypeHandler>(rep_->elements[--current_size_]);
2043   --rep_->allocated_size;
2044   if (current_size_ < rep_->allocated_size) {
2045     // There are cleared elements on the end; replace the removed element
2046     // with the last allocated element.
2047     rep_->elements[current_size_] = rep_->elements[rep_->allocated_size];
2048   }
2049   return result;
2050 }
2051 
2052 inline int RepeatedPtrFieldBase::ClearedCount() const {
2053   return rep_ ? (rep_->allocated_size - current_size_) : 0;
2054 }
2055 
2056 template <typename TypeHandler>
2057 inline void RepeatedPtrFieldBase::AddCleared(
2058     typename TypeHandler::Type* value) {
2059   GOOGLE_DCHECK(GetArena() == NULL)
2060       << "AddCleared() can only be used on a RepeatedPtrField not on an arena.";
2061   GOOGLE_DCHECK(TypeHandler::GetArena(value) == NULL)
2062       << "AddCleared() can only accept values not on an arena.";
2063   if (!rep_ || rep_->allocated_size == total_size_) {
2064     Reserve(total_size_ + 1);
2065   }
2066   rep_->elements[rep_->allocated_size++] = value;
2067 }
2068 
2069 template <typename TypeHandler>
2070 inline typename TypeHandler::Type* RepeatedPtrFieldBase::ReleaseCleared() {
2071   GOOGLE_DCHECK(GetArena() == NULL)
2072       << "ReleaseCleared() can only be used on a RepeatedPtrField not on "
2073       << "an arena.";
2074   GOOGLE_DCHECK(GetArena() == NULL);
2075   GOOGLE_DCHECK(rep_ != NULL);
2076   GOOGLE_DCHECK_GT(rep_->allocated_size, current_size_);
2077   return cast<TypeHandler>(rep_->elements[--rep_->allocated_size]);
2078 }
2079 
2080 }  // namespace internal
2081 
2082 // -------------------------------------------------------------------
2083 
2084 template <typename Element>
2085 class RepeatedPtrField<Element>::TypeHandler
2086     : public internal::GenericTypeHandler<Element> {};
2087 
2088 template <>
2089 class RepeatedPtrField<std::string>::TypeHandler
2090     : public internal::StringTypeHandler {};
2091 
2092 template <typename Element>
2093 constexpr RepeatedPtrField<Element>::RepeatedPtrField()
2094     : RepeatedPtrFieldBase() {}
2095 
2096 template <typename Element>
2097 inline RepeatedPtrField<Element>::RepeatedPtrField(Arena* arena)
2098     : RepeatedPtrFieldBase(arena) {}
2099 
2100 template <typename Element>
2101 inline RepeatedPtrField<Element>::RepeatedPtrField(
2102     const RepeatedPtrField& other)
2103     : RepeatedPtrFieldBase() {
2104   MergeFrom(other);
2105 }
2106 
2107 template <typename Element>
2108 template <typename Iter>
2109 inline RepeatedPtrField<Element>::RepeatedPtrField(Iter begin,
2110                                                    const Iter& end) {
2111   int reserve = internal::CalculateReserve(begin, end);
2112   if (reserve != -1) {
2113     Reserve(reserve);
2114   }
2115   for (; begin != end; ++begin) {
2116     *Add() = *begin;
2117   }
2118 }
2119 
2120 template <typename Element>
2121 RepeatedPtrField<Element>::~RepeatedPtrField() {
2122   Destroy<TypeHandler>();
2123 }
2124 
2125 template <typename Element>
2126 inline RepeatedPtrField<Element>& RepeatedPtrField<Element>::operator=(
2127     const RepeatedPtrField& other) {
2128   if (this != &other) CopyFrom(other);
2129   return *this;
2130 }
2131 
2132 template <typename Element>
2133 inline RepeatedPtrField<Element>::RepeatedPtrField(
2134     RepeatedPtrField&& other) noexcept
2135     : RepeatedPtrField() {
2136   // We don't just call Swap(&other) here because it would perform 3 copies if
2137   // other is on an arena. This field can't be on an arena because arena
2138   // construction always uses the Arena* accepting constructor.
2139   if (other.GetArena()) {
2140     CopyFrom(other);
2141   } else {
2142     InternalSwap(&other);
2143   }
2144 }
2145 
2146 template <typename Element>
2147 inline RepeatedPtrField<Element>& RepeatedPtrField<Element>::operator=(
2148     RepeatedPtrField&& other) noexcept {
2149   // We don't just call Swap(&other) here because it would perform 3 copies if
2150   // the two fields are on different arenas.
2151   if (this != &other) {
2152     if (this->GetArena() != other.GetArena()) {
2153       CopyFrom(other);
2154     } else {
2155       InternalSwap(&other);
2156     }
2157   }
2158   return *this;
2159 }
2160 
2161 template <typename Element>
2162 inline bool RepeatedPtrField<Element>::empty() const {
2163   return RepeatedPtrFieldBase::empty();
2164 }
2165 
2166 template <typename Element>
2167 inline int RepeatedPtrField<Element>::size() const {
2168   return RepeatedPtrFieldBase::size();
2169 }
2170 
2171 template <typename Element>
2172 inline const Element& RepeatedPtrField<Element>::Get(int index) const {
2173   return RepeatedPtrFieldBase::Get<TypeHandler>(index);
2174 }
2175 
2176 template <typename Element>
2177 inline const Element& RepeatedPtrField<Element>::at(int index) const {
2178   return RepeatedPtrFieldBase::at<TypeHandler>(index);
2179 }
2180 
2181 template <typename Element>
2182 inline Element& RepeatedPtrField<Element>::at(int index) {
2183   return RepeatedPtrFieldBase::at<TypeHandler>(index);
2184 }
2185 
2186 
2187 template <typename Element>
2188 inline Element* RepeatedPtrField<Element>::Mutable(int index) {
2189   return RepeatedPtrFieldBase::Mutable<TypeHandler>(index);
2190 }
2191 
2192 template <typename Element>
2193 inline Element* RepeatedPtrField<Element>::Add() {
2194   return RepeatedPtrFieldBase::Add<TypeHandler>();
2195 }
2196 
2197 template <typename Element>
2198 inline void RepeatedPtrField<Element>::Add(Element&& value) {
2199   RepeatedPtrFieldBase::Add<TypeHandler>(std::move(value));
2200 }
2201 
2202 template <typename Element>
2203 inline void RepeatedPtrField<Element>::RemoveLast() {
2204   RepeatedPtrFieldBase::RemoveLast<TypeHandler>();
2205 }
2206 
2207 template <typename Element>
2208 inline void RepeatedPtrField<Element>::DeleteSubrange(int start, int num) {
2209   GOOGLE_DCHECK_GE(start, 0);
2210   GOOGLE_DCHECK_GE(num, 0);
2211   GOOGLE_DCHECK_LE(start + num, size());
2212   for (int i = 0; i < num; ++i) {
2213     RepeatedPtrFieldBase::Delete<TypeHandler>(start + i);
2214   }
2215   ExtractSubrange(start, num, NULL);
2216 }
2217 
2218 template <typename Element>
2219 inline void RepeatedPtrField<Element>::ExtractSubrange(int start, int num,
2220                                                        Element** elements) {
2221   typename internal::TypeImplementsMergeBehavior<
2222       typename TypeHandler::Type>::type t;
2223   ExtractSubrangeInternal(start, num, elements, t);
2224 }
2225 
2226 // ExtractSubrange() implementation for types that implement merge/copy
2227 // behavior.
2228 template <typename Element>
2229 inline void RepeatedPtrField<Element>::ExtractSubrangeInternal(
2230     int start, int num, Element** elements, std::true_type) {
2231   GOOGLE_DCHECK_GE(start, 0);
2232   GOOGLE_DCHECK_GE(num, 0);
2233   GOOGLE_DCHECK_LE(start + num, size());
2234 
2235   if (num > 0) {
2236     // Save the values of the removed elements if requested.
2237     if (elements != NULL) {
2238       if (GetArena() != NULL) {
2239         // If we're on an arena, we perform a copy for each element so that the
2240         // returned elements are heap-allocated.
2241         for (int i = 0; i < num; ++i) {
2242           Element* element =
2243               RepeatedPtrFieldBase::Mutable<TypeHandler>(i + start);
2244           typename TypeHandler::Type* new_value =
2245               TypeHandler::NewFromPrototype(element, NULL);
2246           TypeHandler::Merge(*element, new_value);
2247           elements[i] = new_value;
2248         }
2249       } else {
2250         for (int i = 0; i < num; ++i) {
2251           elements[i] = RepeatedPtrFieldBase::Mutable<TypeHandler>(i + start);
2252         }
2253       }
2254     }
2255     CloseGap(start, num);
2256   }
2257 }
2258 
2259 // ExtractSubrange() implementation for types that do not implement merge/copy
2260 // behavior.
2261 template <typename Element>
2262 inline void RepeatedPtrField<Element>::ExtractSubrangeInternal(
2263     int start, int num, Element** elements, std::false_type) {
2264   // This case is identical to UnsafeArenaExtractSubrange(). However, since
2265   // ExtractSubrange() must return heap-allocated objects by contract, and we
2266   // cannot fulfill this contract if we are an on arena, we must GOOGLE_DCHECK() that
2267   // we are not on an arena.
2268   GOOGLE_DCHECK(GetArena() == NULL)
2269       << "ExtractSubrange() when arena is non-NULL is only supported when "
2270       << "the Element type supplies a MergeFrom() operation to make copies.";
2271   UnsafeArenaExtractSubrange(start, num, elements);
2272 }
2273 
2274 template <typename Element>
2275 inline void RepeatedPtrField<Element>::UnsafeArenaExtractSubrange(
2276     int start, int num, Element** elements) {
2277   GOOGLE_DCHECK_GE(start, 0);
2278   GOOGLE_DCHECK_GE(num, 0);
2279   GOOGLE_DCHECK_LE(start + num, size());
2280 
2281   if (num > 0) {
2282     // Save the values of the removed elements if requested.
2283     if (elements != NULL) {
2284       for (int i = 0; i < num; ++i) {
2285         elements[i] = RepeatedPtrFieldBase::Mutable<TypeHandler>(i + start);
2286       }
2287     }
2288     CloseGap(start, num);
2289   }
2290 }
2291 
2292 template <typename Element>
2293 inline void RepeatedPtrField<Element>::Clear() {
2294   RepeatedPtrFieldBase::Clear<TypeHandler>();
2295 }
2296 
2297 template <typename Element>
2298 inline void RepeatedPtrField<Element>::MergeFrom(
2299     const RepeatedPtrField& other) {
2300   RepeatedPtrFieldBase::MergeFrom<TypeHandler>(other);
2301 }
2302 
2303 template <typename Element>
2304 inline void RepeatedPtrField<Element>::CopyFrom(const RepeatedPtrField& other) {
2305   RepeatedPtrFieldBase::CopyFrom<TypeHandler>(other);
2306 }
2307 
2308 template <typename Element>
2309 inline typename RepeatedPtrField<Element>::iterator
2310 RepeatedPtrField<Element>::erase(const_iterator position) {
2311   return erase(position, position + 1);
2312 }
2313 
2314 template <typename Element>
2315 inline typename RepeatedPtrField<Element>::iterator
2316 RepeatedPtrField<Element>::erase(const_iterator first, const_iterator last) {
2317   size_type pos_offset = std::distance(cbegin(), first);
2318   size_type last_offset = std::distance(cbegin(), last);
2319   DeleteSubrange(pos_offset, last_offset - pos_offset);
2320   return begin() + pos_offset;
2321 }
2322 
2323 template <typename Element>
2324 inline Element** RepeatedPtrField<Element>::mutable_data() {
2325   return RepeatedPtrFieldBase::mutable_data<TypeHandler>();
2326 }
2327 
2328 template <typename Element>
2329 inline const Element* const* RepeatedPtrField<Element>::data() const {
2330   return RepeatedPtrFieldBase::data<TypeHandler>();
2331 }
2332 
2333 template <typename Element>
2334 inline void RepeatedPtrField<Element>::Swap(RepeatedPtrField* other) {
2335   if (this == other) return;
2336   RepeatedPtrFieldBase::Swap<TypeHandler>(other);
2337 }
2338 
2339 template <typename Element>
2340 inline void RepeatedPtrField<Element>::UnsafeArenaSwap(
2341     RepeatedPtrField* other) {
2342   if (this == other) return;
2343   RepeatedPtrFieldBase::InternalSwap(other);
2344 }
2345 
2346 template <typename Element>
2347 inline void RepeatedPtrField<Element>::SwapElements(int index1, int index2) {
2348   RepeatedPtrFieldBase::SwapElements(index1, index2);
2349 }
2350 
2351 template <typename Element>
2352 inline Arena* RepeatedPtrField<Element>::GetArena() const {
2353   return RepeatedPtrFieldBase::GetArena();
2354 }
2355 
2356 template <typename Element>
2357 inline size_t RepeatedPtrField<Element>::SpaceUsedExcludingSelfLong() const {
2358   return RepeatedPtrFieldBase::SpaceUsedExcludingSelfLong<TypeHandler>();
2359 }
2360 
2361 template <typename Element>
2362 inline void RepeatedPtrField<Element>::AddAllocated(Element* value) {
2363   RepeatedPtrFieldBase::AddAllocated<TypeHandler>(value);
2364 }
2365 
2366 template <typename Element>
2367 inline void RepeatedPtrField<Element>::UnsafeArenaAddAllocated(Element* value) {
2368   RepeatedPtrFieldBase::UnsafeArenaAddAllocated<TypeHandler>(value);
2369 }
2370 
2371 template <typename Element>
2372 inline Element* RepeatedPtrField<Element>::ReleaseLast() {
2373   return RepeatedPtrFieldBase::ReleaseLast<TypeHandler>();
2374 }
2375 
2376 template <typename Element>
2377 inline Element* RepeatedPtrField<Element>::UnsafeArenaReleaseLast() {
2378   return RepeatedPtrFieldBase::UnsafeArenaReleaseLast<TypeHandler>();
2379 }
2380 
2381 template <typename Element>
2382 inline int RepeatedPtrField<Element>::ClearedCount() const {
2383   return RepeatedPtrFieldBase::ClearedCount();
2384 }
2385 
2386 template <typename Element>
2387 inline void RepeatedPtrField<Element>::AddCleared(Element* value) {
2388   return RepeatedPtrFieldBase::AddCleared<TypeHandler>(value);
2389 }
2390 
2391 template <typename Element>
2392 inline Element* RepeatedPtrField<Element>::ReleaseCleared() {
2393   return RepeatedPtrFieldBase::ReleaseCleared<TypeHandler>();
2394 }
2395 
2396 template <typename Element>
2397 inline void RepeatedPtrField<Element>::Reserve(int new_size) {
2398   return RepeatedPtrFieldBase::Reserve(new_size);
2399 }
2400 
2401 template <typename Element>
2402 inline int RepeatedPtrField<Element>::Capacity() const {
2403   return RepeatedPtrFieldBase::Capacity();
2404 }
2405 
2406 // -------------------------------------------------------------------
2407 
2408 namespace internal {
2409 
2410 // STL-like iterator implementation for RepeatedPtrField.  You should not
2411 // refer to this class directly; use RepeatedPtrField<T>::iterator instead.
2412 //
2413 // The iterator for RepeatedPtrField<T>, RepeatedPtrIterator<T>, is
2414 // very similar to iterator_ptr<T**> in util/gtl/iterator_adaptors.h,
2415 // but adds random-access operators and is modified to wrap a void** base
2416 // iterator (since RepeatedPtrField stores its array as a void* array and
2417 // casting void** to T** would violate C++ aliasing rules).
2418 //
2419 // This code based on net/proto/proto-array-internal.h by Jeffrey Yasskin
2420 // (jyasskin@google.com).
2421 template <typename Element>
2422 class RepeatedPtrIterator {
2423  public:
2424   using iterator = RepeatedPtrIterator<Element>;
2425   using iterator_category = std::random_access_iterator_tag;
2426   using value_type = typename std::remove_const<Element>::type;
2427   using difference_type = std::ptrdiff_t;
2428   using pointer = Element*;
2429   using reference = Element&;
2430 
2431   RepeatedPtrIterator() : it_(NULL) {}
2432   explicit RepeatedPtrIterator(void* const* it) : it_(it) {}
2433 
2434   // Allow "upcasting" from RepeatedPtrIterator<T**> to
2435   // RepeatedPtrIterator<const T*const*>.
2436   template <typename OtherElement>
2437   RepeatedPtrIterator(const RepeatedPtrIterator<OtherElement>& other)
2438       : it_(other.it_) {
2439     // Force a compiler error if the other type is not convertible to ours.
2440     if (false) {
2441       implicit_cast<Element*>(static_cast<OtherElement*>(nullptr));
2442     }
2443   }
2444 
2445   // dereferenceable
2446   reference operator*() const { return *reinterpret_cast<Element*>(*it_); }
2447   pointer operator->() const { return &(operator*()); }
2448 
2449   // {inc,dec}rementable
2450   iterator& operator++() {
2451     ++it_;
2452     return *this;
2453   }
2454   iterator operator++(int) { return iterator(it_++); }
2455   iterator& operator--() {
2456     --it_;
2457     return *this;
2458   }
2459   iterator operator--(int) { return iterator(it_--); }
2460 
2461   // equality_comparable
2462   bool operator==(const iterator& x) const { return it_ == x.it_; }
2463   bool operator!=(const iterator& x) const { return it_ != x.it_; }
2464 
2465   // less_than_comparable
2466   bool operator<(const iterator& x) const { return it_ < x.it_; }
2467   bool operator<=(const iterator& x) const { return it_ <= x.it_; }
2468   bool operator>(const iterator& x) const { return it_ > x.it_; }
2469   bool operator>=(const iterator& x) const { return it_ >= x.it_; }
2470 
2471   // addable, subtractable
2472   iterator& operator+=(difference_type d) {
2473     it_ += d;
2474     return *this;
2475   }
2476   friend iterator operator+(iterator it, const difference_type d) {
2477     it += d;
2478     return it;
2479   }
2480   friend iterator operator+(const difference_type d, iterator it) {
2481     it += d;
2482     return it;
2483   }
2484   iterator& operator-=(difference_type d) {
2485     it_ -= d;
2486     return *this;
2487   }
2488   friend iterator operator-(iterator it, difference_type d) {
2489     it -= d;
2490     return it;
2491   }
2492 
2493   // indexable
2494   reference operator[](difference_type d) const { return *(*this + d); }
2495 
2496   // random access iterator
2497   difference_type operator-(const iterator& x) const { return it_ - x.it_; }
2498 
2499  private:
2500   template <typename OtherElement>
2501   friend class RepeatedPtrIterator;
2502 
2503   // The internal iterator.
2504   void* const* it_;
2505 };
2506 
2507 // Provide an iterator that operates on pointers to the underlying objects
2508 // rather than the objects themselves as RepeatedPtrIterator does.
2509 // Consider using this when working with stl algorithms that change
2510 // the array.
2511 // The VoidPtr template parameter holds the type-agnostic pointer value
2512 // referenced by the iterator.  It should either be "void *" for a mutable
2513 // iterator, or "const void* const" for a constant iterator.
2514 template <typename Element, typename VoidPtr>
2515 class RepeatedPtrOverPtrsIterator {
2516  public:
2517   using iterator = RepeatedPtrOverPtrsIterator<Element, VoidPtr>;
2518   using iterator_category = std::random_access_iterator_tag;
2519   using value_type = typename std::remove_const<Element>::type;
2520   using difference_type = std::ptrdiff_t;
2521   using pointer = Element*;
2522   using reference = Element&;
2523 
2524   RepeatedPtrOverPtrsIterator() : it_(NULL) {}
2525   explicit RepeatedPtrOverPtrsIterator(VoidPtr* it) : it_(it) {}
2526 
2527   // dereferenceable
2528   reference operator*() const { return *reinterpret_cast<Element*>(it_); }
2529   pointer operator->() const { return &(operator*()); }
2530 
2531   // {inc,dec}rementable
2532   iterator& operator++() {
2533     ++it_;
2534     return *this;
2535   }
2536   iterator operator++(int) { return iterator(it_++); }
2537   iterator& operator--() {
2538     --it_;
2539     return *this;
2540   }
2541   iterator operator--(int) { return iterator(it_--); }
2542 
2543   // equality_comparable
2544   bool operator==(const iterator& x) const { return it_ == x.it_; }
2545   bool operator!=(const iterator& x) const { return it_ != x.it_; }
2546 
2547   // less_than_comparable
2548   bool operator<(const iterator& x) const { return it_ < x.it_; }
2549   bool operator<=(const iterator& x) const { return it_ <= x.it_; }
2550   bool operator>(const iterator& x) const { return it_ > x.it_; }
2551   bool operator>=(const iterator& x) const { return it_ >= x.it_; }
2552 
2553   // addable, subtractable
2554   iterator& operator+=(difference_type d) {
2555     it_ += d;
2556     return *this;
2557   }
2558   friend iterator operator+(iterator it, difference_type d) {
2559     it += d;
2560     return it;
2561   }
2562   friend iterator operator+(difference_type d, iterator it) {
2563     it += d;
2564     return it;
2565   }
2566   iterator& operator-=(difference_type d) {
2567     it_ -= d;
2568     return *this;
2569   }
2570   friend iterator operator-(iterator it, difference_type d) {
2571     it -= d;
2572     return it;
2573   }
2574 
2575   // indexable
2576   reference operator[](difference_type d) const { return *(*this + d); }
2577 
2578   // random access iterator
2579   difference_type operator-(const iterator& x) const { return it_ - x.it_; }
2580 
2581  private:
2582   template <typename OtherElement>
2583   friend class RepeatedPtrIterator;
2584 
2585   // The internal iterator.
2586   VoidPtr* it_;
2587 };
2588 
2589 void RepeatedPtrFieldBase::InternalSwap(RepeatedPtrFieldBase* other) {
2590   GOOGLE_DCHECK(this != other);
2591   GOOGLE_DCHECK(GetArena() == other->GetArena());
2592 
2593   // Swap all fields at once.
2594   static_assert(std::is_standard_layout<RepeatedPtrFieldBase>::value,
2595                 "offsetof() requires standard layout before c++17");
2596   internal::memswap<offsetof(RepeatedPtrFieldBase, rep_) + sizeof(this->rep_) -
2597                     offsetof(RepeatedPtrFieldBase, current_size_)>(
2598       reinterpret_cast<char*>(this) +
2599           offsetof(RepeatedPtrFieldBase, current_size_),
2600       reinterpret_cast<char*>(other) +
2601           offsetof(RepeatedPtrFieldBase, current_size_));
2602 }
2603 
2604 }  // namespace internal
2605 
2606 template <typename Element>
2607 inline typename RepeatedPtrField<Element>::iterator
2608 RepeatedPtrField<Element>::begin() {
2609   return iterator(raw_data());
2610 }
2611 template <typename Element>
2612 inline typename RepeatedPtrField<Element>::const_iterator
2613 RepeatedPtrField<Element>::begin() const {
2614   return iterator(raw_data());
2615 }
2616 template <typename Element>
2617 inline typename RepeatedPtrField<Element>::const_iterator
2618 RepeatedPtrField<Element>::cbegin() const {
2619   return begin();
2620 }
2621 template <typename Element>
2622 inline typename RepeatedPtrField<Element>::iterator
2623 RepeatedPtrField<Element>::end() {
2624   return iterator(raw_data() + size());
2625 }
2626 template <typename Element>
2627 inline typename RepeatedPtrField<Element>::const_iterator
2628 RepeatedPtrField<Element>::end() const {
2629   return iterator(raw_data() + size());
2630 }
2631 template <typename Element>
2632 inline typename RepeatedPtrField<Element>::const_iterator
2633 RepeatedPtrField<Element>::cend() const {
2634   return end();
2635 }
2636 
2637 template <typename Element>
2638 inline typename RepeatedPtrField<Element>::pointer_iterator
2639 RepeatedPtrField<Element>::pointer_begin() {
2640   return pointer_iterator(raw_mutable_data());
2641 }
2642 template <typename Element>
2643 inline typename RepeatedPtrField<Element>::const_pointer_iterator
2644 RepeatedPtrField<Element>::pointer_begin() const {
2645   return const_pointer_iterator(const_cast<const void* const*>(raw_data()));
2646 }
2647 template <typename Element>
2648 inline typename RepeatedPtrField<Element>::pointer_iterator
2649 RepeatedPtrField<Element>::pointer_end() {
2650   return pointer_iterator(raw_mutable_data() + size());
2651 }
2652 template <typename Element>
2653 inline typename RepeatedPtrField<Element>::const_pointer_iterator
2654 RepeatedPtrField<Element>::pointer_end() const {
2655   return const_pointer_iterator(
2656       const_cast<const void* const*>(raw_data() + size()));
2657 }
2658 
2659 // Iterators and helper functions that follow the spirit of the STL
2660 // std::back_insert_iterator and std::back_inserter but are tailor-made
2661 // for RepeatedField and RepeatedPtrField. Typical usage would be:
2662 //
2663 //   std::copy(some_sequence.begin(), some_sequence.end(),
2664 //             RepeatedFieldBackInserter(proto.mutable_sequence()));
2665 //
2666 // Ported by johannes from util/gtl/proto-array-iterators.h
2667 
2668 namespace internal {
2669 // A back inserter for RepeatedField objects.
2670 template <typename T>
2671 class RepeatedFieldBackInsertIterator
2672     : public std::iterator<std::output_iterator_tag, T> {
2673  public:
2674   explicit RepeatedFieldBackInsertIterator(
2675       RepeatedField<T>* const mutable_field)
2676       : field_(mutable_field) {}
2677   RepeatedFieldBackInsertIterator<T>& operator=(const T& value) {
2678     field_->Add(value);
2679     return *this;
2680   }
2681   RepeatedFieldBackInsertIterator<T>& operator*() { return *this; }
2682   RepeatedFieldBackInsertIterator<T>& operator++() { return *this; }
2683   RepeatedFieldBackInsertIterator<T>& operator++(int /* unused */) {
2684     return *this;
2685   }
2686 
2687  private:
2688   RepeatedField<T>* field_;
2689 };
2690 
2691 // A back inserter for RepeatedPtrField objects.
2692 template <typename T>
2693 class RepeatedPtrFieldBackInsertIterator
2694     : public std::iterator<std::output_iterator_tag, T> {
2695  public:
2696   RepeatedPtrFieldBackInsertIterator(RepeatedPtrField<T>* const mutable_field)
2697       : field_(mutable_field) {}
2698   RepeatedPtrFieldBackInsertIterator<T>& operator=(const T& value) {
2699     *field_->Add() = value;
2700     return *this;
2701   }
2702   RepeatedPtrFieldBackInsertIterator<T>& operator=(
2703       const T* const ptr_to_value) {
2704     *field_->Add() = *ptr_to_value;
2705     return *this;
2706   }
2707   RepeatedPtrFieldBackInsertIterator<T>& operator=(T&& value) {
2708     *field_->Add() = std::move(value);
2709     return *this;
2710   }
2711   RepeatedPtrFieldBackInsertIterator<T>& operator*() { return *this; }
2712   RepeatedPtrFieldBackInsertIterator<T>& operator++() { return *this; }
2713   RepeatedPtrFieldBackInsertIterator<T>& operator++(int /* unused */) {
2714     return *this;
2715   }
2716 
2717  private:
2718   RepeatedPtrField<T>* field_;
2719 };
2720 
2721 // A back inserter for RepeatedPtrFields that inserts by transferring ownership
2722 // of a pointer.
2723 template <typename T>
2724 class AllocatedRepeatedPtrFieldBackInsertIterator
2725     : public std::iterator<std::output_iterator_tag, T> {
2726  public:
2727   explicit AllocatedRepeatedPtrFieldBackInsertIterator(
2728       RepeatedPtrField<T>* const mutable_field)
2729       : field_(mutable_field) {}
2730   AllocatedRepeatedPtrFieldBackInsertIterator<T>& operator=(
2731       T* const ptr_to_value) {
2732     field_->AddAllocated(ptr_to_value);
2733     return *this;
2734   }
2735   AllocatedRepeatedPtrFieldBackInsertIterator<T>& operator*() { return *this; }
2736   AllocatedRepeatedPtrFieldBackInsertIterator<T>& operator++() { return *this; }
2737   AllocatedRepeatedPtrFieldBackInsertIterator<T>& operator++(int /* unused */) {
2738     return *this;
2739   }
2740 
2741  private:
2742   RepeatedPtrField<T>* field_;
2743 };
2744 
2745 // Almost identical to AllocatedRepeatedPtrFieldBackInsertIterator. This one
2746 // uses the UnsafeArenaAddAllocated instead.
2747 template <typename T>
2748 class UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator
2749     : public std::iterator<std::output_iterator_tag, T> {
2750  public:
2751   explicit UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator(
2752       RepeatedPtrField<T>* const mutable_field)
2753       : field_(mutable_field) {}
2754   UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>& operator=(
2755       T const* const ptr_to_value) {
2756     field_->UnsafeArenaAddAllocated(const_cast<T*>(ptr_to_value));
2757     return *this;
2758   }
2759   UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>& operator*() {
2760     return *this;
2761   }
2762   UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>& operator++() {
2763     return *this;
2764   }
2765   UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>& operator++(
2766       int /* unused */) {
2767     return *this;
2768   }
2769 
2770  private:
2771   RepeatedPtrField<T>* field_;
2772 };
2773 
2774 }  // namespace internal
2775 
2776 // Provides a back insert iterator for RepeatedField instances,
2777 // similar to std::back_inserter().
2778 template <typename T>
2779 internal::RepeatedFieldBackInsertIterator<T> RepeatedFieldBackInserter(
2780     RepeatedField<T>* const mutable_field) {
2781   return internal::RepeatedFieldBackInsertIterator<T>(mutable_field);
2782 }
2783 
2784 // Provides a back insert iterator for RepeatedPtrField instances,
2785 // similar to std::back_inserter().
2786 template <typename T>
2787 internal::RepeatedPtrFieldBackInsertIterator<T> RepeatedPtrFieldBackInserter(
2788     RepeatedPtrField<T>* const mutable_field) {
2789   return internal::RepeatedPtrFieldBackInsertIterator<T>(mutable_field);
2790 }
2791 
2792 // Special back insert iterator for RepeatedPtrField instances, just in
2793 // case someone wants to write generic template code that can access both
2794 // RepeatedFields and RepeatedPtrFields using a common name.
2795 template <typename T>
2796 internal::RepeatedPtrFieldBackInsertIterator<T> RepeatedFieldBackInserter(
2797     RepeatedPtrField<T>* const mutable_field) {
2798   return internal::RepeatedPtrFieldBackInsertIterator<T>(mutable_field);
2799 }
2800 
2801 // Provides a back insert iterator for RepeatedPtrField instances
2802 // similar to std::back_inserter() which transfers the ownership while
2803 // copying elements.
2804 template <typename T>
2805 internal::AllocatedRepeatedPtrFieldBackInsertIterator<T>
2806 AllocatedRepeatedPtrFieldBackInserter(
2807     RepeatedPtrField<T>* const mutable_field) {
2808   return internal::AllocatedRepeatedPtrFieldBackInsertIterator<T>(
2809       mutable_field);
2810 }
2811 
2812 // Similar to AllocatedRepeatedPtrFieldBackInserter, using
2813 // UnsafeArenaAddAllocated instead of AddAllocated.
2814 // This is slightly faster if that matters. It is also useful in legacy code
2815 // that uses temporary ownership to avoid copies. Example:
2816 //   RepeatedPtrField<T> temp_field;
2817 //   temp_field.AddAllocated(new T);
2818 //   ... // Do something with temp_field
2819 //   temp_field.ExtractSubrange(0, temp_field.size(), nullptr);
2820 // If you put temp_field on the arena this fails, because the ownership
2821 // transfers to the arena at the "AddAllocated" call and is not released anymore
2822 // causing a double delete. Using UnsafeArenaAddAllocated prevents this.
2823 template <typename T>
2824 internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>
2825 UnsafeArenaAllocatedRepeatedPtrFieldBackInserter(
2826     RepeatedPtrField<T>* const mutable_field) {
2827   return internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>(
2828       mutable_field);
2829 }
2830 
2831 // Extern declarations of common instantiations to reduce library bloat.
2832 extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<bool>;
2833 extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<int32>;
2834 extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<uint32>;
2835 extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<int64>;
2836 extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<uint64>;
2837 extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<float>;
2838 extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<double>;
2839 extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE
2840     RepeatedPtrField<std::string>;
2841 
2842 }  // namespace protobuf
2843 }  // namespace google
2844 
2845 #include <google/protobuf/port_undef.inc>
2846 
2847 #endif  // GOOGLE_PROTOBUF_REPEATED_FIELD_H__
2848