You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

repeated_ptr_field.h 71 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970
  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. // This header covers RepeatedPtrField.
  42. // IWYU pragma: private, include "net/proto2/public/repeated_field.h"
  43. #ifndef GOOGLE_PROTOBUF_REPEATED_PTR_FIELD_H__
  44. #define GOOGLE_PROTOBUF_REPEATED_PTR_FIELD_H__
  45. #include <utility>
  46. #ifdef _MSC_VER
  47. // This is required for min/max on VS2013 only.
  48. #include <algorithm>
  49. #endif
  50. #include <iterator>
  51. #include <limits>
  52. #include <string>
  53. #include <type_traits>
  54. #include <google/protobuf/stubs/logging.h>
  55. #include <google/protobuf/stubs/common.h>
  56. #include <google/protobuf/arena.h>
  57. #include <google/protobuf/port.h>
  58. #include <google/protobuf/message_lite.h>
  59. // Must be included last.
  60. #include <google/protobuf/port_def.inc>
  61. #ifdef SWIG
  62. #error "You cannot SWIG proto headers"
  63. #endif
  64. namespace google {
  65. namespace protobuf {
  66. class Message;
  67. class Reflection;
  68. template <typename T>
  69. struct WeakRepeatedPtrField;
  70. namespace internal {
  71. class MergePartialFromCodedStreamHelper;
  72. class SwapFieldHelper;
  73. } // namespace internal
  74. namespace internal {
  75. template <typename It>
  76. class RepeatedPtrIterator;
  77. template <typename It, typename VoidPtr>
  78. class RepeatedPtrOverPtrsIterator;
  79. } // namespace internal
  80. namespace internal {
  81. // type-traits helper for RepeatedPtrFieldBase: we only want to invoke
  82. // arena-related "copy if on different arena" behavior if the necessary methods
  83. // exist on the contained type. In particular, we rely on MergeFrom() existing
  84. // as a general proxy for the fact that a copy will work, and we also provide a
  85. // specific override for std::string*.
  86. template <typename T>
  87. struct TypeImplementsMergeBehaviorProbeForMergeFrom {
  88. typedef char HasMerge;
  89. typedef long HasNoMerge;
  90. // We accept either of:
  91. // - void MergeFrom(const T& other)
  92. // - bool MergeFrom(const T& other)
  93. //
  94. // We mangle these names a bit to avoid compatibility issues in 'unclean'
  95. // include environments that may have, e.g., "#define test ..." (yes, this
  96. // exists).
  97. template <typename U, typename RetType, RetType (U::*)(const U& arg)>
  98. struct CheckType;
  99. template <typename U>
  100. static HasMerge Check(CheckType<U, void, &U::MergeFrom>*);
  101. template <typename U>
  102. static HasMerge Check(CheckType<U, bool, &U::MergeFrom>*);
  103. template <typename U>
  104. static HasNoMerge Check(...);
  105. // Resolves to either std::true_type or std::false_type.
  106. typedef std::integral_constant<bool,
  107. (sizeof(Check<T>(0)) == sizeof(HasMerge))>
  108. type;
  109. };
  110. template <typename T, typename = void>
  111. struct TypeImplementsMergeBehavior
  112. : TypeImplementsMergeBehaviorProbeForMergeFrom<T> {};
  113. template <>
  114. struct TypeImplementsMergeBehavior<std::string> {
  115. typedef std::true_type type;
  116. };
  117. template <typename T>
  118. struct IsMovable
  119. : std::integral_constant<bool, std::is_move_constructible<T>::value &&
  120. std::is_move_assignable<T>::value> {};
  121. // This is the common base class for RepeatedPtrFields. It deals only in void*
  122. // pointers. Users should not use this interface directly.
  123. //
  124. // The methods of this interface correspond to the methods of RepeatedPtrField,
  125. // but may have a template argument called TypeHandler. Its signature is:
  126. // class TypeHandler {
  127. // public:
  128. // typedef MyType Type;
  129. // static Type* New();
  130. // static Type* NewFromPrototype(const Type* prototype,
  131. // Arena* arena);
  132. // static void Delete(Type*);
  133. // static void Clear(Type*);
  134. // static void Merge(const Type& from, Type* to);
  135. //
  136. // // Only needs to be implemented if SpaceUsedExcludingSelf() is called.
  137. // static int SpaceUsedLong(const Type&);
  138. // };
  139. class PROTOBUF_EXPORT RepeatedPtrFieldBase {
  140. protected:
  141. constexpr RepeatedPtrFieldBase()
  142. : arena_(nullptr), current_size_(0), total_size_(0), rep_(nullptr) {}
  143. explicit RepeatedPtrFieldBase(Arena* arena)
  144. : arena_(arena), current_size_(0), total_size_(0), rep_(nullptr) {}
  145. RepeatedPtrFieldBase(const RepeatedPtrFieldBase&) = delete;
  146. RepeatedPtrFieldBase& operator=(const RepeatedPtrFieldBase&) = delete;
  147. ~RepeatedPtrFieldBase() {
  148. #ifndef NDEBUG
  149. // Try to trigger segfault / asan failure in non-opt builds. If arena_
  150. // lifetime has ended before the destructor.
  151. if (arena_) (void)arena_->SpaceAllocated();
  152. #endif
  153. }
  154. bool empty() const { return current_size_ == 0; }
  155. int size() const { return current_size_; }
  156. int Capacity() const { return total_size_; }
  157. template <typename TypeHandler>
  158. const typename TypeHandler::Type& at(int index) const {
  159. GOOGLE_CHECK_GE(index, 0);
  160. GOOGLE_CHECK_LT(index, current_size_);
  161. return *cast<TypeHandler>(rep_->elements[index]);
  162. }
  163. template <typename TypeHandler>
  164. typename TypeHandler::Type& at(int index) {
  165. GOOGLE_CHECK_GE(index, 0);
  166. GOOGLE_CHECK_LT(index, current_size_);
  167. return *cast<TypeHandler>(rep_->elements[index]);
  168. }
  169. template <typename TypeHandler>
  170. typename TypeHandler::Type* Mutable(int index) {
  171. GOOGLE_DCHECK_GE(index, 0);
  172. GOOGLE_DCHECK_LT(index, current_size_);
  173. return cast<TypeHandler>(rep_->elements[index]);
  174. }
  175. template <typename TypeHandler>
  176. typename TypeHandler::Type* Add(
  177. const typename TypeHandler::Type* prototype = nullptr) {
  178. if (rep_ != nullptr && current_size_ < rep_->allocated_size) {
  179. return cast<TypeHandler>(rep_->elements[current_size_++]);
  180. }
  181. typename TypeHandler::Type* result =
  182. TypeHandler::NewFromPrototype(prototype, arena_);
  183. return reinterpret_cast<typename TypeHandler::Type*>(
  184. AddOutOfLineHelper(result));
  185. }
  186. template <
  187. typename TypeHandler,
  188. typename std::enable_if<TypeHandler::Movable::value>::type* = nullptr>
  189. inline void Add(typename TypeHandler::Type&& value) {
  190. if (rep_ != nullptr && current_size_ < rep_->allocated_size) {
  191. *cast<TypeHandler>(rep_->elements[current_size_++]) = std::move(value);
  192. return;
  193. }
  194. if (!rep_ || rep_->allocated_size == total_size_) {
  195. Reserve(total_size_ + 1);
  196. }
  197. ++rep_->allocated_size;
  198. typename TypeHandler::Type* result =
  199. TypeHandler::New(arena_, std::move(value));
  200. rep_->elements[current_size_++] = result;
  201. }
  202. template <typename TypeHandler>
  203. void Delete(int index) {
  204. GOOGLE_DCHECK_GE(index, 0);
  205. GOOGLE_DCHECK_LT(index, current_size_);
  206. TypeHandler::Delete(cast<TypeHandler>(rep_->elements[index]), arena_);
  207. }
  208. // Must be called from destructor.
  209. template <typename TypeHandler>
  210. void Destroy() {
  211. if (rep_ != nullptr && arena_ == nullptr) {
  212. int n = rep_->allocated_size;
  213. void* const* elements = rep_->elements;
  214. for (int i = 0; i < n; i++) {
  215. TypeHandler::Delete(cast<TypeHandler>(elements[i]), nullptr);
  216. }
  217. const size_t size = total_size_ * sizeof(elements[0]) + kRepHeaderSize;
  218. internal::SizedDelete(rep_, size);
  219. }
  220. rep_ = nullptr;
  221. }
  222. bool NeedsDestroy() const { return rep_ != nullptr && arena_ == nullptr; }
  223. void DestroyProtos(); // implemented in the cc file
  224. public:
  225. // The next few methods are public so that they can be called from generated
  226. // code when implicit weak fields are used, but they should never be called by
  227. // application code.
  228. template <typename TypeHandler>
  229. const typename TypeHandler::Type& Get(int index) const {
  230. GOOGLE_DCHECK_GE(index, 0);
  231. GOOGLE_DCHECK_LT(index, current_size_);
  232. return *cast<TypeHandler>(rep_->elements[index]);
  233. }
  234. // Creates and adds an element using the given prototype, without introducing
  235. // a link-time dependency on the concrete message type. This method is used to
  236. // implement implicit weak fields. The prototype may be nullptr, in which case
  237. // an ImplicitWeakMessage will be used as a placeholder.
  238. MessageLite* AddWeak(const MessageLite* prototype);
  239. template <typename TypeHandler>
  240. void Clear() {
  241. const int n = current_size_;
  242. GOOGLE_DCHECK_GE(n, 0);
  243. if (n > 0) {
  244. void* const* elements = rep_->elements;
  245. int i = 0;
  246. do {
  247. TypeHandler::Clear(cast<TypeHandler>(elements[i++]));
  248. } while (i < n);
  249. current_size_ = 0;
  250. }
  251. }
  252. template <typename TypeHandler>
  253. void MergeFrom(const RepeatedPtrFieldBase& other) {
  254. // To avoid unnecessary code duplication and reduce binary size, we use a
  255. // layered approach to implementing MergeFrom(). The toplevel method is
  256. // templated, so we get a small thunk per concrete message type in the
  257. // binary. This calls a shared implementation with most of the logic,
  258. // passing a function pointer to another type-specific piece of code that
  259. // calls the object-allocate and merge handlers.
  260. GOOGLE_DCHECK_NE(&other, this);
  261. if (other.current_size_ == 0) return;
  262. MergeFromInternal(other,
  263. &RepeatedPtrFieldBase::MergeFromInnerLoop<TypeHandler>);
  264. }
  265. inline void InternalSwap(RepeatedPtrFieldBase* rhs) {
  266. GOOGLE_DCHECK(this != rhs);
  267. // Swap all fields at once.
  268. auto temp = std::make_tuple(rhs->arena_, rhs->current_size_,
  269. rhs->total_size_, rhs->rep_);
  270. std::tie(rhs->arena_, rhs->current_size_, rhs->total_size_, rhs->rep_) =
  271. std::make_tuple(arena_, current_size_, total_size_, rep_);
  272. std::tie(arena_, current_size_, total_size_, rep_) = temp;
  273. }
  274. protected:
  275. template <typename TypeHandler>
  276. void RemoveLast() {
  277. GOOGLE_DCHECK_GT(current_size_, 0);
  278. TypeHandler::Clear(cast<TypeHandler>(rep_->elements[--current_size_]));
  279. }
  280. template <typename TypeHandler>
  281. void CopyFrom(const RepeatedPtrFieldBase& other) {
  282. if (&other == this) return;
  283. RepeatedPtrFieldBase::Clear<TypeHandler>();
  284. RepeatedPtrFieldBase::MergeFrom<TypeHandler>(other);
  285. }
  286. void CloseGap(int start, int num); // implemented in the cc file
  287. void Reserve(int new_size); // implemented in the cc file
  288. template <typename TypeHandler>
  289. static inline typename TypeHandler::Type* copy(
  290. typename TypeHandler::Type* value) {
  291. auto* new_value = TypeHandler::NewFromPrototype(value, nullptr);
  292. TypeHandler::Merge(*value, new_value);
  293. return new_value;
  294. }
  295. // Used for constructing iterators.
  296. void* const* raw_data() const { return rep_ ? rep_->elements : nullptr; }
  297. void** raw_mutable_data() const {
  298. return rep_ ? const_cast<void**>(rep_->elements) : nullptr;
  299. }
  300. template <typename TypeHandler>
  301. typename TypeHandler::Type** mutable_data() {
  302. // TODO(kenton): Breaks C++ aliasing rules. We should probably remove this
  303. // method entirely.
  304. return reinterpret_cast<typename TypeHandler::Type**>(raw_mutable_data());
  305. }
  306. template <typename TypeHandler>
  307. const typename TypeHandler::Type* const* data() const {
  308. // TODO(kenton): Breaks C++ aliasing rules. We should probably remove this
  309. // method entirely.
  310. return reinterpret_cast<const typename TypeHandler::Type* const*>(
  311. raw_data());
  312. }
  313. template <typename TypeHandler>
  314. PROTOBUF_NDEBUG_INLINE void Swap(RepeatedPtrFieldBase* other) {
  315. #ifdef PROTOBUF_FORCE_COPY_IN_SWAP
  316. if (GetOwningArena() != nullptr &&
  317. GetOwningArena() == other->GetOwningArena())
  318. #else // PROTOBUF_FORCE_COPY_IN_SWAP
  319. if (GetOwningArena() == other->GetOwningArena())
  320. #endif // !PROTOBUF_FORCE_COPY_IN_SWAP
  321. {
  322. InternalSwap(other);
  323. } else {
  324. SwapFallback<TypeHandler>(other);
  325. }
  326. }
  327. void SwapElements(int index1, int index2) {
  328. using std::swap; // enable ADL with fallback
  329. swap(rep_->elements[index1], rep_->elements[index2]);
  330. }
  331. template <typename TypeHandler>
  332. size_t SpaceUsedExcludingSelfLong() const {
  333. size_t allocated_bytes = static_cast<size_t>(total_size_) * sizeof(void*);
  334. if (rep_ != nullptr) {
  335. for (int i = 0; i < rep_->allocated_size; ++i) {
  336. allocated_bytes +=
  337. TypeHandler::SpaceUsedLong(*cast<TypeHandler>(rep_->elements[i]));
  338. }
  339. allocated_bytes += kRepHeaderSize;
  340. }
  341. return allocated_bytes;
  342. }
  343. // Advanced memory management --------------------------------------
  344. // Like Add(), but if there are no cleared objects to use, returns nullptr.
  345. template <typename TypeHandler>
  346. typename TypeHandler::Type* AddFromCleared() {
  347. if (rep_ != nullptr && current_size_ < rep_->allocated_size) {
  348. return cast<TypeHandler>(rep_->elements[current_size_++]);
  349. } else {
  350. return nullptr;
  351. }
  352. }
  353. template <typename TypeHandler>
  354. void AddAllocated(typename TypeHandler::Type* value) {
  355. typename TypeImplementsMergeBehavior<typename TypeHandler::Type>::type t;
  356. AddAllocatedInternal<TypeHandler>(value, t);
  357. }
  358. template <typename TypeHandler>
  359. void UnsafeArenaAddAllocated(typename TypeHandler::Type* value) {
  360. // Make room for the new pointer.
  361. if (!rep_ || current_size_ == total_size_) {
  362. // The array is completely full with no cleared objects, so grow it.
  363. Reserve(total_size_ + 1);
  364. ++rep_->allocated_size;
  365. } else if (rep_->allocated_size == total_size_) {
  366. // There is no more space in the pointer array because it contains some
  367. // cleared objects awaiting reuse. We don't want to grow the array in
  368. // this case because otherwise a loop calling AddAllocated() followed by
  369. // Clear() would leak memory.
  370. TypeHandler::Delete(cast<TypeHandler>(rep_->elements[current_size_]),
  371. arena_);
  372. } else if (current_size_ < rep_->allocated_size) {
  373. // We have some cleared objects. We don't care about their order, so we
  374. // can just move the first one to the end to make space.
  375. rep_->elements[rep_->allocated_size] = rep_->elements[current_size_];
  376. ++rep_->allocated_size;
  377. } else {
  378. // There are no cleared objects.
  379. ++rep_->allocated_size;
  380. }
  381. rep_->elements[current_size_++] = value;
  382. }
  383. template <typename TypeHandler>
  384. PROTOBUF_NODISCARD typename TypeHandler::Type* ReleaseLast() {
  385. typename TypeImplementsMergeBehavior<typename TypeHandler::Type>::type t;
  386. return ReleaseLastInternal<TypeHandler>(t);
  387. }
  388. // Releases and returns the last element, but does not do out-of-arena copy.
  389. // Instead, just returns the raw pointer to the contained element in the
  390. // arena.
  391. template <typename TypeHandler>
  392. typename TypeHandler::Type* UnsafeArenaReleaseLast() {
  393. GOOGLE_DCHECK_GT(current_size_, 0);
  394. typename TypeHandler::Type* result =
  395. cast<TypeHandler>(rep_->elements[--current_size_]);
  396. --rep_->allocated_size;
  397. if (current_size_ < rep_->allocated_size) {
  398. // There are cleared elements on the end; replace the removed element
  399. // with the last allocated element.
  400. rep_->elements[current_size_] = rep_->elements[rep_->allocated_size];
  401. }
  402. return result;
  403. }
  404. int ClearedCount() const {
  405. return rep_ ? (rep_->allocated_size - current_size_) : 0;
  406. }
  407. template <typename TypeHandler>
  408. void AddCleared(typename TypeHandler::Type* value) {
  409. GOOGLE_DCHECK(GetOwningArena() == nullptr) << "AddCleared() can only be used on a "
  410. "RepeatedPtrField not on an arena.";
  411. GOOGLE_DCHECK(TypeHandler::GetOwningArena(value) == nullptr)
  412. << "AddCleared() can only accept values not on an arena.";
  413. if (!rep_ || rep_->allocated_size == total_size_) {
  414. Reserve(total_size_ + 1);
  415. }
  416. rep_->elements[rep_->allocated_size++] = value;
  417. }
  418. template <typename TypeHandler>
  419. PROTOBUF_NODISCARD typename TypeHandler::Type* ReleaseCleared() {
  420. GOOGLE_DCHECK(GetOwningArena() == nullptr)
  421. << "ReleaseCleared() can only be used on a RepeatedPtrField not on "
  422. << "an arena.";
  423. GOOGLE_DCHECK(GetOwningArena() == nullptr);
  424. GOOGLE_DCHECK(rep_ != nullptr);
  425. GOOGLE_DCHECK_GT(rep_->allocated_size, current_size_);
  426. return cast<TypeHandler>(rep_->elements[--rep_->allocated_size]);
  427. }
  428. template <typename TypeHandler>
  429. void AddAllocatedInternal(typename TypeHandler::Type* value, std::true_type) {
  430. // AddAllocated version that implements arena-safe copying behavior.
  431. Arena* element_arena =
  432. reinterpret_cast<Arena*>(TypeHandler::GetOwningArena(value));
  433. Arena* arena = GetOwningArena();
  434. if (arena == element_arena && rep_ && rep_->allocated_size < total_size_) {
  435. // Fast path: underlying arena representation (tagged pointer) is equal to
  436. // our arena pointer, and we can add to array without resizing it (at
  437. // least one slot that is not allocated).
  438. void** elems = rep_->elements;
  439. if (current_size_ < rep_->allocated_size) {
  440. // Make space at [current] by moving first allocated element to end of
  441. // allocated list.
  442. elems[rep_->allocated_size] = elems[current_size_];
  443. }
  444. elems[current_size_] = value;
  445. current_size_ = current_size_ + 1;
  446. rep_->allocated_size = rep_->allocated_size + 1;
  447. } else {
  448. AddAllocatedSlowWithCopy<TypeHandler>(value, element_arena, arena);
  449. }
  450. }
  451. template <typename TypeHandler>
  452. void AddAllocatedInternal(
  453. // AddAllocated version that does not implement arena-safe copying
  454. // behavior.
  455. typename TypeHandler::Type* value, std::false_type) {
  456. if (rep_ && rep_->allocated_size < total_size_) {
  457. // Fast path: underlying arena representation (tagged pointer) is equal to
  458. // our arena pointer, and we can add to array without resizing it (at
  459. // least one slot that is not allocated).
  460. void** elems = rep_->elements;
  461. if (current_size_ < rep_->allocated_size) {
  462. // Make space at [current] by moving first allocated element to end of
  463. // allocated list.
  464. elems[rep_->allocated_size] = elems[current_size_];
  465. }
  466. elems[current_size_] = value;
  467. current_size_ = current_size_ + 1;
  468. ++rep_->allocated_size;
  469. } else {
  470. UnsafeArenaAddAllocated<TypeHandler>(value);
  471. }
  472. }
  473. // Slowpath handles all cases, copying if necessary.
  474. template <typename TypeHandler>
  475. PROTOBUF_NOINLINE void AddAllocatedSlowWithCopy(
  476. // Pass value_arena and my_arena to avoid duplicate virtual call (value)
  477. // or load (mine).
  478. typename TypeHandler::Type* value, Arena* value_arena, Arena* my_arena) {
  479. // Ensure that either the value is in the same arena, or if not, we do the
  480. // appropriate thing: Own() it (if it's on heap and we're in an arena) or
  481. // copy it to our arena/heap (otherwise).
  482. if (my_arena != nullptr && value_arena == nullptr) {
  483. my_arena->Own(value);
  484. } else if (my_arena != value_arena) {
  485. typename TypeHandler::Type* new_value =
  486. TypeHandler::NewFromPrototype(value, my_arena);
  487. TypeHandler::Merge(*value, new_value);
  488. TypeHandler::Delete(value, value_arena);
  489. value = new_value;
  490. }
  491. UnsafeArenaAddAllocated<TypeHandler>(value);
  492. }
  493. template <typename TypeHandler>
  494. typename TypeHandler::Type* ReleaseLastInternal(std::true_type) {
  495. // ReleaseLast() for types that implement merge/copy behavior.
  496. // First, release an element.
  497. typename TypeHandler::Type* result = UnsafeArenaReleaseLast<TypeHandler>();
  498. // Now perform a copy if we're on an arena.
  499. Arena* arena = GetOwningArena();
  500. typename TypeHandler::Type* new_result;
  501. #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE
  502. new_result = copy<TypeHandler>(result);
  503. if (arena == nullptr) delete result;
  504. #else // PROTOBUF_FORCE_COPY_IN_RELEASE
  505. new_result = (arena == nullptr) ? result : copy<TypeHandler>(result);
  506. #endif // !PROTOBUF_FORCE_COPY_IN_RELEASE
  507. return new_result;
  508. }
  509. template <typename TypeHandler>
  510. typename TypeHandler::Type* ReleaseLastInternal(std::false_type) {
  511. // ReleaseLast() for types that *do not* implement merge/copy behavior --
  512. // this is the same as UnsafeArenaReleaseLast(). Note that we GOOGLE_DCHECK-fail if
  513. // we're on an arena, since the user really should implement the copy
  514. // operation in this case.
  515. GOOGLE_DCHECK(GetOwningArena() == nullptr)
  516. << "ReleaseLast() called on a RepeatedPtrField that is on an arena, "
  517. << "with a type that does not implement MergeFrom. This is unsafe; "
  518. << "please implement MergeFrom for your type.";
  519. return UnsafeArenaReleaseLast<TypeHandler>();
  520. }
  521. template <typename TypeHandler>
  522. PROTOBUF_NOINLINE void SwapFallback(RepeatedPtrFieldBase* other) {
  523. #ifdef PROTOBUF_FORCE_COPY_IN_SWAP
  524. GOOGLE_DCHECK(GetOwningArena() == nullptr ||
  525. other->GetOwningArena() != GetOwningArena());
  526. #else // PROTOBUF_FORCE_COPY_IN_SWAP
  527. GOOGLE_DCHECK(other->GetOwningArena() != GetOwningArena());
  528. #endif // !PROTOBUF_FORCE_COPY_IN_SWAP
  529. // Copy semantics in this case. We try to improve efficiency by placing the
  530. // temporary on |other|'s arena so that messages are copied twice rather
  531. // than three times.
  532. RepeatedPtrFieldBase temp(other->GetOwningArena());
  533. temp.MergeFrom<TypeHandler>(*this);
  534. this->Clear<TypeHandler>();
  535. this->MergeFrom<TypeHandler>(*other);
  536. other->InternalSwap(&temp);
  537. temp.Destroy<TypeHandler>(); // Frees rep_ if `other` had no arena.
  538. }
  539. inline Arena* GetArena() const { return arena_; }
  540. protected:
  541. inline Arena* GetOwningArena() const { return arena_; }
  542. private:
  543. template <typename T> friend class Arena::InternalHelper;
  544. static constexpr int kInitialSize = 0;
  545. // A few notes on internal representation:
  546. //
  547. // We use an indirected approach, with struct Rep, to keep
  548. // sizeof(RepeatedPtrFieldBase) equivalent to what it was before arena support
  549. // was added; namely, 3 8-byte machine words on x86-64. An instance of Rep is
  550. // allocated only when the repeated field is non-empty, and it is a
  551. // dynamically-sized struct (the header is directly followed by elements[]).
  552. // We place arena_ and current_size_ directly in the object to avoid cache
  553. // misses due to the indirection, because these fields are checked frequently.
  554. // Placing all fields directly in the RepeatedPtrFieldBase instance would cost
  555. // significant performance for memory-sensitive workloads.
  556. Arena* arena_;
  557. int current_size_;
  558. int total_size_;
  559. struct Rep {
  560. int allocated_size;
  561. // Here we declare a huge array as a way of approximating C's "flexible
  562. // array member" feature without relying on undefined behavior.
  563. void* elements[(std::numeric_limits<int>::max() - 2 * sizeof(int)) /
  564. sizeof(void*)];
  565. };
  566. static constexpr size_t kRepHeaderSize = offsetof(Rep, elements);
  567. Rep* rep_;
  568. template <typename TypeHandler>
  569. static inline typename TypeHandler::Type* cast(void* element) {
  570. return reinterpret_cast<typename TypeHandler::Type*>(element);
  571. }
  572. template <typename TypeHandler>
  573. static inline const typename TypeHandler::Type* cast(const void* element) {
  574. return reinterpret_cast<const typename TypeHandler::Type*>(element);
  575. }
  576. // Non-templated inner function to avoid code duplication. Takes a function
  577. // pointer to the type-specific (templated) inner allocate/merge loop.
  578. void MergeFromInternal(const RepeatedPtrFieldBase& other,
  579. void (RepeatedPtrFieldBase::*inner_loop)(void**,
  580. void**, int,
  581. int)) {
  582. // Note: wrapper has already guaranteed that other.rep_ != nullptr here.
  583. int other_size = other.current_size_;
  584. void** other_elements = other.rep_->elements;
  585. void** new_elements = InternalExtend(other_size);
  586. int allocated_elems = rep_->allocated_size - current_size_;
  587. (this->*inner_loop)(new_elements, other_elements, other_size,
  588. allocated_elems);
  589. current_size_ += other_size;
  590. if (rep_->allocated_size < current_size_) {
  591. rep_->allocated_size = current_size_;
  592. }
  593. }
  594. // Merges other_elems to our_elems.
  595. template <typename TypeHandler>
  596. PROTOBUF_NOINLINE void MergeFromInnerLoop(void** our_elems,
  597. void** other_elems, int length,
  598. int already_allocated) {
  599. if (already_allocated < length) {
  600. Arena* arena = GetOwningArena();
  601. typename TypeHandler::Type* elem_prototype =
  602. reinterpret_cast<typename TypeHandler::Type*>(other_elems[0]);
  603. for (int i = already_allocated; i < length; i++) {
  604. // Allocate a new empty element that we'll merge into below
  605. typename TypeHandler::Type* new_elem =
  606. TypeHandler::NewFromPrototype(elem_prototype, arena);
  607. our_elems[i] = new_elem;
  608. }
  609. }
  610. // Main loop that does the actual merging
  611. for (int i = 0; i < length; i++) {
  612. // Already allocated: use existing element.
  613. typename TypeHandler::Type* other_elem =
  614. reinterpret_cast<typename TypeHandler::Type*>(other_elems[i]);
  615. typename TypeHandler::Type* new_elem =
  616. reinterpret_cast<typename TypeHandler::Type*>(our_elems[i]);
  617. TypeHandler::Merge(*other_elem, new_elem);
  618. }
  619. }
  620. // Internal helper: extends array space if necessary to contain
  621. // |extend_amount| more elements, and returns a pointer to the element
  622. // immediately following the old list of elements. This interface factors out
  623. // common behavior from Reserve() and MergeFrom() to reduce code size.
  624. // |extend_amount| must be > 0.
  625. void** InternalExtend(int extend_amount);
  626. // Internal helper for Add: adds "obj" as the next element in the
  627. // array, including potentially resizing the array with Reserve if
  628. // needed
  629. void* AddOutOfLineHelper(void* obj);
  630. // The reflection implementation needs to call protected methods directly,
  631. // reinterpreting pointers as being to Message instead of a specific Message
  632. // subclass.
  633. friend class ::PROTOBUF_NAMESPACE_ID::Reflection;
  634. friend class ::PROTOBUF_NAMESPACE_ID::internal::SwapFieldHelper;
  635. // ExtensionSet stores repeated message extensions as
  636. // RepeatedPtrField<MessageLite>, but non-lite ExtensionSets need to implement
  637. // SpaceUsedLong(), and thus need to call SpaceUsedExcludingSelfLong()
  638. // reinterpreting MessageLite as Message. ExtensionSet also needs to make use
  639. // of AddFromCleared(), which is not part of the public interface.
  640. friend class ExtensionSet;
  641. // The MapFieldBase implementation needs to call protected methods directly,
  642. // reinterpreting pointers as being to Message instead of a specific Message
  643. // subclass.
  644. friend class MapFieldBase;
  645. friend class MapFieldBaseStub;
  646. // The table-driven MergePartialFromCodedStream implementation needs to
  647. // operate on RepeatedPtrField<MessageLite>.
  648. friend class MergePartialFromCodedStreamHelper;
  649. friend class AccessorHelper;
  650. template <typename T>
  651. friend struct google::protobuf::WeakRepeatedPtrField;
  652. friend class internal::TcParser; // TODO(jorg): Remove this friend.
  653. };
  654. template <typename GenericType>
  655. class GenericTypeHandler {
  656. public:
  657. typedef GenericType Type;
  658. using Movable = IsMovable<GenericType>;
  659. static inline GenericType* New(Arena* arena) {
  660. return Arena::CreateMaybeMessage<Type>(arena);
  661. }
  662. static inline GenericType* New(Arena* arena, GenericType&& value) {
  663. return Arena::Create<GenericType>(arena, std::move(value));
  664. }
  665. static inline GenericType* NewFromPrototype(const GenericType* /*prototype*/,
  666. Arena* arena = nullptr) {
  667. return New(arena);
  668. }
  669. static inline void Delete(GenericType* value, Arena* arena) {
  670. if (arena == nullptr) {
  671. delete value;
  672. }
  673. }
  674. static inline Arena* GetOwningArena(GenericType* value) {
  675. return Arena::GetOwningArena<Type>(value);
  676. }
  677. static inline void Clear(GenericType* value) { value->Clear(); }
  678. static void Merge(const GenericType& from, GenericType* to);
  679. static inline size_t SpaceUsedLong(const GenericType& value) {
  680. return value.SpaceUsedLong();
  681. }
  682. };
  683. // NewFromPrototypeHelper() is not defined inline here, as we will need to do a
  684. // virtual function dispatch anyways to go from Message* to call New/Merge. (The
  685. // additional helper is needed as a workaround for MSVC.)
  686. MessageLite* NewFromPrototypeHelper(const MessageLite* prototype, Arena* arena);
  687. template <>
  688. inline MessageLite* GenericTypeHandler<MessageLite>::NewFromPrototype(
  689. const MessageLite* prototype, Arena* arena) {
  690. return NewFromPrototypeHelper(prototype, arena);
  691. }
  692. template <>
  693. inline Arena* GenericTypeHandler<MessageLite>::GetOwningArena(
  694. MessageLite* value) {
  695. return value->GetOwningArena();
  696. }
  697. template <typename GenericType>
  698. PROTOBUF_NOINLINE inline void GenericTypeHandler<GenericType>::Merge(
  699. const GenericType& from, GenericType* to) {
  700. to->MergeFrom(from);
  701. }
  702. template <>
  703. void GenericTypeHandler<MessageLite>::Merge(const MessageLite& from,
  704. MessageLite* to);
  705. template <>
  706. inline void GenericTypeHandler<std::string>::Clear(std::string* value) {
  707. value->clear();
  708. }
  709. template <>
  710. void GenericTypeHandler<std::string>::Merge(const std::string& from,
  711. std::string* to);
  712. // Message specialization bodies defined in message.cc. This split is necessary
  713. // to allow proto2-lite (which includes this header) to be independent of
  714. // Message.
  715. template <>
  716. PROTOBUF_EXPORT Message* GenericTypeHandler<Message>::NewFromPrototype(
  717. const Message* prototype, Arena* arena);
  718. template <>
  719. PROTOBUF_EXPORT Arena* GenericTypeHandler<Message>::GetOwningArena(
  720. Message* value);
  721. class StringTypeHandler {
  722. public:
  723. typedef std::string Type;
  724. using Movable = IsMovable<Type>;
  725. static inline std::string* New(Arena* arena) {
  726. return Arena::Create<std::string>(arena);
  727. }
  728. static inline std::string* New(Arena* arena, std::string&& value) {
  729. return Arena::Create<std::string>(arena, std::move(value));
  730. }
  731. static inline std::string* NewFromPrototype(const std::string*,
  732. Arena* arena) {
  733. return New(arena);
  734. }
  735. static inline Arena* GetOwningArena(std::string*) { return nullptr; }
  736. static inline void Delete(std::string* value, Arena* arena) {
  737. if (arena == nullptr) {
  738. delete value;
  739. }
  740. }
  741. static inline void Clear(std::string* value) { value->clear(); }
  742. static inline void Merge(const std::string& from, std::string* to) {
  743. *to = from;
  744. }
  745. static size_t SpaceUsedLong(const std::string& value) {
  746. return sizeof(value) + StringSpaceUsedExcludingSelfLong(value);
  747. }
  748. };
  749. } // namespace internal
  750. // RepeatedPtrField is like RepeatedField, but used for repeated strings or
  751. // Messages.
  752. template <typename Element>
  753. class RepeatedPtrField final : private internal::RepeatedPtrFieldBase {
  754. public:
  755. constexpr RepeatedPtrField();
  756. explicit RepeatedPtrField(Arena* arena);
  757. RepeatedPtrField(const RepeatedPtrField& other);
  758. template <typename Iter,
  759. typename = typename std::enable_if<std::is_constructible<
  760. Element, decltype(*std::declval<Iter>())>::value>::type>
  761. RepeatedPtrField(Iter begin, Iter end);
  762. ~RepeatedPtrField();
  763. RepeatedPtrField& operator=(const RepeatedPtrField& other);
  764. RepeatedPtrField(RepeatedPtrField&& other) noexcept;
  765. RepeatedPtrField& operator=(RepeatedPtrField&& other) noexcept;
  766. bool empty() const;
  767. int size() const;
  768. const Element& Get(int index) const;
  769. Element* Mutable(int index);
  770. // Unlike std::vector, adding an element to a RepeatedPtrField doesn't always
  771. // make a new element; it might re-use an element left over from when the
  772. // field was Clear()'d or reize()'d smaller. For this reason, Add() is the
  773. // fastest API for adding a new element.
  774. Element* Add();
  775. // `Add(std::move(value));` is equivalent to `*Add() = std::move(value);`
  776. // It will either move-construct to the end of this field, or swap value
  777. // with the new-or-recycled element at the end of this field. Note that
  778. // this operation is very slow if this RepeatedPtrField is not on the
  779. // same Arena, if any, as `value`.
  780. void Add(Element&& value);
  781. // Copying to the end of this RepeatedPtrField is slowest of all; it can't
  782. // reliably copy-construct to the last element of this RepeatedPtrField, for
  783. // example (unlike std::vector).
  784. // We currently block this API. The right way to add to the end is to call
  785. // Add() and modify the element it points to.
  786. // If you must add an existing value, call `*Add() = value;`
  787. void Add(const Element& value) = delete;
  788. // Append elements in the range [begin, end) after reserving
  789. // the appropriate number of elements.
  790. template <typename Iter>
  791. void Add(Iter begin, Iter end);
  792. const Element& operator[](int index) const { return Get(index); }
  793. Element& operator[](int index) { return *Mutable(index); }
  794. const Element& at(int index) const;
  795. Element& at(int index);
  796. // Removes the last element in the array.
  797. // Ownership of the element is retained by the array.
  798. void RemoveLast();
  799. // Deletes elements with indices in the range [start .. start+num-1].
  800. // Caution: moves all elements with indices [start+num .. ].
  801. // Calling this routine inside a loop can cause quadratic behavior.
  802. void DeleteSubrange(int start, int num);
  803. PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear();
  804. void MergeFrom(const RepeatedPtrField& other);
  805. PROTOBUF_ATTRIBUTE_REINITIALIZES void CopyFrom(const RepeatedPtrField& other);
  806. // Replaces the contents with RepeatedPtrField(begin, end).
  807. template <typename Iter>
  808. PROTOBUF_ATTRIBUTE_REINITIALIZES void Assign(Iter begin, Iter end);
  809. // Reserves space to expand the field to at least the given size. This only
  810. // resizes the pointer array; it doesn't allocate any objects. If the
  811. // array is grown, it will always be at least doubled in size.
  812. void Reserve(int new_size);
  813. int Capacity() const;
  814. // Gets the underlying array. This pointer is possibly invalidated by
  815. // any add or remove operation.
  816. //
  817. // This API is deprecated. Instead of directly working with element array,
  818. // use APIs in repeated_field_util.h; e.g. sorting, etc.
  819. PROTOBUF_DEPRECATED_MSG("Use APIs in repeated_field_util.h")
  820. Element** mutable_data();
  821. const Element* const* data() const;
  822. // Swaps entire contents with "other". If they are on separate arenas, then
  823. // copies data.
  824. void Swap(RepeatedPtrField* other);
  825. // Swaps entire contents with "other". Caller should guarantee that either
  826. // both fields are on the same arena or both are on the heap. Swapping between
  827. // different arenas with this function is disallowed and is caught via
  828. // GOOGLE_DCHECK.
  829. void UnsafeArenaSwap(RepeatedPtrField* other);
  830. // Swaps two elements.
  831. void SwapElements(int index1, int index2);
  832. // STL-like iterator support
  833. typedef internal::RepeatedPtrIterator<Element> iterator;
  834. typedef internal::RepeatedPtrIterator<const Element> const_iterator;
  835. typedef Element value_type;
  836. typedef value_type& reference;
  837. typedef const value_type& const_reference;
  838. typedef value_type* pointer;
  839. typedef const value_type* const_pointer;
  840. typedef int size_type;
  841. typedef ptrdiff_t difference_type;
  842. iterator begin();
  843. const_iterator begin() const;
  844. const_iterator cbegin() const;
  845. iterator end();
  846. const_iterator end() const;
  847. const_iterator cend() const;
  848. // Reverse iterator support
  849. typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
  850. typedef std::reverse_iterator<iterator> reverse_iterator;
  851. reverse_iterator rbegin() { return reverse_iterator(end()); }
  852. const_reverse_iterator rbegin() const {
  853. return const_reverse_iterator(end());
  854. }
  855. reverse_iterator rend() { return reverse_iterator(begin()); }
  856. const_reverse_iterator rend() const {
  857. return const_reverse_iterator(begin());
  858. }
  859. // Custom STL-like iterator that iterates over and returns the underlying
  860. // pointers to Element rather than Element itself.
  861. typedef internal::RepeatedPtrOverPtrsIterator<Element*, void*>
  862. pointer_iterator;
  863. typedef internal::RepeatedPtrOverPtrsIterator<const Element* const,
  864. const void* const>
  865. const_pointer_iterator;
  866. pointer_iterator pointer_begin();
  867. const_pointer_iterator pointer_begin() const;
  868. pointer_iterator pointer_end();
  869. const_pointer_iterator pointer_end() const;
  870. // Returns (an estimate of) the number of bytes used by the repeated field,
  871. // excluding sizeof(*this).
  872. size_t SpaceUsedExcludingSelfLong() const;
  873. int SpaceUsedExcludingSelf() const {
  874. return internal::ToIntSize(SpaceUsedExcludingSelfLong());
  875. }
  876. // Advanced memory management --------------------------------------
  877. // When hardcore memory management becomes necessary -- as it sometimes
  878. // does here at Google -- the following methods may be useful.
  879. // Adds an already-allocated object, passing ownership to the
  880. // RepeatedPtrField.
  881. //
  882. // Note that some special behavior occurs with respect to arenas:
  883. //
  884. // (i) if this field holds submessages, the new submessage will be copied if
  885. // the original is in an arena and this RepeatedPtrField is either in a
  886. // different arena, or on the heap.
  887. // (ii) if this field holds strings, the passed-in string *must* be
  888. // heap-allocated, not arena-allocated. There is no way to dynamically check
  889. // this at runtime, so User Beware.
  890. void AddAllocated(Element* value);
  891. // Removes and returns the last element, passing ownership to the caller.
  892. // Requires: size() > 0
  893. //
  894. // If this RepeatedPtrField is on an arena, an object copy is required to pass
  895. // ownership back to the user (for compatible semantics). Use
  896. // UnsafeArenaReleaseLast() if this behavior is undesired.
  897. PROTOBUF_NODISCARD Element* ReleaseLast();
  898. // Adds an already-allocated object, skipping arena-ownership checks. The user
  899. // must guarantee that the given object is in the same arena as this
  900. // RepeatedPtrField.
  901. // It is also useful in legacy code that uses temporary ownership to avoid
  902. // copies. Example:
  903. // RepeatedPtrField<T> temp_field;
  904. // temp_field.UnsafeArenaAddAllocated(new T);
  905. // ... // Do something with temp_field
  906. // temp_field.UnsafeArenaExtractSubrange(0, temp_field.size(), nullptr);
  907. // If you put temp_field on the arena this fails, because the ownership
  908. // transfers to the arena at the "AddAllocated" call and is not released
  909. // anymore, causing a double delete. UnsafeArenaAddAllocated prevents this.
  910. void UnsafeArenaAddAllocated(Element* value);
  911. // Removes and returns the last element. Unlike ReleaseLast, the returned
  912. // pointer is always to the original object. This may be in an arena, in
  913. // which case it would have the arena's lifetime.
  914. // Requires: current_size_ > 0
  915. Element* UnsafeArenaReleaseLast();
  916. // Extracts elements with indices in the range "[start .. start+num-1]".
  917. // The caller assumes ownership of the extracted elements and is responsible
  918. // for deleting them when they are no longer needed.
  919. // If "elements" is non-nullptr, then pointers to the extracted elements
  920. // are stored in "elements[0 .. num-1]" for the convenience of the caller.
  921. // If "elements" is nullptr, then the caller must use some other mechanism
  922. // to perform any further operations (like deletion) on these elements.
  923. // Caution: implementation also moves elements with indices [start+num ..].
  924. // Calling this routine inside a loop can cause quadratic behavior.
  925. //
  926. // Memory copying behavior is identical to ReleaseLast(), described above: if
  927. // this RepeatedPtrField is on an arena, an object copy is performed for each
  928. // returned element, so that all returned element pointers are to
  929. // heap-allocated copies. If this copy is not desired, the user should call
  930. // UnsafeArenaExtractSubrange().
  931. void ExtractSubrange(int start, int num, Element** elements);
  932. // Identical to ExtractSubrange() described above, except that no object
  933. // copies are ever performed. Instead, the raw object pointers are returned.
  934. // Thus, if on an arena, the returned objects must not be freed, because they
  935. // will not be heap-allocated objects.
  936. void UnsafeArenaExtractSubrange(int start, int num, Element** elements);
  937. // When elements are removed by calls to RemoveLast() or Clear(), they
  938. // are not actually freed. Instead, they are cleared and kept so that
  939. // they can be reused later. This can save lots of CPU time when
  940. // repeatedly reusing a protocol message for similar purposes.
  941. //
  942. // Hardcore programs may choose to manipulate these cleared objects
  943. // to better optimize memory management using the following routines.
  944. // Gets the number of cleared objects that are currently being kept
  945. // around for reuse.
  946. int ClearedCount() const;
  947. #ifndef PROTOBUF_FUTURE_BREAKING_CHANGES
  948. // Adds an element to the pool of cleared objects, passing ownership to
  949. // the RepeatedPtrField. The element must be cleared prior to calling
  950. // this method.
  951. //
  952. // This method cannot be called when either the repeated field or |value| is
  953. // on an arena; both cases will trigger a GOOGLE_DCHECK-failure.
  954. void AddCleared(Element* value);
  955. // Removes and returns a single element from the cleared pool, passing
  956. // ownership to the caller. The element is guaranteed to be cleared.
  957. // Requires: ClearedCount() > 0
  958. //
  959. // This method cannot be called when the repeated field is on an arena; doing
  960. // so will trigger a GOOGLE_DCHECK-failure.
  961. PROTOBUF_NODISCARD Element* ReleaseCleared();
  962. #endif // !PROTOBUF_FUTURE_BREAKING_CHANGES
  963. // Removes the element referenced by position.
  964. //
  965. // Returns an iterator to the element immediately following the removed
  966. // element.
  967. //
  968. // Invalidates all iterators at or after the removed element, including end().
  969. iterator erase(const_iterator position);
  970. // Removes the elements in the range [first, last).
  971. //
  972. // Returns an iterator to the element immediately following the removed range.
  973. //
  974. // Invalidates all iterators at or after the removed range, including end().
  975. iterator erase(const_iterator first, const_iterator last);
  976. // Gets the arena on which this RepeatedPtrField stores its elements.
  977. inline Arena* GetArena() const;
  978. // For internal use only.
  979. //
  980. // This is public due to it being called by generated code.
  981. void InternalSwap(RepeatedPtrField* other) {
  982. internal::RepeatedPtrFieldBase::InternalSwap(other);
  983. }
  984. private:
  985. // Note: RepeatedPtrField SHOULD NOT be subclassed by users.
  986. class TypeHandler;
  987. // Internal version of GetArena().
  988. inline Arena* GetOwningArena() const;
  989. // Implementations for ExtractSubrange(). The copying behavior must be
  990. // included only if the type supports the necessary operations (e.g.,
  991. // MergeFrom()), so we must resolve this at compile time. ExtractSubrange()
  992. // uses SFINAE to choose one of the below implementations.
  993. void ExtractSubrangeInternal(int start, int num, Element** elements,
  994. std::true_type);
  995. void ExtractSubrangeInternal(int start, int num, Element** elements,
  996. std::false_type);
  997. friend class Arena;
  998. template <typename T>
  999. friend struct WeakRepeatedPtrField;
  1000. typedef void InternalArenaConstructable_;
  1001. };
  1002. // -------------------------------------------------------------------
  1003. template <typename Element>
  1004. class RepeatedPtrField<Element>::TypeHandler
  1005. : public internal::GenericTypeHandler<Element> {};
  1006. template <>
  1007. class RepeatedPtrField<std::string>::TypeHandler
  1008. : public internal::StringTypeHandler {};
  1009. template <typename Element>
  1010. constexpr RepeatedPtrField<Element>::RepeatedPtrField()
  1011. : RepeatedPtrFieldBase() {}
  1012. template <typename Element>
  1013. inline RepeatedPtrField<Element>::RepeatedPtrField(Arena* arena)
  1014. : RepeatedPtrFieldBase(arena) {}
  1015. template <typename Element>
  1016. inline RepeatedPtrField<Element>::RepeatedPtrField(
  1017. const RepeatedPtrField& other)
  1018. : RepeatedPtrFieldBase() {
  1019. MergeFrom(other);
  1020. }
  1021. template <typename Element>
  1022. template <typename Iter, typename>
  1023. inline RepeatedPtrField<Element>::RepeatedPtrField(Iter begin, Iter end) {
  1024. Add(begin, end);
  1025. }
  1026. template <typename Element>
  1027. RepeatedPtrField<Element>::~RepeatedPtrField() {
  1028. #ifdef __cpp_if_constexpr
  1029. if constexpr (std::is_base_of<MessageLite, Element>::value) {
  1030. #else
  1031. if (std::is_base_of<MessageLite, Element>::value) {
  1032. #endif
  1033. if (NeedsDestroy()) DestroyProtos();
  1034. } else {
  1035. Destroy<TypeHandler>();
  1036. }
  1037. }
  1038. template <typename Element>
  1039. inline RepeatedPtrField<Element>& RepeatedPtrField<Element>::operator=(
  1040. const RepeatedPtrField& other) {
  1041. if (this != &other) CopyFrom(other);
  1042. return *this;
  1043. }
  1044. template <typename Element>
  1045. inline RepeatedPtrField<Element>::RepeatedPtrField(
  1046. RepeatedPtrField&& other) noexcept
  1047. : RepeatedPtrField() {
  1048. #ifdef PROTOBUF_FORCE_COPY_IN_MOVE
  1049. CopyFrom(other);
  1050. #else // PROTOBUF_FORCE_COPY_IN_MOVE
  1051. // We don't just call Swap(&other) here because it would perform 3 copies if
  1052. // other is on an arena. This field can't be on an arena because arena
  1053. // construction always uses the Arena* accepting constructor.
  1054. if (other.GetOwningArena()) {
  1055. CopyFrom(other);
  1056. } else {
  1057. InternalSwap(&other);
  1058. }
  1059. #endif // !PROTOBUF_FORCE_COPY_IN_MOVE
  1060. }
  1061. template <typename Element>
  1062. inline RepeatedPtrField<Element>& RepeatedPtrField<Element>::operator=(
  1063. RepeatedPtrField&& other) noexcept {
  1064. // We don't just call Swap(&other) here because it would perform 3 copies if
  1065. // the two fields are on different arenas.
  1066. if (this != &other) {
  1067. if (GetOwningArena() != other.GetOwningArena()
  1068. #ifdef PROTOBUF_FORCE_COPY_IN_MOVE
  1069. || GetOwningArena() == nullptr
  1070. #endif // !PROTOBUF_FORCE_COPY_IN_MOVE
  1071. ) {
  1072. CopyFrom(other);
  1073. } else {
  1074. InternalSwap(&other);
  1075. }
  1076. }
  1077. return *this;
  1078. }
  1079. template <typename Element>
  1080. inline bool RepeatedPtrField<Element>::empty() const {
  1081. return RepeatedPtrFieldBase::empty();
  1082. }
  1083. template <typename Element>
  1084. inline int RepeatedPtrField<Element>::size() const {
  1085. return RepeatedPtrFieldBase::size();
  1086. }
  1087. template <typename Element>
  1088. inline const Element& RepeatedPtrField<Element>::Get(int index) const {
  1089. return RepeatedPtrFieldBase::Get<TypeHandler>(index);
  1090. }
  1091. template <typename Element>
  1092. inline const Element& RepeatedPtrField<Element>::at(int index) const {
  1093. return RepeatedPtrFieldBase::at<TypeHandler>(index);
  1094. }
  1095. template <typename Element>
  1096. inline Element& RepeatedPtrField<Element>::at(int index) {
  1097. return RepeatedPtrFieldBase::at<TypeHandler>(index);
  1098. }
  1099. template <typename Element>
  1100. inline Element* RepeatedPtrField<Element>::Mutable(int index) {
  1101. return RepeatedPtrFieldBase::Mutable<TypeHandler>(index);
  1102. }
  1103. template <typename Element>
  1104. inline Element* RepeatedPtrField<Element>::Add() {
  1105. return RepeatedPtrFieldBase::Add<TypeHandler>();
  1106. }
  1107. template <typename Element>
  1108. inline void RepeatedPtrField<Element>::Add(Element&& value) {
  1109. RepeatedPtrFieldBase::Add<TypeHandler>(std::move(value));
  1110. }
  1111. template <typename Element>
  1112. template <typename Iter>
  1113. inline void RepeatedPtrField<Element>::Add(Iter begin, Iter end) {
  1114. if (std::is_base_of<
  1115. std::forward_iterator_tag,
  1116. typename std::iterator_traits<Iter>::iterator_category>::value) {
  1117. int reserve = std::distance(begin, end);
  1118. Reserve(size() + reserve);
  1119. }
  1120. for (; begin != end; ++begin) {
  1121. *Add() = *begin;
  1122. }
  1123. }
  1124. template <typename Element>
  1125. inline void RepeatedPtrField<Element>::RemoveLast() {
  1126. RepeatedPtrFieldBase::RemoveLast<TypeHandler>();
  1127. }
  1128. template <typename Element>
  1129. inline void RepeatedPtrField<Element>::DeleteSubrange(int start, int num) {
  1130. GOOGLE_DCHECK_GE(start, 0);
  1131. GOOGLE_DCHECK_GE(num, 0);
  1132. GOOGLE_DCHECK_LE(start + num, size());
  1133. for (int i = 0; i < num; ++i) {
  1134. RepeatedPtrFieldBase::Delete<TypeHandler>(start + i);
  1135. }
  1136. UnsafeArenaExtractSubrange(start, num, nullptr);
  1137. }
  1138. template <typename Element>
  1139. inline void RepeatedPtrField<Element>::ExtractSubrange(int start, int num,
  1140. Element** elements) {
  1141. typename internal::TypeImplementsMergeBehavior<
  1142. typename TypeHandler::Type>::type t;
  1143. ExtractSubrangeInternal(start, num, elements, t);
  1144. }
  1145. // ExtractSubrange() implementation for types that implement merge/copy
  1146. // behavior.
  1147. template <typename Element>
  1148. inline void RepeatedPtrField<Element>::ExtractSubrangeInternal(
  1149. int start, int num, Element** elements, std::true_type) {
  1150. GOOGLE_DCHECK_GE(start, 0);
  1151. GOOGLE_DCHECK_GE(num, 0);
  1152. GOOGLE_DCHECK_LE(start + num, size());
  1153. if (num == 0) return;
  1154. GOOGLE_DCHECK_NE(elements, nullptr)
  1155. << "Releasing elements without transferring ownership is an unsafe "
  1156. "operation. Use UnsafeArenaExtractSubrange.";
  1157. if (elements == nullptr) {
  1158. CloseGap(start, num);
  1159. return;
  1160. }
  1161. Arena* arena = GetOwningArena();
  1162. #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE
  1163. // Always copy.
  1164. for (int i = 0; i < num; ++i) {
  1165. elements[i] = copy<TypeHandler>(
  1166. RepeatedPtrFieldBase::Mutable<TypeHandler>(i + start));
  1167. }
  1168. if (arena == nullptr) {
  1169. for (int i = 0; i < num; ++i) {
  1170. delete RepeatedPtrFieldBase::Mutable<TypeHandler>(i + start);
  1171. }
  1172. }
  1173. #else // PROTOBUF_FORCE_COPY_IN_RELEASE
  1174. // If we're on an arena, we perform a copy for each element so that the
  1175. // returned elements are heap-allocated. Otherwise, just forward it.
  1176. if (arena != nullptr) {
  1177. for (int i = 0; i < num; ++i) {
  1178. elements[i] = copy<TypeHandler>(
  1179. RepeatedPtrFieldBase::Mutable<TypeHandler>(i + start));
  1180. }
  1181. } else {
  1182. for (int i = 0; i < num; ++i) {
  1183. elements[i] = RepeatedPtrFieldBase::Mutable<TypeHandler>(i + start);
  1184. }
  1185. }
  1186. #endif // !PROTOBUF_FORCE_COPY_IN_RELEASE
  1187. CloseGap(start, num);
  1188. }
  1189. // ExtractSubrange() implementation for types that do not implement merge/copy
  1190. // behavior.
  1191. template <typename Element>
  1192. inline void RepeatedPtrField<Element>::ExtractSubrangeInternal(
  1193. int start, int num, Element** elements, std::false_type) {
  1194. // This case is identical to UnsafeArenaExtractSubrange(). However, since
  1195. // ExtractSubrange() must return heap-allocated objects by contract, and we
  1196. // cannot fulfill this contract if we are an on arena, we must GOOGLE_DCHECK() that
  1197. // we are not on an arena.
  1198. GOOGLE_DCHECK(GetOwningArena() == nullptr)
  1199. << "ExtractSubrange() when arena is non-nullptr is only supported when "
  1200. << "the Element type supplies a MergeFrom() operation to make copies.";
  1201. UnsafeArenaExtractSubrange(start, num, elements);
  1202. }
  1203. template <typename Element>
  1204. inline void RepeatedPtrField<Element>::UnsafeArenaExtractSubrange(
  1205. int start, int num, Element** elements) {
  1206. GOOGLE_DCHECK_GE(start, 0);
  1207. GOOGLE_DCHECK_GE(num, 0);
  1208. GOOGLE_DCHECK_LE(start + num, size());
  1209. if (num > 0) {
  1210. // Save the values of the removed elements if requested.
  1211. if (elements != nullptr) {
  1212. for (int i = 0; i < num; ++i) {
  1213. elements[i] = RepeatedPtrFieldBase::Mutable<TypeHandler>(i + start);
  1214. }
  1215. }
  1216. CloseGap(start, num);
  1217. }
  1218. }
  1219. template <typename Element>
  1220. inline void RepeatedPtrField<Element>::Clear() {
  1221. RepeatedPtrFieldBase::Clear<TypeHandler>();
  1222. }
  1223. template <typename Element>
  1224. inline void RepeatedPtrField<Element>::MergeFrom(
  1225. const RepeatedPtrField& other) {
  1226. RepeatedPtrFieldBase::MergeFrom<TypeHandler>(other);
  1227. }
  1228. template <typename Element>
  1229. inline void RepeatedPtrField<Element>::CopyFrom(const RepeatedPtrField& other) {
  1230. RepeatedPtrFieldBase::CopyFrom<TypeHandler>(other);
  1231. }
  1232. template <typename Element>
  1233. template <typename Iter>
  1234. inline void RepeatedPtrField<Element>::Assign(Iter begin, Iter end) {
  1235. Clear();
  1236. Add(begin, end);
  1237. }
  1238. template <typename Element>
  1239. inline typename RepeatedPtrField<Element>::iterator
  1240. RepeatedPtrField<Element>::erase(const_iterator position) {
  1241. return erase(position, position + 1);
  1242. }
  1243. template <typename Element>
  1244. inline typename RepeatedPtrField<Element>::iterator
  1245. RepeatedPtrField<Element>::erase(const_iterator first, const_iterator last) {
  1246. size_type pos_offset = std::distance(cbegin(), first);
  1247. size_type last_offset = std::distance(cbegin(), last);
  1248. DeleteSubrange(pos_offset, last_offset - pos_offset);
  1249. return begin() + pos_offset;
  1250. }
  1251. template <typename Element>
  1252. inline Element** RepeatedPtrField<Element>::mutable_data() {
  1253. return RepeatedPtrFieldBase::mutable_data<TypeHandler>();
  1254. }
  1255. template <typename Element>
  1256. inline const Element* const* RepeatedPtrField<Element>::data() const {
  1257. return RepeatedPtrFieldBase::data<TypeHandler>();
  1258. }
  1259. template <typename Element>
  1260. inline void RepeatedPtrField<Element>::Swap(RepeatedPtrField* other) {
  1261. if (this == other) return;
  1262. RepeatedPtrFieldBase::Swap<TypeHandler>(other);
  1263. }
  1264. template <typename Element>
  1265. inline void RepeatedPtrField<Element>::UnsafeArenaSwap(
  1266. RepeatedPtrField* other) {
  1267. if (this == other) return;
  1268. GOOGLE_DCHECK_EQ(GetOwningArena(), other->GetOwningArena());
  1269. RepeatedPtrFieldBase::InternalSwap(other);
  1270. }
  1271. template <typename Element>
  1272. inline void RepeatedPtrField<Element>::SwapElements(int index1, int index2) {
  1273. RepeatedPtrFieldBase::SwapElements(index1, index2);
  1274. }
  1275. template <typename Element>
  1276. inline Arena* RepeatedPtrField<Element>::GetArena() const {
  1277. return RepeatedPtrFieldBase::GetArena();
  1278. }
  1279. template <typename Element>
  1280. inline Arena* RepeatedPtrField<Element>::GetOwningArena() const {
  1281. return RepeatedPtrFieldBase::GetOwningArena();
  1282. }
  1283. template <typename Element>
  1284. inline size_t RepeatedPtrField<Element>::SpaceUsedExcludingSelfLong() const {
  1285. return RepeatedPtrFieldBase::SpaceUsedExcludingSelfLong<TypeHandler>();
  1286. }
  1287. template <typename Element>
  1288. inline void RepeatedPtrField<Element>::AddAllocated(Element* value) {
  1289. RepeatedPtrFieldBase::AddAllocated<TypeHandler>(value);
  1290. }
  1291. template <typename Element>
  1292. inline void RepeatedPtrField<Element>::UnsafeArenaAddAllocated(Element* value) {
  1293. RepeatedPtrFieldBase::UnsafeArenaAddAllocated<TypeHandler>(value);
  1294. }
  1295. template <typename Element>
  1296. inline Element* RepeatedPtrField<Element>::ReleaseLast() {
  1297. return RepeatedPtrFieldBase::ReleaseLast<TypeHandler>();
  1298. }
  1299. template <typename Element>
  1300. inline Element* RepeatedPtrField<Element>::UnsafeArenaReleaseLast() {
  1301. return RepeatedPtrFieldBase::UnsafeArenaReleaseLast<TypeHandler>();
  1302. }
  1303. template <typename Element>
  1304. inline int RepeatedPtrField<Element>::ClearedCount() const {
  1305. return RepeatedPtrFieldBase::ClearedCount();
  1306. }
  1307. #ifndef PROTOBUF_FUTURE_BREAKING_CHANGES
  1308. template <typename Element>
  1309. inline void RepeatedPtrField<Element>::AddCleared(Element* value) {
  1310. return RepeatedPtrFieldBase::AddCleared<TypeHandler>(value);
  1311. }
  1312. template <typename Element>
  1313. inline Element* RepeatedPtrField<Element>::ReleaseCleared() {
  1314. return RepeatedPtrFieldBase::ReleaseCleared<TypeHandler>();
  1315. }
  1316. #endif // !PROTOBUF_FUTURE_BREAKING_CHANGES
  1317. template <typename Element>
  1318. inline void RepeatedPtrField<Element>::Reserve(int new_size) {
  1319. return RepeatedPtrFieldBase::Reserve(new_size);
  1320. }
  1321. template <typename Element>
  1322. inline int RepeatedPtrField<Element>::Capacity() const {
  1323. return RepeatedPtrFieldBase::Capacity();
  1324. }
  1325. // -------------------------------------------------------------------
  1326. namespace internal {
  1327. // STL-like iterator implementation for RepeatedPtrField. You should not
  1328. // refer to this class directly; use RepeatedPtrField<T>::iterator instead.
  1329. //
  1330. // The iterator for RepeatedPtrField<T>, RepeatedPtrIterator<T>, is
  1331. // very similar to iterator_ptr<T**> in util/gtl/iterator_adaptors.h,
  1332. // but adds random-access operators and is modified to wrap a void** base
  1333. // iterator (since RepeatedPtrField stores its array as a void* array and
  1334. // casting void** to T** would violate C++ aliasing rules).
  1335. //
  1336. // This code based on net/proto/proto-array-internal.h by Jeffrey Yasskin
  1337. // (jyasskin@google.com).
  1338. template <typename Element>
  1339. class RepeatedPtrIterator {
  1340. public:
  1341. using iterator = RepeatedPtrIterator<Element>;
  1342. using iterator_category = std::random_access_iterator_tag;
  1343. using value_type = typename std::remove_const<Element>::type;
  1344. using difference_type = std::ptrdiff_t;
  1345. using pointer = Element*;
  1346. using reference = Element&;
  1347. RepeatedPtrIterator() : it_(nullptr) {}
  1348. explicit RepeatedPtrIterator(void* const* it) : it_(it) {}
  1349. // Allows "upcasting" from RepeatedPtrIterator<T**> to
  1350. // RepeatedPtrIterator<const T*const*>.
  1351. template <typename OtherElement,
  1352. typename std::enable_if<std::is_convertible<
  1353. OtherElement*, pointer>::value>::type* = nullptr>
  1354. RepeatedPtrIterator(const RepeatedPtrIterator<OtherElement>& other)
  1355. : it_(other.it_) {}
  1356. // dereferenceable
  1357. reference operator*() const { return *reinterpret_cast<Element*>(*it_); }
  1358. pointer operator->() const { return &(operator*()); }
  1359. // {inc,dec}rementable
  1360. iterator& operator++() {
  1361. ++it_;
  1362. return *this;
  1363. }
  1364. iterator operator++(int) { return iterator(it_++); }
  1365. iterator& operator--() {
  1366. --it_;
  1367. return *this;
  1368. }
  1369. iterator operator--(int) { return iterator(it_--); }
  1370. // equality_comparable
  1371. friend bool operator==(const iterator& x, const iterator& y) {
  1372. return x.it_ == y.it_;
  1373. }
  1374. friend bool operator!=(const iterator& x, const iterator& y) {
  1375. return x.it_ != y.it_;
  1376. }
  1377. // less_than_comparable
  1378. friend bool operator<(const iterator& x, const iterator& y) {
  1379. return x.it_ < y.it_;
  1380. }
  1381. friend bool operator<=(const iterator& x, const iterator& y) {
  1382. return x.it_ <= y.it_;
  1383. }
  1384. friend bool operator>(const iterator& x, const iterator& y) {
  1385. return x.it_ > y.it_;
  1386. }
  1387. friend bool operator>=(const iterator& x, const iterator& y) {
  1388. return x.it_ >= y.it_;
  1389. }
  1390. // addable, subtractable
  1391. iterator& operator+=(difference_type d) {
  1392. it_ += d;
  1393. return *this;
  1394. }
  1395. friend iterator operator+(iterator it, const difference_type d) {
  1396. it += d;
  1397. return it;
  1398. }
  1399. friend iterator operator+(const difference_type d, iterator it) {
  1400. it += d;
  1401. return it;
  1402. }
  1403. iterator& operator-=(difference_type d) {
  1404. it_ -= d;
  1405. return *this;
  1406. }
  1407. friend iterator operator-(iterator it, difference_type d) {
  1408. it -= d;
  1409. return it;
  1410. }
  1411. // indexable
  1412. reference operator[](difference_type d) const { return *(*this + d); }
  1413. // random access iterator
  1414. friend difference_type operator-(iterator it1, iterator it2) {
  1415. return it1.it_ - it2.it_;
  1416. }
  1417. private:
  1418. template <typename OtherElement>
  1419. friend class RepeatedPtrIterator;
  1420. // The internal iterator.
  1421. void* const* it_;
  1422. };
  1423. // Provides an iterator that operates on pointers to the underlying objects
  1424. // rather than the objects themselves as RepeatedPtrIterator does.
  1425. // Consider using this when working with stl algorithms that change
  1426. // the array.
  1427. // The VoidPtr template parameter holds the type-agnostic pointer value
  1428. // referenced by the iterator. It should either be "void *" for a mutable
  1429. // iterator, or "const void* const" for a constant iterator.
  1430. template <typename Element, typename VoidPtr>
  1431. class RepeatedPtrOverPtrsIterator {
  1432. public:
  1433. using iterator = RepeatedPtrOverPtrsIterator<Element, VoidPtr>;
  1434. using iterator_category = std::random_access_iterator_tag;
  1435. using value_type = typename std::remove_const<Element>::type;
  1436. using difference_type = std::ptrdiff_t;
  1437. using pointer = Element*;
  1438. using reference = Element&;
  1439. RepeatedPtrOverPtrsIterator() : it_(nullptr) {}
  1440. explicit RepeatedPtrOverPtrsIterator(VoidPtr* it) : it_(it) {}
  1441. // Allows "upcasting" from RepeatedPtrOverPtrsIterator<T**> to
  1442. // RepeatedPtrOverPtrsIterator<const T*const*>.
  1443. template <
  1444. typename OtherElement, typename OtherVoidPtr,
  1445. typename std::enable_if<
  1446. std::is_convertible<OtherElement*, pointer>::value &&
  1447. std::is_convertible<OtherVoidPtr*, VoidPtr>::value>::type* = nullptr>
  1448. RepeatedPtrOverPtrsIterator(
  1449. const RepeatedPtrOverPtrsIterator<OtherElement, OtherVoidPtr>& other)
  1450. : it_(other.it_) {}
  1451. // dereferenceable
  1452. reference operator*() const { return *reinterpret_cast<Element*>(it_); }
  1453. pointer operator->() const { return &(operator*()); }
  1454. // {inc,dec}rementable
  1455. iterator& operator++() {
  1456. ++it_;
  1457. return *this;
  1458. }
  1459. iterator operator++(int) { return iterator(it_++); }
  1460. iterator& operator--() {
  1461. --it_;
  1462. return *this;
  1463. }
  1464. iterator operator--(int) { return iterator(it_--); }
  1465. // equality_comparable
  1466. friend bool operator==(const iterator& x, const iterator& y) {
  1467. return x.it_ == y.it_;
  1468. }
  1469. friend bool operator!=(const iterator& x, const iterator& y) {
  1470. return x.it_ != y.it_;
  1471. }
  1472. // less_than_comparable
  1473. friend bool operator<(const iterator& x, const iterator& y) {
  1474. return x.it_ < y.it_;
  1475. }
  1476. friend bool operator<=(const iterator& x, const iterator& y) {
  1477. return x.it_ <= y.it_;
  1478. }
  1479. friend bool operator>(const iterator& x, const iterator& y) {
  1480. return x.it_ > y.it_;
  1481. }
  1482. friend bool operator>=(const iterator& x, const iterator& y) {
  1483. return x.it_ >= y.it_;
  1484. }
  1485. // addable, subtractable
  1486. iterator& operator+=(difference_type d) {
  1487. it_ += d;
  1488. return *this;
  1489. }
  1490. friend iterator operator+(iterator it, difference_type d) {
  1491. it += d;
  1492. return it;
  1493. }
  1494. friend iterator operator+(difference_type d, iterator it) {
  1495. it += d;
  1496. return it;
  1497. }
  1498. iterator& operator-=(difference_type d) {
  1499. it_ -= d;
  1500. return *this;
  1501. }
  1502. friend iterator operator-(iterator it, difference_type d) {
  1503. it -= d;
  1504. return it;
  1505. }
  1506. // indexable
  1507. reference operator[](difference_type d) const { return *(*this + d); }
  1508. // random access iterator
  1509. friend difference_type operator-(iterator it1, iterator it2) {
  1510. return it1.it_ - it2.it_;
  1511. }
  1512. private:
  1513. template <typename OtherElement, typename OtherVoidPtr>
  1514. friend class RepeatedPtrOverPtrsIterator;
  1515. // The internal iterator.
  1516. VoidPtr* it_;
  1517. };
  1518. } // namespace internal
  1519. template <typename Element>
  1520. inline typename RepeatedPtrField<Element>::iterator
  1521. RepeatedPtrField<Element>::begin() {
  1522. return iterator(raw_data());
  1523. }
  1524. template <typename Element>
  1525. inline typename RepeatedPtrField<Element>::const_iterator
  1526. RepeatedPtrField<Element>::begin() const {
  1527. return iterator(raw_data());
  1528. }
  1529. template <typename Element>
  1530. inline typename RepeatedPtrField<Element>::const_iterator
  1531. RepeatedPtrField<Element>::cbegin() const {
  1532. return begin();
  1533. }
  1534. template <typename Element>
  1535. inline typename RepeatedPtrField<Element>::iterator
  1536. RepeatedPtrField<Element>::end() {
  1537. return iterator(raw_data() + size());
  1538. }
  1539. template <typename Element>
  1540. inline typename RepeatedPtrField<Element>::const_iterator
  1541. RepeatedPtrField<Element>::end() const {
  1542. return iterator(raw_data() + size());
  1543. }
  1544. template <typename Element>
  1545. inline typename RepeatedPtrField<Element>::const_iterator
  1546. RepeatedPtrField<Element>::cend() const {
  1547. return end();
  1548. }
  1549. template <typename Element>
  1550. inline typename RepeatedPtrField<Element>::pointer_iterator
  1551. RepeatedPtrField<Element>::pointer_begin() {
  1552. return pointer_iterator(raw_mutable_data());
  1553. }
  1554. template <typename Element>
  1555. inline typename RepeatedPtrField<Element>::const_pointer_iterator
  1556. RepeatedPtrField<Element>::pointer_begin() const {
  1557. return const_pointer_iterator(const_cast<const void* const*>(raw_data()));
  1558. }
  1559. template <typename Element>
  1560. inline typename RepeatedPtrField<Element>::pointer_iterator
  1561. RepeatedPtrField<Element>::pointer_end() {
  1562. return pointer_iterator(raw_mutable_data() + size());
  1563. }
  1564. template <typename Element>
  1565. inline typename RepeatedPtrField<Element>::const_pointer_iterator
  1566. RepeatedPtrField<Element>::pointer_end() const {
  1567. return const_pointer_iterator(
  1568. const_cast<const void* const*>(raw_data() + size()));
  1569. }
  1570. // Iterators and helper functions that follow the spirit of the STL
  1571. // std::back_insert_iterator and std::back_inserter but are tailor-made
  1572. // for RepeatedField and RepeatedPtrField. Typical usage would be:
  1573. //
  1574. // std::copy(some_sequence.begin(), some_sequence.end(),
  1575. // RepeatedFieldBackInserter(proto.mutable_sequence()));
  1576. //
  1577. // Ported by johannes from util/gtl/proto-array-iterators.h
  1578. namespace internal {
  1579. // A back inserter for RepeatedPtrField objects.
  1580. template <typename T>
  1581. class RepeatedPtrFieldBackInsertIterator {
  1582. public:
  1583. using iterator_category = std::output_iterator_tag;
  1584. using value_type = T;
  1585. using pointer = void;
  1586. using reference = void;
  1587. using difference_type = std::ptrdiff_t;
  1588. RepeatedPtrFieldBackInsertIterator(RepeatedPtrField<T>* const mutable_field)
  1589. : field_(mutable_field) {}
  1590. RepeatedPtrFieldBackInsertIterator<T>& operator=(const T& value) {
  1591. *field_->Add() = value;
  1592. return *this;
  1593. }
  1594. RepeatedPtrFieldBackInsertIterator<T>& operator=(
  1595. const T* const ptr_to_value) {
  1596. *field_->Add() = *ptr_to_value;
  1597. return *this;
  1598. }
  1599. RepeatedPtrFieldBackInsertIterator<T>& operator=(T&& value) {
  1600. *field_->Add() = std::move(value);
  1601. return *this;
  1602. }
  1603. RepeatedPtrFieldBackInsertIterator<T>& operator*() { return *this; }
  1604. RepeatedPtrFieldBackInsertIterator<T>& operator++() { return *this; }
  1605. RepeatedPtrFieldBackInsertIterator<T>& operator++(int /* unused */) {
  1606. return *this;
  1607. }
  1608. private:
  1609. RepeatedPtrField<T>* field_;
  1610. };
  1611. // A back inserter for RepeatedPtrFields that inserts by transferring ownership
  1612. // of a pointer.
  1613. template <typename T>
  1614. class AllocatedRepeatedPtrFieldBackInsertIterator {
  1615. public:
  1616. using iterator_category = std::output_iterator_tag;
  1617. using value_type = T;
  1618. using pointer = void;
  1619. using reference = void;
  1620. using difference_type = std::ptrdiff_t;
  1621. explicit AllocatedRepeatedPtrFieldBackInsertIterator(
  1622. RepeatedPtrField<T>* const mutable_field)
  1623. : field_(mutable_field) {}
  1624. AllocatedRepeatedPtrFieldBackInsertIterator<T>& operator=(
  1625. T* const ptr_to_value) {
  1626. field_->AddAllocated(ptr_to_value);
  1627. return *this;
  1628. }
  1629. AllocatedRepeatedPtrFieldBackInsertIterator<T>& operator*() { return *this; }
  1630. AllocatedRepeatedPtrFieldBackInsertIterator<T>& operator++() { return *this; }
  1631. AllocatedRepeatedPtrFieldBackInsertIterator<T>& operator++(int /* unused */) {
  1632. return *this;
  1633. }
  1634. private:
  1635. RepeatedPtrField<T>* field_;
  1636. };
  1637. // Almost identical to AllocatedRepeatedPtrFieldBackInsertIterator. This one
  1638. // uses the UnsafeArenaAddAllocated instead.
  1639. template <typename T>
  1640. class UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator {
  1641. public:
  1642. using iterator_category = std::output_iterator_tag;
  1643. using value_type = T;
  1644. using pointer = void;
  1645. using reference = void;
  1646. using difference_type = std::ptrdiff_t;
  1647. explicit UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator(
  1648. RepeatedPtrField<T>* const mutable_field)
  1649. : field_(mutable_field) {}
  1650. UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>& operator=(
  1651. T const* const ptr_to_value) {
  1652. field_->UnsafeArenaAddAllocated(const_cast<T*>(ptr_to_value));
  1653. return *this;
  1654. }
  1655. UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>& operator*() {
  1656. return *this;
  1657. }
  1658. UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>& operator++() {
  1659. return *this;
  1660. }
  1661. UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>& operator++(
  1662. int /* unused */) {
  1663. return *this;
  1664. }
  1665. private:
  1666. RepeatedPtrField<T>* field_;
  1667. };
  1668. } // namespace internal
  1669. // Provides a back insert iterator for RepeatedPtrField instances,
  1670. // similar to std::back_inserter().
  1671. template <typename T>
  1672. internal::RepeatedPtrFieldBackInsertIterator<T> RepeatedPtrFieldBackInserter(
  1673. RepeatedPtrField<T>* const mutable_field) {
  1674. return internal::RepeatedPtrFieldBackInsertIterator<T>(mutable_field);
  1675. }
  1676. // Special back insert iterator for RepeatedPtrField instances, just in
  1677. // case someone wants to write generic template code that can access both
  1678. // RepeatedFields and RepeatedPtrFields using a common name.
  1679. template <typename T>
  1680. internal::RepeatedPtrFieldBackInsertIterator<T> RepeatedFieldBackInserter(
  1681. RepeatedPtrField<T>* const mutable_field) {
  1682. return internal::RepeatedPtrFieldBackInsertIterator<T>(mutable_field);
  1683. }
  1684. // Provides a back insert iterator for RepeatedPtrField instances
  1685. // similar to std::back_inserter() which transfers the ownership while
  1686. // copying elements.
  1687. template <typename T>
  1688. internal::AllocatedRepeatedPtrFieldBackInsertIterator<T>
  1689. AllocatedRepeatedPtrFieldBackInserter(
  1690. RepeatedPtrField<T>* const mutable_field) {
  1691. return internal::AllocatedRepeatedPtrFieldBackInsertIterator<T>(
  1692. mutable_field);
  1693. }
  1694. // Similar to AllocatedRepeatedPtrFieldBackInserter, using
  1695. // UnsafeArenaAddAllocated instead of AddAllocated.
  1696. // This is slightly faster if that matters. It is also useful in legacy code
  1697. // that uses temporary ownership to avoid copies. Example:
  1698. // RepeatedPtrField<T> temp_field;
  1699. // temp_field.UnsafeArenaAddAllocated(new T);
  1700. // ... // Do something with temp_field
  1701. // temp_field.UnsafeArenaExtractSubrange(0, temp_field.size(), nullptr);
  1702. // Putting temp_field on the arena fails because the ownership transfers to the
  1703. // arena at the "AddAllocated" call and is not released anymore causing a
  1704. // double delete. This function uses UnsafeArenaAddAllocated to prevent this.
  1705. template <typename T>
  1706. internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>
  1707. UnsafeArenaAllocatedRepeatedPtrFieldBackInserter(
  1708. RepeatedPtrField<T>* const mutable_field) {
  1709. return internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>(
  1710. mutable_field);
  1711. }
  1712. extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE
  1713. RepeatedPtrField<std::string>;
  1714. } // namespace protobuf
  1715. } // namespace google
  1716. #include <google/protobuf/port_undef.inc>
  1717. #endif // GOOGLE_PROTOBUF_REPEATED_PTR_FIELD_H__