repeated_field.h 102 KB

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