GPBMessage.m 154 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. //
  4. // Use of this source code is governed by a BSD-style
  5. // license that can be found in the LICENSE file or at
  6. // https://developers.google.com/open-source/licenses/bsd
  7. #import "GPBMessage.h"
  8. #import "GPBMessage_PackagePrivate.h"
  9. #import <Foundation/Foundation.h>
  10. #import <objc/message.h>
  11. #import <objc/runtime.h>
  12. #import <os/lock.h>
  13. #import <stdatomic.h>
  14. #import "GPBArray.h"
  15. #import "GPBArray_PackagePrivate.h"
  16. #import "GPBCodedInputStream.h"
  17. #import "GPBCodedInputStream_PackagePrivate.h"
  18. #import "GPBCodedOutputStream.h"
  19. #import "GPBCodedOutputStream_PackagePrivate.h"
  20. #import "GPBDescriptor.h"
  21. #import "GPBDescriptor_PackagePrivate.h"
  22. #import "GPBDictionary.h"
  23. #import "GPBDictionary_PackagePrivate.h"
  24. #import "GPBExtensionInternals.h"
  25. #import "GPBExtensionRegistry.h"
  26. #import "GPBRootObject.h"
  27. #import "GPBRootObject_PackagePrivate.h"
  28. #import "GPBUnknownField.h"
  29. #import "GPBUnknownFieldSet.h"
  30. #import "GPBUnknownFieldSet_PackagePrivate.h"
  31. #import "GPBUnknownFields.h"
  32. #import "GPBUnknownFields_PackagePrivate.h"
  33. #import "GPBUtilities.h"
  34. #import "GPBUtilities_PackagePrivate.h"
  35. // TODO: Consider using on other functions to reduce bloat when
  36. // some compiler optimizations are enabled.
  37. #define GPB_NOINLINE __attribute__((noinline))
  38. // Returns a new instance that was automatically created by |autocreator| for
  39. // its field |field|.
  40. static GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, GPBMessage *autocreator,
  41. GPBFieldDescriptor *field)
  42. __attribute__((ns_returns_retained));
  43. // Direct access is use for speed, to avoid even internally declaring things
  44. // read/write, etc. The warning is enabled in the project to ensure code calling
  45. // protos can turn on -Wdirect-ivar-access without issues.
  46. #pragma clang diagnostic push
  47. #pragma clang diagnostic ignored "-Wdirect-ivar-access"
  48. NSString *const GPBMessageErrorDomain = GPBNSStringifySymbol(GPBMessageErrorDomain);
  49. NSString *const GPBErrorReasonKey = @"Reason";
  50. static NSString *const kGPBDataCoderKey = @"GPBData";
  51. // Length-delimited has a max size of 2GB, and thus messages do also.
  52. // src/google/protobuf/message_lite also does this enforcement on the C++ side. Validation for
  53. // parsing is done with GPBCodedInputStream; but for messages, it is less checks to do it within
  54. // the message side since the input stream code calls these same bottlenecks.
  55. // https://protobuf.dev/programming-guides/encoding/#cheat-sheet
  56. static const size_t kMaximumMessageSize = 0x7fffffff;
  57. NSString *const GPBMessageExceptionMessageTooLarge =
  58. GPBNSStringifySymbol(GPBMessageExceptionMessageTooLarge);
  59. //
  60. // PLEASE REMEMBER:
  61. //
  62. // This is the base class for *all* messages generated, so any selector defined,
  63. // *public* or *private* could end up colliding with a proto message field. So
  64. // avoid using selectors that could match a property, use C functions to hide
  65. // them, etc.
  66. //
  67. @interface GPBMessage () {
  68. @package
  69. // Only one of these two is ever set, GPBUnknownFieldSet is being deprecated and will
  70. // eventually be removed, but because that api support mutation, once the property is
  71. // fetch it must continue to be used so any mutations will be honored in future operations
  72. // on the message.
  73. // Read only operations that access these two/cause things to migration between them should
  74. // be protected with an @synchronized(self) block (that way the code also doesn't have to
  75. // worry about throws).
  76. NSMutableData *unknownFieldData_;
  77. #pragma clang diagnostic push
  78. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  79. GPBUnknownFieldSet *unknownFields_;
  80. #pragma clang diagnostic pop
  81. NSMutableDictionary *extensionMap_;
  82. // Readonly access to autocreatedExtensionMap_ is protected via readOnlyLock_.
  83. NSMutableDictionary *autocreatedExtensionMap_;
  84. // If the object was autocreated, we remember the creator so that if we get
  85. // mutated, we can inform the creator to make our field visible.
  86. GPBMessage *autocreator_;
  87. GPBFieldDescriptor *autocreatorField_;
  88. GPBExtensionDescriptor *autocreatorExtension_;
  89. // Messages can only be mutated from one thread. But some *readonly* operations modify internal
  90. // state because they autocreate things. The autocreatedExtensionMap_ is one such structure.
  91. // Access during readonly operations is protected via this lock.
  92. //
  93. // Long ago, this was an OSSpinLock, but then it came to light that there were issues for that on
  94. // iOS:
  95. // http://mjtsai.com/blog/2015/12/16/osspinlock-is-unsafe/
  96. // https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000372.html
  97. // It was changed to a dispatch_semaphore_t, but that has potential for priority inversion issues.
  98. // The minOS versions are now high enough that os_unfair_lock can be used, and should provide
  99. // all the support we need. For more information in the concurrency/locking space see:
  100. // https://gist.github.com/tclementdev/6af616354912b0347cdf6db159c37057
  101. // https://developer.apple.com/library/archive/documentation/Performance/Conceptual/EnergyGuide-iOS/PrioritizeWorkWithQoS.html
  102. // https://developer.apple.com/videos/play/wwdc2017/706/
  103. os_unfair_lock readOnlyLock_;
  104. }
  105. @end
  106. static id CreateArrayForField(GPBFieldDescriptor *field, GPBMessage *autocreator)
  107. __attribute__((ns_returns_retained));
  108. static id GetOrCreateArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
  109. static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
  110. static id CreateMapForField(GPBFieldDescriptor *field, GPBMessage *autocreator)
  111. __attribute__((ns_returns_retained));
  112. static id GetOrCreateMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
  113. static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
  114. static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, NSZone *zone)
  115. __attribute__((ns_returns_retained));
  116. #if defined(DEBUG) && DEBUG
  117. static NSError *MessageError(NSInteger code, NSDictionary *userInfo) {
  118. return [NSError errorWithDomain:GPBMessageErrorDomain code:code userInfo:userInfo];
  119. }
  120. #endif
  121. static NSError *ErrorFromException(NSException *exception) {
  122. NSError *error = nil;
  123. if ([exception.name isEqual:GPBCodedInputStreamException]) {
  124. NSDictionary *exceptionInfo = exception.userInfo;
  125. error = exceptionInfo[GPBCodedInputStreamUnderlyingErrorKey];
  126. }
  127. if (!error) {
  128. NSString *reason = exception.reason;
  129. NSDictionary *userInfo = nil;
  130. if ([reason length]) {
  131. userInfo = @{GPBErrorReasonKey : reason};
  132. }
  133. error = [NSError errorWithDomain:GPBMessageErrorDomain
  134. code:GPBMessageErrorCodeOther
  135. userInfo:userInfo];
  136. }
  137. return error;
  138. }
  139. // Helper to encode varints onto the mutable data, the max size need is 10 bytes.
  140. GPB_NOINLINE
  141. static uint8_t *EncodeVarintU64(uint64_t val, uint8_t *ptr) {
  142. do {
  143. uint8_t byte = val & 0x7fU;
  144. val >>= 7;
  145. if (val) byte |= 0x80U;
  146. *(ptr++) = byte;
  147. } while (val);
  148. return ptr;
  149. }
  150. // Helper to encode varints onto the mutable data, the max size need is 5 bytes.
  151. GPB_NOINLINE
  152. static uint8_t *EncodeVarintU32(uint32_t val, uint8_t *ptr) {
  153. do {
  154. uint8_t byte = val & 0x7fU;
  155. val >>= 7;
  156. if (val) byte |= 0x80U;
  157. *(ptr++) = byte;
  158. } while (val);
  159. return ptr;
  160. }
  161. // Helper to encode signed int32 values as varints onto the mutable data, the max size need is 10
  162. // bytes.
  163. GPB_NOINLINE
  164. static uint8_t *EncodeVarintS32(int32_t val, uint8_t *ptr) {
  165. if (val >= 0) {
  166. return EncodeVarintU32((uint32_t)val, ptr);
  167. } else {
  168. // Must sign-extend
  169. int64_t extended = val;
  170. return EncodeVarintU64((uint64_t)extended, ptr);
  171. }
  172. }
  173. GPB_NOINLINE
  174. static void AddUnknownFieldVarint32(GPBMessage *self, uint32_t fieldNumber, int32_t value) {
  175. if (self->unknownFields_) {
  176. [self->unknownFields_ mergeVarintField:fieldNumber value:value];
  177. return;
  178. }
  179. uint8_t buf[20];
  180. uint8_t *ptr = buf;
  181. ptr = EncodeVarintU32(GPBWireFormatMakeTag(fieldNumber, GPBWireFormatVarint), ptr);
  182. ptr = EncodeVarintS32(value, ptr);
  183. if (self->unknownFieldData_ == nil) {
  184. self->unknownFieldData_ = [[NSMutableData alloc] initWithCapacity:ptr - buf];
  185. GPBBecomeVisibleToAutocreator(self);
  186. }
  187. [self->unknownFieldData_ appendBytes:buf length:ptr - buf];
  188. }
  189. GPB_NOINLINE
  190. static void AddUnknownFieldLengthDelimited(GPBMessage *self, uint32_t fieldNumber, NSData *value) {
  191. if (self->unknownFields_) {
  192. [self->unknownFields_ mergeLengthDelimited:fieldNumber value:value];
  193. return;
  194. }
  195. uint8_t buf[20];
  196. uint8_t *ptr = buf;
  197. ptr = EncodeVarintU32(GPBWireFormatMakeTag(fieldNumber, GPBWireFormatLengthDelimited), ptr);
  198. ptr = EncodeVarintU64((uint64_t)value.length, ptr);
  199. if (self->unknownFieldData_ == nil) {
  200. self->unknownFieldData_ = [[NSMutableData alloc] initWithCapacity:(ptr - buf) + value.length];
  201. GPBBecomeVisibleToAutocreator(self);
  202. }
  203. [self->unknownFieldData_ appendBytes:buf length:ptr - buf];
  204. [self->unknownFieldData_ appendData:value];
  205. }
  206. GPB_NOINLINE
  207. static void AddUnknownMessageSetEntry(GPBMessage *self, uint32_t typeId, NSData *value) {
  208. if (self->unknownFields_) {
  209. // Legacy Set does this odd storage for MessageSet.
  210. [self->unknownFields_ mergeLengthDelimited:typeId value:value];
  211. return;
  212. }
  213. uint8_t buf[60];
  214. uint8_t *ptr = buf;
  215. ptr = EncodeVarintU32(GPBWireFormatMessageSetItemTag, ptr);
  216. ptr = EncodeVarintU32(GPBWireFormatMessageSetTypeIdTag, ptr);
  217. ptr = EncodeVarintU32(typeId, ptr);
  218. ptr = EncodeVarintU32(GPBWireFormatMessageSetMessageTag, ptr);
  219. ptr = EncodeVarintU64((uint64_t)value.length, ptr);
  220. uint8_t *split = ptr;
  221. ptr = EncodeVarintU32(GPBWireFormatMessageSetItemEndTag, ptr);
  222. uint8_t *end = ptr;
  223. if (self->unknownFieldData_ == nil) {
  224. self->unknownFieldData_ = [[NSMutableData alloc] initWithCapacity:(end - buf) + value.length];
  225. GPBBecomeVisibleToAutocreator(self);
  226. }
  227. [self->unknownFieldData_ appendBytes:buf length:split - buf];
  228. [self->unknownFieldData_ appendData:value];
  229. [self->unknownFieldData_ appendBytes:split length:end - split];
  230. }
  231. GPB_NOINLINE
  232. static void ParseUnknownField(GPBMessage *self, uint32_t tag, GPBCodedInputStream *input) {
  233. if (self->unknownFields_) {
  234. if (![self->unknownFields_ mergeFieldFrom:tag input:input]) {
  235. GPBRaiseStreamError(GPBCodedInputStreamErrorInvalidTag, @"Unexpected end-group tag");
  236. }
  237. return;
  238. }
  239. uint8_t buf[20];
  240. uint8_t *ptr = buf;
  241. ptr = EncodeVarintU32(tag, ptr); // All will need the tag
  242. NSData *bytesToAppend = nil;
  243. GPBCodedInputStreamState *state = &input->state_;
  244. switch (GPBWireFormatGetTagWireType(tag)) {
  245. case GPBWireFormatVarint: {
  246. ptr = EncodeVarintU64(GPBCodedInputStreamReadUInt64(state), ptr);
  247. break;
  248. }
  249. case GPBWireFormatFixed64: {
  250. uint64_t value = GPBCodedInputStreamReadFixed64(state);
  251. *(ptr++) = (uint8_t)(value) & 0xFF;
  252. *(ptr++) = (uint8_t)(value >> 8) & 0xFF;
  253. *(ptr++) = (uint8_t)(value >> 16) & 0xFF;
  254. *(ptr++) = (uint8_t)(value >> 24) & 0xFF;
  255. *(ptr++) = (uint8_t)(value >> 32) & 0xFF;
  256. *(ptr++) = (uint8_t)(value >> 40) & 0xFF;
  257. *(ptr++) = (uint8_t)(value >> 48) & 0xFF;
  258. *(ptr++) = (uint8_t)(value >> 56) & 0xFF;
  259. break;
  260. }
  261. case GPBWireFormatLengthDelimited: {
  262. bytesToAppend = GPBCodedInputStreamReadRetainedBytes(state);
  263. ptr = EncodeVarintU64((uint64_t)bytesToAppend.length, ptr);
  264. break;
  265. }
  266. case GPBWireFormatStartGroup: {
  267. bytesToAppend = GPBCodedInputStreamReadRetainedBytesToEndGroupNoCopy(
  268. state, GPBWireFormatGetTagFieldNumber(tag));
  269. break;
  270. }
  271. case GPBWireFormatEndGroup:
  272. GPBRaiseStreamError(GPBCodedInputStreamErrorInvalidTag, @"Unexpected end-group tag");
  273. break;
  274. case GPBWireFormatFixed32: {
  275. uint32_t value = GPBCodedInputStreamReadFixed32(state);
  276. *(ptr++) = (uint8_t)(value) & 0xFF;
  277. *(ptr++) = (uint8_t)(value >> 8) & 0xFF;
  278. *(ptr++) = (uint8_t)(value >> 16) & 0xFF;
  279. *(ptr++) = (uint8_t)(value >> 24) & 0xFF;
  280. break;
  281. }
  282. }
  283. if (self->unknownFieldData_ == nil) {
  284. self->unknownFieldData_ =
  285. [[NSMutableData alloc] initWithCapacity:(ptr - buf) + bytesToAppend.length];
  286. GPBBecomeVisibleToAutocreator(self);
  287. }
  288. [self->unknownFieldData_ appendBytes:buf length:ptr - buf];
  289. if (bytesToAppend) {
  290. [self->unknownFieldData_ appendData:bytesToAppend];
  291. [bytesToAppend release];
  292. }
  293. }
  294. static void CheckExtension(GPBMessage *self, GPBExtensionDescriptor *extension) {
  295. if (![self isKindOfClass:extension.containingMessageClass]) {
  296. [NSException raise:NSInvalidArgumentException
  297. format:@"Extension %@ used on wrong class (%@ instead of %@)",
  298. extension.singletonName, [self class], extension.containingMessageClass];
  299. }
  300. }
  301. static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, NSZone *zone) {
  302. if (extensionMap.count == 0) {
  303. return nil;
  304. }
  305. NSMutableDictionary *result =
  306. [[NSMutableDictionary allocWithZone:zone] initWithCapacity:extensionMap.count];
  307. for (GPBExtensionDescriptor *extension in extensionMap) {
  308. id value = [extensionMap objectForKey:extension];
  309. BOOL isMessageExtension = GPBExtensionIsMessage(extension);
  310. if (extension.repeated) {
  311. if (isMessageExtension) {
  312. NSMutableArray *list = [[NSMutableArray alloc] initWithCapacity:[value count]];
  313. for (GPBMessage *listValue in value) {
  314. GPBMessage *copiedValue = [listValue copyWithZone:zone];
  315. [list addObject:copiedValue];
  316. [copiedValue release];
  317. }
  318. [result setObject:list forKey:extension];
  319. [list release];
  320. } else {
  321. NSMutableArray *copiedValue = [value mutableCopyWithZone:zone];
  322. [result setObject:copiedValue forKey:extension];
  323. [copiedValue release];
  324. }
  325. } else {
  326. if (isMessageExtension) {
  327. GPBMessage *copiedValue = [value copyWithZone:zone];
  328. [result setObject:copiedValue forKey:extension];
  329. [copiedValue release];
  330. } else {
  331. [result setObject:value forKey:extension];
  332. }
  333. }
  334. }
  335. return result;
  336. }
  337. static id CreateArrayForField(GPBFieldDescriptor *field, GPBMessage *autocreator) {
  338. id result;
  339. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  340. switch (fieldDataType) {
  341. case GPBDataTypeBool:
  342. result = [[GPBBoolArray alloc] init];
  343. break;
  344. case GPBDataTypeFixed32:
  345. case GPBDataTypeUInt32:
  346. result = [[GPBUInt32Array alloc] init];
  347. break;
  348. case GPBDataTypeInt32:
  349. case GPBDataTypeSFixed32:
  350. case GPBDataTypeSInt32:
  351. result = [[GPBInt32Array alloc] init];
  352. break;
  353. case GPBDataTypeFixed64:
  354. case GPBDataTypeUInt64:
  355. result = [[GPBUInt64Array alloc] init];
  356. break;
  357. case GPBDataTypeInt64:
  358. case GPBDataTypeSFixed64:
  359. case GPBDataTypeSInt64:
  360. result = [[GPBInt64Array alloc] init];
  361. break;
  362. case GPBDataTypeFloat:
  363. result = [[GPBFloatArray alloc] init];
  364. break;
  365. case GPBDataTypeDouble:
  366. result = [[GPBDoubleArray alloc] init];
  367. break;
  368. case GPBDataTypeEnum:
  369. result = [[GPBEnumArray alloc] initWithValidationFunction:field.enumDescriptor.enumVerifier];
  370. break;
  371. case GPBDataTypeBytes:
  372. case GPBDataTypeGroup:
  373. case GPBDataTypeMessage:
  374. case GPBDataTypeString:
  375. if (autocreator) {
  376. result = [[GPBAutocreatedArray alloc] init];
  377. } else {
  378. result = [[NSMutableArray alloc] init];
  379. }
  380. break;
  381. }
  382. if (autocreator) {
  383. if (GPBDataTypeIsObject(fieldDataType)) {
  384. GPBAutocreatedArray *autoArray = result;
  385. autoArray->_autocreator = autocreator;
  386. } else {
  387. GPBInt32Array *gpbArray = result;
  388. gpbArray->_autocreator = autocreator;
  389. }
  390. }
  391. return result;
  392. }
  393. static id CreateMapForField(GPBFieldDescriptor *field, GPBMessage *autocreator) {
  394. id result;
  395. GPBDataType keyDataType = field.mapKeyDataType;
  396. GPBDataType valueDataType = GPBGetFieldDataType(field);
  397. switch (keyDataType) {
  398. case GPBDataTypeBool:
  399. switch (valueDataType) {
  400. case GPBDataTypeBool:
  401. result = [[GPBBoolBoolDictionary alloc] init];
  402. break;
  403. case GPBDataTypeFixed32:
  404. case GPBDataTypeUInt32:
  405. result = [[GPBBoolUInt32Dictionary alloc] init];
  406. break;
  407. case GPBDataTypeInt32:
  408. case GPBDataTypeSFixed32:
  409. case GPBDataTypeSInt32:
  410. result = [[GPBBoolInt32Dictionary alloc] init];
  411. break;
  412. case GPBDataTypeFixed64:
  413. case GPBDataTypeUInt64:
  414. result = [[GPBBoolUInt64Dictionary alloc] init];
  415. break;
  416. case GPBDataTypeInt64:
  417. case GPBDataTypeSFixed64:
  418. case GPBDataTypeSInt64:
  419. result = [[GPBBoolInt64Dictionary alloc] init];
  420. break;
  421. case GPBDataTypeFloat:
  422. result = [[GPBBoolFloatDictionary alloc] init];
  423. break;
  424. case GPBDataTypeDouble:
  425. result = [[GPBBoolDoubleDictionary alloc] init];
  426. break;
  427. case GPBDataTypeEnum:
  428. result = [[GPBBoolEnumDictionary alloc]
  429. initWithValidationFunction:field.enumDescriptor.enumVerifier];
  430. break;
  431. case GPBDataTypeBytes:
  432. case GPBDataTypeMessage:
  433. case GPBDataTypeString:
  434. result = [[GPBBoolObjectDictionary alloc] init];
  435. break;
  436. case GPBDataTypeGroup:
  437. NSCAssert(NO, @"shouldn't happen");
  438. return nil;
  439. }
  440. break;
  441. case GPBDataTypeFixed32:
  442. case GPBDataTypeUInt32:
  443. switch (valueDataType) {
  444. case GPBDataTypeBool:
  445. result = [[GPBUInt32BoolDictionary alloc] init];
  446. break;
  447. case GPBDataTypeFixed32:
  448. case GPBDataTypeUInt32:
  449. result = [[GPBUInt32UInt32Dictionary alloc] init];
  450. break;
  451. case GPBDataTypeInt32:
  452. case GPBDataTypeSFixed32:
  453. case GPBDataTypeSInt32:
  454. result = [[GPBUInt32Int32Dictionary alloc] init];
  455. break;
  456. case GPBDataTypeFixed64:
  457. case GPBDataTypeUInt64:
  458. result = [[GPBUInt32UInt64Dictionary alloc] init];
  459. break;
  460. case GPBDataTypeInt64:
  461. case GPBDataTypeSFixed64:
  462. case GPBDataTypeSInt64:
  463. result = [[GPBUInt32Int64Dictionary alloc] init];
  464. break;
  465. case GPBDataTypeFloat:
  466. result = [[GPBUInt32FloatDictionary alloc] init];
  467. break;
  468. case GPBDataTypeDouble:
  469. result = [[GPBUInt32DoubleDictionary alloc] init];
  470. break;
  471. case GPBDataTypeEnum:
  472. result = [[GPBUInt32EnumDictionary alloc]
  473. initWithValidationFunction:field.enumDescriptor.enumVerifier];
  474. break;
  475. case GPBDataTypeBytes:
  476. case GPBDataTypeMessage:
  477. case GPBDataTypeString:
  478. result = [[GPBUInt32ObjectDictionary alloc] init];
  479. break;
  480. case GPBDataTypeGroup:
  481. NSCAssert(NO, @"shouldn't happen");
  482. return nil;
  483. }
  484. break;
  485. case GPBDataTypeInt32:
  486. case GPBDataTypeSFixed32:
  487. case GPBDataTypeSInt32:
  488. switch (valueDataType) {
  489. case GPBDataTypeBool:
  490. result = [[GPBInt32BoolDictionary alloc] init];
  491. break;
  492. case GPBDataTypeFixed32:
  493. case GPBDataTypeUInt32:
  494. result = [[GPBInt32UInt32Dictionary alloc] init];
  495. break;
  496. case GPBDataTypeInt32:
  497. case GPBDataTypeSFixed32:
  498. case GPBDataTypeSInt32:
  499. result = [[GPBInt32Int32Dictionary alloc] init];
  500. break;
  501. case GPBDataTypeFixed64:
  502. case GPBDataTypeUInt64:
  503. result = [[GPBInt32UInt64Dictionary alloc] init];
  504. break;
  505. case GPBDataTypeInt64:
  506. case GPBDataTypeSFixed64:
  507. case GPBDataTypeSInt64:
  508. result = [[GPBInt32Int64Dictionary alloc] init];
  509. break;
  510. case GPBDataTypeFloat:
  511. result = [[GPBInt32FloatDictionary alloc] init];
  512. break;
  513. case GPBDataTypeDouble:
  514. result = [[GPBInt32DoubleDictionary alloc] init];
  515. break;
  516. case GPBDataTypeEnum:
  517. result = [[GPBInt32EnumDictionary alloc]
  518. initWithValidationFunction:field.enumDescriptor.enumVerifier];
  519. break;
  520. case GPBDataTypeBytes:
  521. case GPBDataTypeMessage:
  522. case GPBDataTypeString:
  523. result = [[GPBInt32ObjectDictionary alloc] init];
  524. break;
  525. case GPBDataTypeGroup:
  526. NSCAssert(NO, @"shouldn't happen");
  527. return nil;
  528. }
  529. break;
  530. case GPBDataTypeFixed64:
  531. case GPBDataTypeUInt64:
  532. switch (valueDataType) {
  533. case GPBDataTypeBool:
  534. result = [[GPBUInt64BoolDictionary alloc] init];
  535. break;
  536. case GPBDataTypeFixed32:
  537. case GPBDataTypeUInt32:
  538. result = [[GPBUInt64UInt32Dictionary alloc] init];
  539. break;
  540. case GPBDataTypeInt32:
  541. case GPBDataTypeSFixed32:
  542. case GPBDataTypeSInt32:
  543. result = [[GPBUInt64Int32Dictionary alloc] init];
  544. break;
  545. case GPBDataTypeFixed64:
  546. case GPBDataTypeUInt64:
  547. result = [[GPBUInt64UInt64Dictionary alloc] init];
  548. break;
  549. case GPBDataTypeInt64:
  550. case GPBDataTypeSFixed64:
  551. case GPBDataTypeSInt64:
  552. result = [[GPBUInt64Int64Dictionary alloc] init];
  553. break;
  554. case GPBDataTypeFloat:
  555. result = [[GPBUInt64FloatDictionary alloc] init];
  556. break;
  557. case GPBDataTypeDouble:
  558. result = [[GPBUInt64DoubleDictionary alloc] init];
  559. break;
  560. case GPBDataTypeEnum:
  561. result = [[GPBUInt64EnumDictionary alloc]
  562. initWithValidationFunction:field.enumDescriptor.enumVerifier];
  563. break;
  564. case GPBDataTypeBytes:
  565. case GPBDataTypeMessage:
  566. case GPBDataTypeString:
  567. result = [[GPBUInt64ObjectDictionary alloc] init];
  568. break;
  569. case GPBDataTypeGroup:
  570. NSCAssert(NO, @"shouldn't happen");
  571. return nil;
  572. }
  573. break;
  574. case GPBDataTypeInt64:
  575. case GPBDataTypeSFixed64:
  576. case GPBDataTypeSInt64:
  577. switch (valueDataType) {
  578. case GPBDataTypeBool:
  579. result = [[GPBInt64BoolDictionary alloc] init];
  580. break;
  581. case GPBDataTypeFixed32:
  582. case GPBDataTypeUInt32:
  583. result = [[GPBInt64UInt32Dictionary alloc] init];
  584. break;
  585. case GPBDataTypeInt32:
  586. case GPBDataTypeSFixed32:
  587. case GPBDataTypeSInt32:
  588. result = [[GPBInt64Int32Dictionary alloc] init];
  589. break;
  590. case GPBDataTypeFixed64:
  591. case GPBDataTypeUInt64:
  592. result = [[GPBInt64UInt64Dictionary alloc] init];
  593. break;
  594. case GPBDataTypeInt64:
  595. case GPBDataTypeSFixed64:
  596. case GPBDataTypeSInt64:
  597. result = [[GPBInt64Int64Dictionary alloc] init];
  598. break;
  599. case GPBDataTypeFloat:
  600. result = [[GPBInt64FloatDictionary alloc] init];
  601. break;
  602. case GPBDataTypeDouble:
  603. result = [[GPBInt64DoubleDictionary alloc] init];
  604. break;
  605. case GPBDataTypeEnum:
  606. result = [[GPBInt64EnumDictionary alloc]
  607. initWithValidationFunction:field.enumDescriptor.enumVerifier];
  608. break;
  609. case GPBDataTypeBytes:
  610. case GPBDataTypeMessage:
  611. case GPBDataTypeString:
  612. result = [[GPBInt64ObjectDictionary alloc] init];
  613. break;
  614. case GPBDataTypeGroup:
  615. NSCAssert(NO, @"shouldn't happen");
  616. return nil;
  617. }
  618. break;
  619. case GPBDataTypeString:
  620. switch (valueDataType) {
  621. case GPBDataTypeBool:
  622. result = [[GPBStringBoolDictionary alloc] init];
  623. break;
  624. case GPBDataTypeFixed32:
  625. case GPBDataTypeUInt32:
  626. result = [[GPBStringUInt32Dictionary alloc] init];
  627. break;
  628. case GPBDataTypeInt32:
  629. case GPBDataTypeSFixed32:
  630. case GPBDataTypeSInt32:
  631. result = [[GPBStringInt32Dictionary alloc] init];
  632. break;
  633. case GPBDataTypeFixed64:
  634. case GPBDataTypeUInt64:
  635. result = [[GPBStringUInt64Dictionary alloc] init];
  636. break;
  637. case GPBDataTypeInt64:
  638. case GPBDataTypeSFixed64:
  639. case GPBDataTypeSInt64:
  640. result = [[GPBStringInt64Dictionary alloc] init];
  641. break;
  642. case GPBDataTypeFloat:
  643. result = [[GPBStringFloatDictionary alloc] init];
  644. break;
  645. case GPBDataTypeDouble:
  646. result = [[GPBStringDoubleDictionary alloc] init];
  647. break;
  648. case GPBDataTypeEnum:
  649. result = [[GPBStringEnumDictionary alloc]
  650. initWithValidationFunction:field.enumDescriptor.enumVerifier];
  651. break;
  652. case GPBDataTypeBytes:
  653. case GPBDataTypeMessage:
  654. case GPBDataTypeString:
  655. if (autocreator) {
  656. result = [[GPBAutocreatedDictionary alloc] init];
  657. } else {
  658. result = [[NSMutableDictionary alloc] init];
  659. }
  660. break;
  661. case GPBDataTypeGroup:
  662. NSCAssert(NO, @"shouldn't happen");
  663. return nil;
  664. }
  665. break;
  666. case GPBDataTypeFloat:
  667. case GPBDataTypeDouble:
  668. case GPBDataTypeEnum:
  669. case GPBDataTypeBytes:
  670. case GPBDataTypeGroup:
  671. case GPBDataTypeMessage:
  672. NSCAssert(NO, @"shouldn't happen");
  673. return nil;
  674. }
  675. if (autocreator) {
  676. if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) {
  677. GPBAutocreatedDictionary *autoDict = result;
  678. autoDict->_autocreator = autocreator;
  679. } else {
  680. GPBInt32Int32Dictionary *gpbDict = result;
  681. gpbDict->_autocreator = autocreator;
  682. }
  683. }
  684. return result;
  685. }
  686. #if !defined(__clang_analyzer__)
  687. // These functions are blocked from the analyzer because the analyzer sees the
  688. // GPBSetRetainedObjectIvarWithFieldPrivate() call as consuming the array/map,
  689. // so use of the array/map after the call returns is flagged as a use after
  690. // free.
  691. // But GPBSetRetainedObjectIvarWithFieldPrivate() is "consuming" the retain
  692. // count be holding onto the object (it is transferring it), the object is
  693. // still valid after returning from the call. The other way to avoid this
  694. // would be to add a -retain/-autorelease, but that would force every
  695. // repeated/map field parsed into the autorelease pool which is both a memory
  696. // and performance hit.
  697. static id GetOrCreateArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
  698. id array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  699. if (!array) {
  700. // No lock needed, this is called from places expecting to mutate
  701. // so no threading protection is needed.
  702. array = CreateArrayForField(field, nil);
  703. GPBSetRetainedObjectIvarWithFieldPrivate(self, field, array);
  704. }
  705. return array;
  706. }
  707. // This is like GPBGetObjectIvarWithField(), but for arrays, it should
  708. // only be used to wire the method into the class.
  709. static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
  710. uint8_t *storage = (uint8_t *)self->messageStorage_;
  711. _Atomic(id) *typePtr = (_Atomic(id) *)&storage[field->description_->offset];
  712. id array = atomic_load(typePtr);
  713. if (array) {
  714. return array;
  715. }
  716. id expected = nil;
  717. id autocreated = CreateArrayForField(field, self);
  718. if (atomic_compare_exchange_strong(typePtr, &expected, autocreated)) {
  719. // Value was set, return it.
  720. return autocreated;
  721. }
  722. // Some other thread set it, release the one created and return what got set.
  723. if (GPBFieldDataTypeIsObject(field)) {
  724. GPBAutocreatedArray *autoArray = autocreated;
  725. autoArray->_autocreator = nil;
  726. } else {
  727. GPBInt32Array *gpbArray = autocreated;
  728. gpbArray->_autocreator = nil;
  729. }
  730. [autocreated release];
  731. return expected;
  732. }
  733. static id GetOrCreateMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
  734. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  735. if (!dict) {
  736. // No lock needed, this is called from places expecting to mutate
  737. // so no threading protection is needed.
  738. dict = CreateMapForField(field, nil);
  739. GPBSetRetainedObjectIvarWithFieldPrivate(self, field, dict);
  740. }
  741. return dict;
  742. }
  743. // This is like GPBGetObjectIvarWithField(), but for maps, it should
  744. // only be used to wire the method into the class.
  745. static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
  746. uint8_t *storage = (uint8_t *)self->messageStorage_;
  747. _Atomic(id) *typePtr = (_Atomic(id) *)&storage[field->description_->offset];
  748. id dict = atomic_load(typePtr);
  749. if (dict) {
  750. return dict;
  751. }
  752. id expected = nil;
  753. id autocreated = CreateMapForField(field, self);
  754. if (atomic_compare_exchange_strong(typePtr, &expected, autocreated)) {
  755. // Value was set, return it.
  756. return autocreated;
  757. }
  758. // Some other thread set it, release the one created and return what got set.
  759. if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) {
  760. GPBAutocreatedDictionary *autoDict = autocreated;
  761. autoDict->_autocreator = nil;
  762. } else {
  763. GPBInt32Int32Dictionary *gpbDict = autocreated;
  764. gpbDict->_autocreator = nil;
  765. }
  766. [autocreated release];
  767. return expected;
  768. }
  769. #endif // !defined(__clang_analyzer__)
  770. static void DecodeSingleValueFromInputStream(GPBExtensionDescriptor *extension,
  771. GPBMessage *messageToGetExtension,
  772. GPBCodedInputStream *input,
  773. id<GPBExtensionRegistry> extensionRegistry,
  774. BOOL isRepeated, GPBMessage *targetMessage) {
  775. GPBExtensionDescription *description = extension->description_;
  776. #if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS)
  777. if (GPBDataTypeIsMessage(description->dataType)) {
  778. NSCAssert(targetMessage != nil, @"Internal error: must have a target message");
  779. } else {
  780. NSCAssert(targetMessage == nil, @"Internal error: should not have a target message");
  781. }
  782. #endif
  783. GPBCodedInputStreamState *state = &input->state_;
  784. id nsValue;
  785. switch (description->dataType) {
  786. case GPBDataTypeBool: {
  787. BOOL value = GPBCodedInputStreamReadBool(state);
  788. nsValue = [[NSNumber alloc] initWithBool:value];
  789. break;
  790. }
  791. case GPBDataTypeFixed32: {
  792. uint32_t value = GPBCodedInputStreamReadFixed32(state);
  793. nsValue = [[NSNumber alloc] initWithUnsignedInt:value];
  794. break;
  795. }
  796. case GPBDataTypeSFixed32: {
  797. int32_t value = GPBCodedInputStreamReadSFixed32(state);
  798. nsValue = [[NSNumber alloc] initWithInt:value];
  799. break;
  800. }
  801. case GPBDataTypeFloat: {
  802. float value = GPBCodedInputStreamReadFloat(state);
  803. nsValue = [[NSNumber alloc] initWithFloat:value];
  804. break;
  805. }
  806. case GPBDataTypeFixed64: {
  807. uint64_t value = GPBCodedInputStreamReadFixed64(state);
  808. nsValue = [[NSNumber alloc] initWithUnsignedLongLong:value];
  809. break;
  810. }
  811. case GPBDataTypeSFixed64: {
  812. int64_t value = GPBCodedInputStreamReadSFixed64(state);
  813. nsValue = [[NSNumber alloc] initWithLongLong:value];
  814. break;
  815. }
  816. case GPBDataTypeDouble: {
  817. double value = GPBCodedInputStreamReadDouble(state);
  818. nsValue = [[NSNumber alloc] initWithDouble:value];
  819. break;
  820. }
  821. case GPBDataTypeInt32: {
  822. int32_t value = GPBCodedInputStreamReadInt32(state);
  823. nsValue = [[NSNumber alloc] initWithInt:value];
  824. break;
  825. }
  826. case GPBDataTypeInt64: {
  827. int64_t value = GPBCodedInputStreamReadInt64(state);
  828. nsValue = [[NSNumber alloc] initWithLongLong:value];
  829. break;
  830. }
  831. case GPBDataTypeSInt32: {
  832. int32_t value = GPBCodedInputStreamReadSInt32(state);
  833. nsValue = [[NSNumber alloc] initWithInt:value];
  834. break;
  835. }
  836. case GPBDataTypeSInt64: {
  837. int64_t value = GPBCodedInputStreamReadSInt64(state);
  838. nsValue = [[NSNumber alloc] initWithLongLong:value];
  839. break;
  840. }
  841. case GPBDataTypeUInt32: {
  842. uint32_t value = GPBCodedInputStreamReadUInt32(state);
  843. nsValue = [[NSNumber alloc] initWithUnsignedInt:value];
  844. break;
  845. }
  846. case GPBDataTypeUInt64: {
  847. uint64_t value = GPBCodedInputStreamReadUInt64(state);
  848. nsValue = [[NSNumber alloc] initWithUnsignedLongLong:value];
  849. break;
  850. }
  851. case GPBDataTypeBytes:
  852. nsValue = GPBCodedInputStreamReadRetainedBytes(state);
  853. break;
  854. case GPBDataTypeString:
  855. nsValue = GPBCodedInputStreamReadRetainedString(state);
  856. break;
  857. case GPBDataTypeEnum: {
  858. int32_t val = GPBCodedInputStreamReadEnum(&input->state_);
  859. GPBEnumDescriptor *enumDescriptor = extension.enumDescriptor;
  860. // If run with source generated before the closed enum support, all enums
  861. // will be considers not closed, so casing to the enum type for a switch
  862. // could cause things to fall off the end of a switch.
  863. if (!enumDescriptor.isClosed || enumDescriptor.enumVerifier(val)) {
  864. nsValue = [[NSNumber alloc] initWithInt:val];
  865. } else {
  866. AddUnknownFieldVarint32(messageToGetExtension, extension->description_->fieldNumber, val);
  867. nsValue = nil;
  868. }
  869. break;
  870. }
  871. case GPBDataTypeGroup:
  872. case GPBDataTypeMessage: {
  873. if (description->dataType == GPBDataTypeGroup) {
  874. [input readGroup:description->fieldNumber
  875. message:targetMessage
  876. extensionRegistry:extensionRegistry];
  877. } else {
  878. // description->dataType == GPBDataTypeMessage
  879. #if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS)
  880. NSCAssert(!GPBExtensionIsWireFormat(description),
  881. @"Internal error: got a MessageSet extension when not expected.");
  882. #endif
  883. [input readMessage:targetMessage extensionRegistry:extensionRegistry];
  884. }
  885. // Nothing to add below since the caller provided the message (and added it).
  886. nsValue = nil;
  887. break;
  888. }
  889. } // switch
  890. if (nsValue) {
  891. if (isRepeated) {
  892. [messageToGetExtension addExtension:extension value:nsValue];
  893. } else {
  894. [messageToGetExtension setExtension:extension value:nsValue];
  895. }
  896. [nsValue release];
  897. }
  898. }
  899. static void ExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, BOOL isPackedOnStream,
  900. GPBCodedInputStream *input,
  901. id<GPBExtensionRegistry> extensionRegistry,
  902. GPBMessage *message) {
  903. GPBExtensionDescription *description = extension->description_;
  904. GPBCodedInputStreamState *state = &input->state_;
  905. if (isPackedOnStream) {
  906. #if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS)
  907. NSCAssert(GPBExtensionIsRepeated(description), @"How was it packed if it isn't repeated?");
  908. #endif
  909. int32_t length = GPBCodedInputStreamReadInt32(state);
  910. size_t limit = GPBCodedInputStreamPushLimit(state, length);
  911. while (GPBCodedInputStreamBytesUntilLimit(state) > 0) {
  912. DecodeSingleValueFromInputStream(extension, message, input, extensionRegistry,
  913. /*isRepeated=*/YES, nil);
  914. }
  915. GPBCodedInputStreamPopLimit(state, limit);
  916. } else {
  917. BOOL isRepeated = GPBExtensionIsRepeated(description);
  918. GPBMessage *targetMessage = nil;
  919. if (GPBDataTypeIsMessage(description->dataType)) {
  920. // For messages/groups create the targetMessage out here and add it to the objects graph in
  921. // advance, that way if DecodeSingleValueFromInputStream() throw for a parsing issue, the
  922. // object won't be leaked.
  923. if (isRepeated) {
  924. GPBDescriptor *descriptor = [extension.msgClass descriptor];
  925. targetMessage = [[descriptor.messageClass alloc] init];
  926. [message addExtension:extension value:targetMessage];
  927. [targetMessage release];
  928. } else {
  929. targetMessage = [message getExistingExtension:extension];
  930. if (!targetMessage) {
  931. GPBDescriptor *descriptor = [extension.msgClass descriptor];
  932. targetMessage = [[descriptor.messageClass alloc] init];
  933. [message setExtension:extension value:targetMessage];
  934. [targetMessage release];
  935. }
  936. }
  937. }
  938. DecodeSingleValueFromInputStream(extension, message, input, extensionRegistry, isRepeated,
  939. targetMessage);
  940. }
  941. }
  942. static GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, GPBMessage *autocreator,
  943. GPBFieldDescriptor *field) {
  944. GPBMessage *message = [[msgClass alloc] init];
  945. message->autocreator_ = autocreator;
  946. message->autocreatorField_ = [field retain];
  947. return message;
  948. }
  949. static GPBMessage *CreateMessageWithAutocreatorForExtension(Class msgClass, GPBMessage *autocreator,
  950. GPBExtensionDescriptor *extension)
  951. __attribute__((ns_returns_retained));
  952. static GPBMessage *CreateMessageWithAutocreatorForExtension(Class msgClass, GPBMessage *autocreator,
  953. GPBExtensionDescriptor *extension) {
  954. GPBMessage *message = [[msgClass alloc] init];
  955. message->autocreator_ = autocreator;
  956. message->autocreatorExtension_ = [extension retain];
  957. return message;
  958. }
  959. BOOL GPBWasMessageAutocreatedBy(GPBMessage *message, GPBMessage *parent) {
  960. return (message->autocreator_ == parent);
  961. }
  962. void GPBBecomeVisibleToAutocreator(GPBMessage *self) {
  963. // Message objects that are implicitly created by accessing a message field
  964. // are initially not visible via the hasX selector. This method makes them
  965. // visible.
  966. if (self->autocreator_) {
  967. // This will recursively make all parent messages visible until it reaches a
  968. // super-creator that's visible.
  969. if (self->autocreatorField_) {
  970. GPBSetObjectIvarWithFieldPrivate(self->autocreator_, self->autocreatorField_, self);
  971. } else {
  972. [self->autocreator_ setExtension:self->autocreatorExtension_ value:self];
  973. }
  974. }
  975. }
  976. void GPBAutocreatedArrayModified(GPBMessage *self, id array) {
  977. // When one of our autocreated arrays adds elements, make it visible.
  978. GPBDescriptor *descriptor = [[self class] descriptor];
  979. for (GPBFieldDescriptor *field in descriptor->fields_) {
  980. if (field.fieldType == GPBFieldTypeRepeated) {
  981. id curArray = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  982. if (curArray == array) {
  983. if (GPBFieldDataTypeIsObject(field)) {
  984. GPBAutocreatedArray *autoArray = array;
  985. autoArray->_autocreator = nil;
  986. } else {
  987. GPBInt32Array *gpbArray = array;
  988. gpbArray->_autocreator = nil;
  989. }
  990. GPBBecomeVisibleToAutocreator(self);
  991. return;
  992. }
  993. }
  994. }
  995. NSCAssert(NO, @"Unknown autocreated %@ for %@.", [array class], self);
  996. }
  997. void GPBAutocreatedDictionaryModified(GPBMessage *self, id dictionary) {
  998. // When one of our autocreated dicts adds elements, make it visible.
  999. GPBDescriptor *descriptor = [[self class] descriptor];
  1000. for (GPBFieldDescriptor *field in descriptor->fields_) {
  1001. if (field.fieldType == GPBFieldTypeMap) {
  1002. id curDict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1003. if (curDict == dictionary) {
  1004. if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) {
  1005. GPBAutocreatedDictionary *autoDict = dictionary;
  1006. autoDict->_autocreator = nil;
  1007. } else {
  1008. GPBInt32Int32Dictionary *gpbDict = dictionary;
  1009. gpbDict->_autocreator = nil;
  1010. }
  1011. GPBBecomeVisibleToAutocreator(self);
  1012. return;
  1013. }
  1014. }
  1015. }
  1016. NSCAssert(NO, @"Unknown autocreated %@ for %@.", [dictionary class], self);
  1017. }
  1018. void GPBClearMessageAutocreator(GPBMessage *self) {
  1019. if ((self == nil) || !self->autocreator_) {
  1020. return;
  1021. }
  1022. #if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS)
  1023. // Either the autocreator must have its "has" flag set to YES, or it must be
  1024. // NO and not equal to ourselves.
  1025. BOOL autocreatorHas =
  1026. (self->autocreatorField_ ? GPBGetHasIvarField(self->autocreator_, self->autocreatorField_)
  1027. : [self->autocreator_ hasExtension:self->autocreatorExtension_]);
  1028. GPBMessage *autocreatorFieldValue =
  1029. (self->autocreatorField_
  1030. ? GPBGetObjectIvarWithFieldNoAutocreate(self->autocreator_, self->autocreatorField_)
  1031. : [self->autocreator_->autocreatedExtensionMap_
  1032. objectForKey:self->autocreatorExtension_]);
  1033. NSCAssert(autocreatorHas || autocreatorFieldValue != self,
  1034. @"Cannot clear autocreator because it still refers to self, self: %@.", self);
  1035. #endif // DEBUG && !defined(NS_BLOCK_ASSERTIONS)
  1036. self->autocreator_ = nil;
  1037. [self->autocreatorField_ release];
  1038. self->autocreatorField_ = nil;
  1039. [self->autocreatorExtension_ release];
  1040. self->autocreatorExtension_ = nil;
  1041. }
  1042. #pragma clang diagnostic push
  1043. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  1044. GPB_NOINLINE
  1045. static void MergeUnknownFieldDataIntoFieldSet(GPBMessage *self, NSData *data,
  1046. GPBUnknownFieldSet *targetSet) {
  1047. GPBUnknownFieldSet *unknownFields = targetSet ? targetSet : self->unknownFields_;
  1048. #if defined(DEBUG) && DEBUG
  1049. NSCAssert(unknownFields != nil, @"Internal error: unknown fields not initialized.");
  1050. #endif
  1051. BOOL isMessageSet = self.descriptor.isWireFormat;
  1052. GPBUnknownFieldSet *decodeInto = isMessageSet ? [[GPBUnknownFieldSet alloc] init] : unknownFields;
  1053. GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data];
  1054. @try {
  1055. [decodeInto mergeFromCodedInputStream:input];
  1056. } @catch (NSException *exception) {
  1057. #if defined(DEBUG) && DEBUG
  1058. NSLog(@"%@: Internal exception while parsing the unknown fields into a Set: %@", [self class],
  1059. exception);
  1060. #endif
  1061. }
  1062. [input release];
  1063. if (isMessageSet) {
  1064. // Need to transform the groups back into how Message feeds the data into a MessageSet when
  1065. // doing a full MessageSet based decode.
  1066. GPBUnknownField *groupField = [decodeInto getField:GPBWireFormatMessageSetItem];
  1067. for (GPBUnknownFieldSet *group in groupField.groupList) {
  1068. GPBUnknownField *typeIdField = [group getField:GPBWireFormatMessageSetTypeId];
  1069. GPBUnknownField *messageField = [group getField:GPBWireFormatMessageSetMessage];
  1070. if (typeIdField.varintList.count != 1 || messageField.lengthDelimitedList.count != 1) {
  1071. #if defined(DEBUG) && DEBUG
  1072. NSCAssert(NO, @"Internal error: MessageSet group missing typeId or message.");
  1073. #endif
  1074. continue;
  1075. }
  1076. int32_t fieldNumber = (int32_t)[typeIdField.varintList valueAtIndex:0];
  1077. GPBUnknownField *messageSetField = [[GPBUnknownField alloc] initWithNumber:fieldNumber];
  1078. [messageSetField addLengthDelimited:messageField.lengthDelimitedList[0]];
  1079. [unknownFields addField:messageSetField];
  1080. [messageSetField release];
  1081. }
  1082. [decodeInto release];
  1083. }
  1084. }
  1085. #pragma clang diagnostic pop
  1086. @implementation GPBMessage
  1087. + (void)initialize {
  1088. Class pbMessageClass = [GPBMessage class];
  1089. if ([self class] == pbMessageClass) {
  1090. // This is here to start up the "base" class descriptor.
  1091. [self descriptor];
  1092. // Message shares extension method resolving with GPBRootObject so insure
  1093. // it is started up at the same time.
  1094. (void)[GPBRootObject class];
  1095. } else if ([self superclass] == pbMessageClass) {
  1096. // This is here to start up all the "message" subclasses. Just needs to be
  1097. // done for the messages, not any of the subclasses.
  1098. // This must be done in initialize to enforce thread safety of start up of
  1099. // the protocol buffer library.
  1100. // Note: The generated code for -descriptor calls
  1101. // +[GPBDescriptor allocDescriptorForClass:...], passing the GPBRootObject
  1102. // subclass for the file. That call chain is what ensures that *Root class
  1103. // is started up to support extension resolution off the message class
  1104. // (+resolveClassMethod: below) in a thread safe manner.
  1105. [self descriptor];
  1106. }
  1107. }
  1108. + (instancetype)allocWithZone:(NSZone *)zone {
  1109. // Override alloc to allocate our classes with the additional storage
  1110. // required for the instance variables.
  1111. GPBDescriptor *descriptor = [self descriptor];
  1112. return NSAllocateObject(self, descriptor->storageSize_, zone);
  1113. }
  1114. + (instancetype)alloc {
  1115. return [self allocWithZone:nil];
  1116. }
  1117. + (GPBDescriptor *)descriptor {
  1118. // This is thread safe because it is called from +initialize.
  1119. static GPBDescriptor *descriptor = NULL;
  1120. static GPBFileDescription fileDescription = {
  1121. .package = "internal", .prefix = "", .syntax = GPBFileSyntaxProto2};
  1122. if (!descriptor) {
  1123. descriptor = [GPBDescriptor
  1124. allocDescriptorForClass:[GPBMessage class]
  1125. messageName:@"GPBMessage"
  1126. fileDescription:&fileDescription
  1127. fields:NULL
  1128. fieldCount:0
  1129. storageSize:0
  1130. flags:(GPBDescriptorInitializationFlag_UsesClassRefs |
  1131. GPBDescriptorInitializationFlag_Proto3OptionalKnown |
  1132. GPBDescriptorInitializationFlag_ClosedEnumSupportKnown)];
  1133. }
  1134. return descriptor;
  1135. }
  1136. + (instancetype)message {
  1137. return [[[self alloc] init] autorelease];
  1138. }
  1139. - (instancetype)init {
  1140. if ((self = [super init])) {
  1141. messageStorage_ =
  1142. (GPBMessage_StoragePtr)(((uint8_t *)self) + class_getInstanceSize([self class]));
  1143. readOnlyLock_ = OS_UNFAIR_LOCK_INIT;
  1144. }
  1145. return self;
  1146. }
  1147. - (instancetype)initWithData:(NSData *)data error:(NSError **)errorPtr {
  1148. return [self initWithData:data extensionRegistry:nil error:errorPtr];
  1149. }
  1150. - (instancetype)initWithData:(NSData *)data
  1151. extensionRegistry:(id<GPBExtensionRegistry>)extensionRegistry
  1152. error:(NSError **)errorPtr {
  1153. if ((self = [self init])) {
  1154. if (![self mergeFromData:data extensionRegistry:extensionRegistry error:errorPtr]) {
  1155. [self release];
  1156. self = nil;
  1157. #if defined(DEBUG) && DEBUG
  1158. } else if (!self.initialized) {
  1159. [self release];
  1160. self = nil;
  1161. if (errorPtr) {
  1162. *errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil);
  1163. }
  1164. #endif
  1165. }
  1166. }
  1167. return self;
  1168. }
  1169. - (instancetype)initWithCodedInputStream:(GPBCodedInputStream *)input
  1170. extensionRegistry:(id<GPBExtensionRegistry>)extensionRegistry
  1171. error:(NSError **)errorPtr {
  1172. if ((self = [self init])) {
  1173. @try {
  1174. [self mergeFromCodedInputStream:input extensionRegistry:extensionRegistry endingTag:0];
  1175. if (errorPtr) {
  1176. *errorPtr = nil;
  1177. }
  1178. } @catch (NSException *exception) {
  1179. [self release];
  1180. self = nil;
  1181. if (errorPtr) {
  1182. *errorPtr = ErrorFromException(exception);
  1183. }
  1184. }
  1185. #if defined(DEBUG) && DEBUG
  1186. if (self && !self.initialized) {
  1187. [self release];
  1188. self = nil;
  1189. if (errorPtr) {
  1190. *errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil);
  1191. }
  1192. }
  1193. #endif
  1194. }
  1195. return self;
  1196. }
  1197. - (void)dealloc {
  1198. [self internalClear:NO];
  1199. NSCAssert(!autocreator_, @"Autocreator was not cleared before dealloc.");
  1200. [super dealloc];
  1201. }
  1202. - (void)copyFieldsInto:(GPBMessage *)message
  1203. zone:(NSZone *)zone
  1204. descriptor:(GPBDescriptor *)descriptor {
  1205. // Copy all the storage...
  1206. memcpy(message->messageStorage_, messageStorage_, descriptor->storageSize_);
  1207. // Loop over the fields doing fixup...
  1208. for (GPBFieldDescriptor *field in descriptor->fields_) {
  1209. if (GPBFieldIsMapOrArray(field)) {
  1210. id value = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1211. if (value) {
  1212. // We need to copy the array/map, but the catch is for message fields,
  1213. // we also need to ensure all the messages as those need copying also.
  1214. id newValue;
  1215. if (GPBFieldDataTypeIsMessage(field)) {
  1216. if (field.fieldType == GPBFieldTypeRepeated) {
  1217. NSArray *existingArray = (NSArray *)value;
  1218. NSMutableArray *newArray =
  1219. [[NSMutableArray alloc] initWithCapacity:existingArray.count];
  1220. newValue = newArray;
  1221. for (GPBMessage *msg in existingArray) {
  1222. GPBMessage *copiedMsg = [msg copyWithZone:zone];
  1223. [newArray addObject:copiedMsg];
  1224. [copiedMsg release];
  1225. }
  1226. } else {
  1227. if (field.mapKeyDataType == GPBDataTypeString) {
  1228. // Map is an NSDictionary.
  1229. NSDictionary *existingDict = value;
  1230. NSMutableDictionary *newDict =
  1231. [[NSMutableDictionary alloc] initWithCapacity:existingDict.count];
  1232. newValue = newDict;
  1233. [existingDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, GPBMessage *msg,
  1234. __unused BOOL *stop) {
  1235. GPBMessage *copiedMsg = [msg copyWithZone:zone];
  1236. [newDict setObject:copiedMsg forKey:key];
  1237. [copiedMsg release];
  1238. }];
  1239. } else {
  1240. // Is one of the GPB*ObjectDictionary classes. Type doesn't
  1241. // matter, just need one to invoke the selector.
  1242. GPBInt32ObjectDictionary *existingDict = value;
  1243. newValue = [existingDict deepCopyWithZone:zone];
  1244. }
  1245. }
  1246. } else {
  1247. // Not messages (but is a map/array)...
  1248. if (field.fieldType == GPBFieldTypeRepeated) {
  1249. if (GPBFieldDataTypeIsObject(field)) {
  1250. // NSArray
  1251. newValue = [value mutableCopyWithZone:zone];
  1252. } else {
  1253. // GPB*Array
  1254. newValue = [value copyWithZone:zone];
  1255. }
  1256. } else {
  1257. if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) {
  1258. // NSDictionary
  1259. newValue = [value mutableCopyWithZone:zone];
  1260. } else {
  1261. // Is one of the GPB*Dictionary classes. Type doesn't matter,
  1262. // just need one to invoke the selector.
  1263. GPBInt32Int32Dictionary *existingDict = value;
  1264. newValue = [existingDict copyWithZone:zone];
  1265. }
  1266. }
  1267. }
  1268. // We retain here because the memcpy picked up the pointer value and
  1269. // the next call to SetRetainedObject... will release the current value.
  1270. [value retain];
  1271. GPBSetRetainedObjectIvarWithFieldPrivate(message, field, newValue);
  1272. }
  1273. } else if (GPBFieldDataTypeIsMessage(field)) {
  1274. // For object types, if we have a value, copy it. If we don't,
  1275. // zero it to remove the pointer to something that was autocreated
  1276. // (and the ptr just got memcpyed).
  1277. if (GPBGetHasIvarField(self, field)) {
  1278. GPBMessage *value = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1279. GPBMessage *newValue = [value copyWithZone:zone];
  1280. // We retain here because the memcpy picked up the pointer value and
  1281. // the next call to SetRetainedObject... will release the current value.
  1282. [value retain];
  1283. GPBSetRetainedObjectIvarWithFieldPrivate(message, field, newValue);
  1284. } else {
  1285. uint8_t *storage = (uint8_t *)message->messageStorage_;
  1286. id *typePtr = (id *)&storage[field->description_->offset];
  1287. *typePtr = NULL;
  1288. }
  1289. } else if (GPBFieldDataTypeIsObject(field) && GPBGetHasIvarField(self, field)) {
  1290. // A set string/data value (message picked off above), copy it.
  1291. id value = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1292. id newValue = [value copyWithZone:zone];
  1293. // We retain here because the memcpy picked up the pointer value and
  1294. // the next call to SetRetainedObject... will release the current value.
  1295. [value retain];
  1296. GPBSetRetainedObjectIvarWithFieldPrivate(message, field, newValue);
  1297. } else {
  1298. // memcpy took care of the rest of the primitive fields if they were set.
  1299. }
  1300. } // for (field in descriptor->fields_)
  1301. }
  1302. - (id)copyWithZone:(NSZone *)zone {
  1303. GPBDescriptor *descriptor = [self descriptor];
  1304. GPBMessage *result = [[descriptor.messageClass allocWithZone:zone] init];
  1305. [self copyFieldsInto:result zone:zone descriptor:descriptor];
  1306. @synchronized(self) {
  1307. result->unknownFields_ = [unknownFields_ copyWithZone:zone];
  1308. result->unknownFieldData_ = [unknownFieldData_ mutableCopyWithZone:zone];
  1309. }
  1310. result->extensionMap_ = CloneExtensionMap(extensionMap_, zone);
  1311. return result;
  1312. }
  1313. - (void)clear {
  1314. [self internalClear:YES];
  1315. }
  1316. - (void)internalClear:(BOOL)zeroStorage {
  1317. GPBDescriptor *descriptor = [self descriptor];
  1318. for (GPBFieldDescriptor *field in descriptor->fields_) {
  1319. if (GPBFieldIsMapOrArray(field)) {
  1320. id arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1321. if (arrayOrMap) {
  1322. if (field.fieldType == GPBFieldTypeRepeated) {
  1323. if (GPBFieldDataTypeIsObject(field)) {
  1324. if ([arrayOrMap isKindOfClass:[GPBAutocreatedArray class]]) {
  1325. GPBAutocreatedArray *autoArray = arrayOrMap;
  1326. if (autoArray->_autocreator == self) {
  1327. autoArray->_autocreator = nil;
  1328. }
  1329. }
  1330. } else {
  1331. // Type doesn't matter, it is a GPB*Array.
  1332. GPBInt32Array *gpbArray = arrayOrMap;
  1333. if (gpbArray->_autocreator == self) {
  1334. gpbArray->_autocreator = nil;
  1335. }
  1336. }
  1337. } else {
  1338. if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) {
  1339. if ([arrayOrMap isKindOfClass:[GPBAutocreatedDictionary class]]) {
  1340. GPBAutocreatedDictionary *autoDict = arrayOrMap;
  1341. if (autoDict->_autocreator == self) {
  1342. autoDict->_autocreator = nil;
  1343. }
  1344. }
  1345. } else {
  1346. // Type doesn't matter, it is a GPB*Dictionary.
  1347. GPBInt32Int32Dictionary *gpbDict = arrayOrMap;
  1348. if (gpbDict->_autocreator == self) {
  1349. gpbDict->_autocreator = nil;
  1350. }
  1351. }
  1352. }
  1353. [arrayOrMap release];
  1354. }
  1355. } else if (GPBFieldDataTypeIsMessage(field)) {
  1356. GPBClearAutocreatedMessageIvarWithField(self, field);
  1357. GPBMessage *value = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1358. [value release];
  1359. } else if (GPBFieldDataTypeIsObject(field) && GPBGetHasIvarField(self, field)) {
  1360. id value = GPBGetObjectIvarWithField(self, field);
  1361. [value release];
  1362. }
  1363. }
  1364. // GPBClearMessageAutocreator() expects that its caller has already been
  1365. // removed from autocreatedExtensionMap_ so we set to nil first.
  1366. NSArray *autocreatedValues = [autocreatedExtensionMap_ allValues];
  1367. [autocreatedExtensionMap_ release];
  1368. autocreatedExtensionMap_ = nil;
  1369. // Since we're clearing all of our extensions, make sure that we clear the
  1370. // autocreator on any that we've created so they no longer refer to us.
  1371. for (GPBMessage *value in autocreatedValues) {
  1372. NSCAssert(GPBWasMessageAutocreatedBy(value, self),
  1373. @"Autocreated extension does not refer back to self.");
  1374. GPBClearMessageAutocreator(value);
  1375. }
  1376. [extensionMap_ release];
  1377. extensionMap_ = nil;
  1378. [unknownFieldData_ release];
  1379. unknownFieldData_ = nil;
  1380. [unknownFields_ release];
  1381. unknownFields_ = nil;
  1382. // Note that clearing does not affect autocreator_. If we are being cleared
  1383. // because of a dealloc, then autocreator_ should be nil anyway. If we are
  1384. // being cleared because someone explicitly clears us, we don't want to
  1385. // sever our relationship with our autocreator.
  1386. if (zeroStorage) {
  1387. memset(messageStorage_, 0, descriptor->storageSize_);
  1388. }
  1389. }
  1390. - (void)clearUnknownFields {
  1391. [unknownFieldData_ release];
  1392. unknownFieldData_ = nil;
  1393. #pragma clang diagnostic push
  1394. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  1395. [unknownFields_ release];
  1396. unknownFields_ = nil;
  1397. #pragma clang diagnostic pop
  1398. GPBBecomeVisibleToAutocreator(self);
  1399. }
  1400. - (BOOL)mergeUnknownFields:(GPBUnknownFields *)unknownFields
  1401. extensionRegistry:(nullable id<GPBExtensionRegistry>)extensionRegistry
  1402. error:(NSError **)errorPtr {
  1403. return [self mergeFromData:[unknownFields serializeAsData]
  1404. extensionRegistry:extensionRegistry
  1405. error:errorPtr];
  1406. }
  1407. - (BOOL)isInitialized {
  1408. GPBDescriptor *descriptor = [self descriptor];
  1409. for (GPBFieldDescriptor *field in descriptor->fields_) {
  1410. if (field.isRequired) {
  1411. if (!GPBGetHasIvarField(self, field)) {
  1412. return NO;
  1413. }
  1414. }
  1415. if (GPBFieldDataTypeIsMessage(field)) {
  1416. GPBFieldType fieldType = field.fieldType;
  1417. if (fieldType == GPBFieldTypeSingle) {
  1418. if (field.isRequired) {
  1419. GPBMessage *message = GPBGetMessageMessageField(self, field);
  1420. if (!message.initialized) {
  1421. return NO;
  1422. }
  1423. } else {
  1424. NSAssert(field.isOptional, @"%@: Single message field %@ not required or optional?",
  1425. [self class], field.name);
  1426. if (GPBGetHasIvarField(self, field)) {
  1427. GPBMessage *message = GPBGetMessageMessageField(self, field);
  1428. if (!message.initialized) {
  1429. return NO;
  1430. }
  1431. }
  1432. }
  1433. } else if (fieldType == GPBFieldTypeRepeated) {
  1434. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1435. for (GPBMessage *message in array) {
  1436. if (!message.initialized) {
  1437. return NO;
  1438. }
  1439. }
  1440. } else { // fieldType == GPBFieldTypeMap
  1441. if (field.mapKeyDataType == GPBDataTypeString) {
  1442. NSDictionary *map = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1443. if (map && !GPBDictionaryIsInitializedInternalHelper(map, field)) {
  1444. return NO;
  1445. }
  1446. } else {
  1447. // Real type is GPB*ObjectDictionary, exact type doesn't matter.
  1448. GPBInt32ObjectDictionary *map = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1449. if (map && ![map isInitialized]) {
  1450. return NO;
  1451. }
  1452. }
  1453. }
  1454. }
  1455. }
  1456. __block BOOL result = YES;
  1457. [extensionMap_
  1458. enumerateKeysAndObjectsUsingBlock:^(GPBExtensionDescriptor *extension, id obj, BOOL *stop) {
  1459. if (GPBExtensionIsMessage(extension)) {
  1460. if (extension.isRepeated) {
  1461. for (GPBMessage *msg in obj) {
  1462. if (!msg.initialized) {
  1463. result = NO;
  1464. *stop = YES;
  1465. break;
  1466. }
  1467. }
  1468. } else {
  1469. GPBMessage *asMsg = obj;
  1470. if (!asMsg.initialized) {
  1471. result = NO;
  1472. *stop = YES;
  1473. }
  1474. }
  1475. }
  1476. }];
  1477. return result;
  1478. }
  1479. - (GPBDescriptor *)descriptor {
  1480. return [[self class] descriptor];
  1481. }
  1482. - (NSData *)data {
  1483. #if defined(DEBUG) && DEBUG
  1484. if (!self.initialized) {
  1485. return nil;
  1486. }
  1487. #endif
  1488. size_t expectedSize = [self serializedSize];
  1489. if (expectedSize > kMaximumMessageSize) {
  1490. return nil;
  1491. }
  1492. NSMutableData *data = [NSMutableData dataWithLength:expectedSize];
  1493. GPBCodedOutputStream *stream = [[GPBCodedOutputStream alloc] initWithData:data];
  1494. @try {
  1495. [self writeToCodedOutputStream:stream];
  1496. [stream flush];
  1497. } @catch (NSException *exception) {
  1498. // This really shouldn't happen. Normally, this could mean there was a bug in the library and it
  1499. // failed to match between computing the size and writing out the bytes. However, the more
  1500. // common cause is while one thread was writing out the data, some other thread had a reference
  1501. // to this message or a message used as a nested field, and that other thread mutated that
  1502. // message, causing the pre computed serializedSize to no longer match the final size after
  1503. // serialization. It is not safe to mutate a message while accessing it from another thread.
  1504. #if defined(DEBUG) && DEBUG
  1505. NSLog(@"%@: Internal exception while building message data: %@", [self class], exception);
  1506. #endif
  1507. data = nil;
  1508. }
  1509. #if defined(DEBUG) && DEBUG
  1510. NSAssert(!data || [stream bytesWritten] == expectedSize, @"Internal error within the library");
  1511. #endif
  1512. [stream release];
  1513. return data;
  1514. }
  1515. - (NSData *)delimitedData {
  1516. size_t serializedSize = [self serializedSize];
  1517. size_t varintSize = GPBComputeRawVarint32SizeForInteger(serializedSize);
  1518. NSMutableData *data = [NSMutableData dataWithLength:(serializedSize + varintSize)];
  1519. GPBCodedOutputStream *stream = [[GPBCodedOutputStream alloc] initWithData:data];
  1520. @try {
  1521. [self writeDelimitedToCodedOutputStream:stream];
  1522. [stream flush];
  1523. } @catch (NSException *exception) {
  1524. // This really shouldn't happen. Normally, this could mean there was a bug in the library and it
  1525. // failed to match between computing the size and writing out the bytes. However, the more
  1526. // common cause is while one thread was writing out the data, some other thread had a reference
  1527. // to this message or a message used as a nested field, and that other thread mutated that
  1528. // message, causing the pre computed serializedSize to no longer match the final size after
  1529. // serialization. It is not safe to mutate a message while accessing it from another thread.
  1530. #if defined(DEBUG) && DEBUG
  1531. NSLog(@"%@: Internal exception while building message delimitedData: %@", [self class],
  1532. exception);
  1533. #endif
  1534. // If it happens, return an empty data.
  1535. [stream release];
  1536. return [NSData data];
  1537. }
  1538. [stream release];
  1539. return data;
  1540. }
  1541. - (void)writeToOutputStream:(NSOutputStream *)output {
  1542. GPBCodedOutputStream *stream = [[GPBCodedOutputStream alloc] initWithOutputStream:output];
  1543. @try {
  1544. [self writeToCodedOutputStream:stream];
  1545. [stream flush];
  1546. size_t bytesWritten = [stream bytesWritten];
  1547. if (bytesWritten > kMaximumMessageSize) {
  1548. [NSException raise:GPBMessageExceptionMessageTooLarge
  1549. format:@"Message would have been %zu bytes", bytesWritten];
  1550. }
  1551. } @finally {
  1552. [stream release];
  1553. }
  1554. }
  1555. - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output {
  1556. GPBDescriptor *descriptor = [self descriptor];
  1557. NSArray *fieldsArray = descriptor->fields_;
  1558. NSUInteger fieldCount = fieldsArray.count;
  1559. const GPBExtensionRange *extensionRanges = descriptor.extensionRanges;
  1560. NSUInteger extensionRangesCount = descriptor.extensionRangesCount;
  1561. NSArray *sortedExtensions =
  1562. [[extensionMap_ allKeys] sortedArrayUsingSelector:@selector(compareByFieldNumber:)];
  1563. for (NSUInteger i = 0, j = 0; i < fieldCount || j < extensionRangesCount;) {
  1564. if (i == fieldCount) {
  1565. [self writeExtensionsToCodedOutputStream:output
  1566. range:extensionRanges[j++]
  1567. sortedExtensions:sortedExtensions];
  1568. } else if (j == extensionRangesCount ||
  1569. GPBFieldNumber(fieldsArray[i]) < extensionRanges[j].start) {
  1570. [self writeField:fieldsArray[i++] toCodedOutputStream:output];
  1571. } else {
  1572. [self writeExtensionsToCodedOutputStream:output
  1573. range:extensionRanges[j++]
  1574. sortedExtensions:sortedExtensions];
  1575. }
  1576. }
  1577. @synchronized(self) {
  1578. if (unknownFieldData_) {
  1579. #if defined(DEBUG) && DEBUG
  1580. NSAssert(unknownFields_ == nil, @"Internal error both unknown states were set");
  1581. #endif
  1582. [output writeRawData:unknownFieldData_];
  1583. } else {
  1584. if (descriptor.isWireFormat) {
  1585. [unknownFields_ writeAsMessageSetTo:output];
  1586. } else {
  1587. [unknownFields_ writeToCodedOutputStream:output];
  1588. }
  1589. }
  1590. } // @synchronized(self)
  1591. }
  1592. - (void)writeDelimitedToOutputStream:(NSOutputStream *)output {
  1593. GPBCodedOutputStream *codedOutput = [[GPBCodedOutputStream alloc] initWithOutputStream:output];
  1594. @try {
  1595. [self writeDelimitedToCodedOutputStream:codedOutput];
  1596. [codedOutput flush];
  1597. } @finally {
  1598. [codedOutput release];
  1599. }
  1600. }
  1601. - (void)writeDelimitedToCodedOutputStream:(GPBCodedOutputStream *)output {
  1602. size_t expectedSize = [self serializedSize];
  1603. if (expectedSize > kMaximumMessageSize) {
  1604. [NSException raise:GPBMessageExceptionMessageTooLarge
  1605. format:@"Message would have been %zu bytes", expectedSize];
  1606. }
  1607. [output writeRawVarintSizeTAs32:expectedSize];
  1608. #if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS)
  1609. size_t initialSize = [output bytesWritten];
  1610. #endif
  1611. [self writeToCodedOutputStream:output];
  1612. #if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS)
  1613. NSAssert(([output bytesWritten] - initialSize) == expectedSize,
  1614. @"Internal error within the library");
  1615. #endif
  1616. }
  1617. - (void)writeField:(GPBFieldDescriptor *)field toCodedOutputStream:(GPBCodedOutputStream *)output {
  1618. GPBFieldType fieldType = field.fieldType;
  1619. if (fieldType == GPBFieldTypeSingle) {
  1620. BOOL has = GPBGetHasIvarField(self, field);
  1621. if (!has) {
  1622. return;
  1623. }
  1624. }
  1625. uint32_t fieldNumber = GPBFieldNumber(field);
  1626. switch (GPBGetFieldDataType(field)) {
  1627. // clang-format off
  1628. //%PDDM-DEFINE FIELD_CASE(TYPE, REAL_TYPE)
  1629. //%FIELD_CASE_FULL(TYPE, REAL_TYPE, REAL_TYPE)
  1630. //%PDDM-DEFINE FIELD_CASE_FULL(TYPE, REAL_TYPE, ARRAY_TYPE)
  1631. //% case GPBDataType##TYPE:
  1632. //% if (fieldType == GPBFieldTypeRepeated) {
  1633. //% uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1634. //% GPB##ARRAY_TYPE##Array *array =
  1635. //% GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1636. //% [output write##TYPE##Array:fieldNumber values:array tag:tag];
  1637. //% } else if (fieldType == GPBFieldTypeSingle) {
  1638. //% [output write##TYPE:fieldNumber
  1639. //% TYPE$S value:GPBGetMessage##REAL_TYPE##Field(self, field)];
  1640. //% } else { // fieldType == GPBFieldTypeMap
  1641. //% // Exact type here doesn't matter.
  1642. //% GPBInt32##ARRAY_TYPE##Dictionary *dict =
  1643. //% GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1644. //% [dict writeToCodedOutputStream:output asField:field];
  1645. //% }
  1646. //% break;
  1647. //%
  1648. //%PDDM-DEFINE FIELD_CASE2(TYPE)
  1649. //% case GPBDataType##TYPE:
  1650. //% if (fieldType == GPBFieldTypeRepeated) {
  1651. //% NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1652. //% [output write##TYPE##Array:fieldNumber values:array];
  1653. //% } else if (fieldType == GPBFieldTypeSingle) {
  1654. //% // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1655. //% // again.
  1656. //% [output write##TYPE:fieldNumber
  1657. //% TYPE$S value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1658. //% } else { // fieldType == GPBFieldTypeMap
  1659. //% // Exact type here doesn't matter.
  1660. //% id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1661. //% GPBDataType mapKeyDataType = field.mapKeyDataType;
  1662. //% if (mapKeyDataType == GPBDataTypeString) {
  1663. //% GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1664. //% } else {
  1665. //% [dict writeToCodedOutputStream:output asField:field];
  1666. //% }
  1667. //% }
  1668. //% break;
  1669. //%
  1670. //%PDDM-EXPAND FIELD_CASE(Bool, Bool)
  1671. // This block of code is generated, do not edit it directly.
  1672. case GPBDataTypeBool:
  1673. if (fieldType == GPBFieldTypeRepeated) {
  1674. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1675. GPBBoolArray *array =
  1676. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1677. [output writeBoolArray:fieldNumber values:array tag:tag];
  1678. } else if (fieldType == GPBFieldTypeSingle) {
  1679. [output writeBool:fieldNumber
  1680. value:GPBGetMessageBoolField(self, field)];
  1681. } else { // fieldType == GPBFieldTypeMap
  1682. // Exact type here doesn't matter.
  1683. GPBInt32BoolDictionary *dict =
  1684. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1685. [dict writeToCodedOutputStream:output asField:field];
  1686. }
  1687. break;
  1688. //%PDDM-EXPAND FIELD_CASE(Fixed32, UInt32)
  1689. // This block of code is generated, do not edit it directly.
  1690. case GPBDataTypeFixed32:
  1691. if (fieldType == GPBFieldTypeRepeated) {
  1692. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1693. GPBUInt32Array *array =
  1694. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1695. [output writeFixed32Array:fieldNumber values:array tag:tag];
  1696. } else if (fieldType == GPBFieldTypeSingle) {
  1697. [output writeFixed32:fieldNumber
  1698. value:GPBGetMessageUInt32Field(self, field)];
  1699. } else { // fieldType == GPBFieldTypeMap
  1700. // Exact type here doesn't matter.
  1701. GPBInt32UInt32Dictionary *dict =
  1702. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1703. [dict writeToCodedOutputStream:output asField:field];
  1704. }
  1705. break;
  1706. //%PDDM-EXPAND FIELD_CASE(SFixed32, Int32)
  1707. // This block of code is generated, do not edit it directly.
  1708. case GPBDataTypeSFixed32:
  1709. if (fieldType == GPBFieldTypeRepeated) {
  1710. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1711. GPBInt32Array *array =
  1712. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1713. [output writeSFixed32Array:fieldNumber values:array tag:tag];
  1714. } else if (fieldType == GPBFieldTypeSingle) {
  1715. [output writeSFixed32:fieldNumber
  1716. value:GPBGetMessageInt32Field(self, field)];
  1717. } else { // fieldType == GPBFieldTypeMap
  1718. // Exact type here doesn't matter.
  1719. GPBInt32Int32Dictionary *dict =
  1720. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1721. [dict writeToCodedOutputStream:output asField:field];
  1722. }
  1723. break;
  1724. //%PDDM-EXPAND FIELD_CASE(Float, Float)
  1725. // This block of code is generated, do not edit it directly.
  1726. case GPBDataTypeFloat:
  1727. if (fieldType == GPBFieldTypeRepeated) {
  1728. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1729. GPBFloatArray *array =
  1730. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1731. [output writeFloatArray:fieldNumber values:array tag:tag];
  1732. } else if (fieldType == GPBFieldTypeSingle) {
  1733. [output writeFloat:fieldNumber
  1734. value:GPBGetMessageFloatField(self, field)];
  1735. } else { // fieldType == GPBFieldTypeMap
  1736. // Exact type here doesn't matter.
  1737. GPBInt32FloatDictionary *dict =
  1738. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1739. [dict writeToCodedOutputStream:output asField:field];
  1740. }
  1741. break;
  1742. //%PDDM-EXPAND FIELD_CASE(Fixed64, UInt64)
  1743. // This block of code is generated, do not edit it directly.
  1744. case GPBDataTypeFixed64:
  1745. if (fieldType == GPBFieldTypeRepeated) {
  1746. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1747. GPBUInt64Array *array =
  1748. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1749. [output writeFixed64Array:fieldNumber values:array tag:tag];
  1750. } else if (fieldType == GPBFieldTypeSingle) {
  1751. [output writeFixed64:fieldNumber
  1752. value:GPBGetMessageUInt64Field(self, field)];
  1753. } else { // fieldType == GPBFieldTypeMap
  1754. // Exact type here doesn't matter.
  1755. GPBInt32UInt64Dictionary *dict =
  1756. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1757. [dict writeToCodedOutputStream:output asField:field];
  1758. }
  1759. break;
  1760. //%PDDM-EXPAND FIELD_CASE(SFixed64, Int64)
  1761. // This block of code is generated, do not edit it directly.
  1762. case GPBDataTypeSFixed64:
  1763. if (fieldType == GPBFieldTypeRepeated) {
  1764. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1765. GPBInt64Array *array =
  1766. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1767. [output writeSFixed64Array:fieldNumber values:array tag:tag];
  1768. } else if (fieldType == GPBFieldTypeSingle) {
  1769. [output writeSFixed64:fieldNumber
  1770. value:GPBGetMessageInt64Field(self, field)];
  1771. } else { // fieldType == GPBFieldTypeMap
  1772. // Exact type here doesn't matter.
  1773. GPBInt32Int64Dictionary *dict =
  1774. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1775. [dict writeToCodedOutputStream:output asField:field];
  1776. }
  1777. break;
  1778. //%PDDM-EXPAND FIELD_CASE(Double, Double)
  1779. // This block of code is generated, do not edit it directly.
  1780. case GPBDataTypeDouble:
  1781. if (fieldType == GPBFieldTypeRepeated) {
  1782. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1783. GPBDoubleArray *array =
  1784. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1785. [output writeDoubleArray:fieldNumber values:array tag:tag];
  1786. } else if (fieldType == GPBFieldTypeSingle) {
  1787. [output writeDouble:fieldNumber
  1788. value:GPBGetMessageDoubleField(self, field)];
  1789. } else { // fieldType == GPBFieldTypeMap
  1790. // Exact type here doesn't matter.
  1791. GPBInt32DoubleDictionary *dict =
  1792. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1793. [dict writeToCodedOutputStream:output asField:field];
  1794. }
  1795. break;
  1796. //%PDDM-EXPAND FIELD_CASE(Int32, Int32)
  1797. // This block of code is generated, do not edit it directly.
  1798. case GPBDataTypeInt32:
  1799. if (fieldType == GPBFieldTypeRepeated) {
  1800. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1801. GPBInt32Array *array =
  1802. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1803. [output writeInt32Array:fieldNumber values:array tag:tag];
  1804. } else if (fieldType == GPBFieldTypeSingle) {
  1805. [output writeInt32:fieldNumber
  1806. value:GPBGetMessageInt32Field(self, field)];
  1807. } else { // fieldType == GPBFieldTypeMap
  1808. // Exact type here doesn't matter.
  1809. GPBInt32Int32Dictionary *dict =
  1810. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1811. [dict writeToCodedOutputStream:output asField:field];
  1812. }
  1813. break;
  1814. //%PDDM-EXPAND FIELD_CASE(Int64, Int64)
  1815. // This block of code is generated, do not edit it directly.
  1816. case GPBDataTypeInt64:
  1817. if (fieldType == GPBFieldTypeRepeated) {
  1818. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1819. GPBInt64Array *array =
  1820. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1821. [output writeInt64Array:fieldNumber values:array tag:tag];
  1822. } else if (fieldType == GPBFieldTypeSingle) {
  1823. [output writeInt64:fieldNumber
  1824. value:GPBGetMessageInt64Field(self, field)];
  1825. } else { // fieldType == GPBFieldTypeMap
  1826. // Exact type here doesn't matter.
  1827. GPBInt32Int64Dictionary *dict =
  1828. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1829. [dict writeToCodedOutputStream:output asField:field];
  1830. }
  1831. break;
  1832. //%PDDM-EXPAND FIELD_CASE(SInt32, Int32)
  1833. // This block of code is generated, do not edit it directly.
  1834. case GPBDataTypeSInt32:
  1835. if (fieldType == GPBFieldTypeRepeated) {
  1836. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1837. GPBInt32Array *array =
  1838. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1839. [output writeSInt32Array:fieldNumber values:array tag:tag];
  1840. } else if (fieldType == GPBFieldTypeSingle) {
  1841. [output writeSInt32:fieldNumber
  1842. value:GPBGetMessageInt32Field(self, field)];
  1843. } else { // fieldType == GPBFieldTypeMap
  1844. // Exact type here doesn't matter.
  1845. GPBInt32Int32Dictionary *dict =
  1846. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1847. [dict writeToCodedOutputStream:output asField:field];
  1848. }
  1849. break;
  1850. //%PDDM-EXPAND FIELD_CASE(SInt64, Int64)
  1851. // This block of code is generated, do not edit it directly.
  1852. case GPBDataTypeSInt64:
  1853. if (fieldType == GPBFieldTypeRepeated) {
  1854. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1855. GPBInt64Array *array =
  1856. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1857. [output writeSInt64Array:fieldNumber values:array tag:tag];
  1858. } else if (fieldType == GPBFieldTypeSingle) {
  1859. [output writeSInt64:fieldNumber
  1860. value:GPBGetMessageInt64Field(self, field)];
  1861. } else { // fieldType == GPBFieldTypeMap
  1862. // Exact type here doesn't matter.
  1863. GPBInt32Int64Dictionary *dict =
  1864. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1865. [dict writeToCodedOutputStream:output asField:field];
  1866. }
  1867. break;
  1868. //%PDDM-EXPAND FIELD_CASE(UInt32, UInt32)
  1869. // This block of code is generated, do not edit it directly.
  1870. case GPBDataTypeUInt32:
  1871. if (fieldType == GPBFieldTypeRepeated) {
  1872. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1873. GPBUInt32Array *array =
  1874. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1875. [output writeUInt32Array:fieldNumber values:array tag:tag];
  1876. } else if (fieldType == GPBFieldTypeSingle) {
  1877. [output writeUInt32:fieldNumber
  1878. value:GPBGetMessageUInt32Field(self, field)];
  1879. } else { // fieldType == GPBFieldTypeMap
  1880. // Exact type here doesn't matter.
  1881. GPBInt32UInt32Dictionary *dict =
  1882. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1883. [dict writeToCodedOutputStream:output asField:field];
  1884. }
  1885. break;
  1886. //%PDDM-EXPAND FIELD_CASE(UInt64, UInt64)
  1887. // This block of code is generated, do not edit it directly.
  1888. case GPBDataTypeUInt64:
  1889. if (fieldType == GPBFieldTypeRepeated) {
  1890. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1891. GPBUInt64Array *array =
  1892. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1893. [output writeUInt64Array:fieldNumber values:array tag:tag];
  1894. } else if (fieldType == GPBFieldTypeSingle) {
  1895. [output writeUInt64:fieldNumber
  1896. value:GPBGetMessageUInt64Field(self, field)];
  1897. } else { // fieldType == GPBFieldTypeMap
  1898. // Exact type here doesn't matter.
  1899. GPBInt32UInt64Dictionary *dict =
  1900. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1901. [dict writeToCodedOutputStream:output asField:field];
  1902. }
  1903. break;
  1904. //%PDDM-EXPAND FIELD_CASE_FULL(Enum, Int32, Enum)
  1905. // This block of code is generated, do not edit it directly.
  1906. case GPBDataTypeEnum:
  1907. if (fieldType == GPBFieldTypeRepeated) {
  1908. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1909. GPBEnumArray *array =
  1910. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1911. [output writeEnumArray:fieldNumber values:array tag:tag];
  1912. } else if (fieldType == GPBFieldTypeSingle) {
  1913. [output writeEnum:fieldNumber
  1914. value:GPBGetMessageInt32Field(self, field)];
  1915. } else { // fieldType == GPBFieldTypeMap
  1916. // Exact type here doesn't matter.
  1917. GPBInt32EnumDictionary *dict =
  1918. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1919. [dict writeToCodedOutputStream:output asField:field];
  1920. }
  1921. break;
  1922. //%PDDM-EXPAND FIELD_CASE2(Bytes)
  1923. // This block of code is generated, do not edit it directly.
  1924. case GPBDataTypeBytes:
  1925. if (fieldType == GPBFieldTypeRepeated) {
  1926. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1927. [output writeBytesArray:fieldNumber values:array];
  1928. } else if (fieldType == GPBFieldTypeSingle) {
  1929. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1930. // again.
  1931. [output writeBytes:fieldNumber
  1932. value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1933. } else { // fieldType == GPBFieldTypeMap
  1934. // Exact type here doesn't matter.
  1935. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1936. GPBDataType mapKeyDataType = field.mapKeyDataType;
  1937. if (mapKeyDataType == GPBDataTypeString) {
  1938. GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1939. } else {
  1940. [dict writeToCodedOutputStream:output asField:field];
  1941. }
  1942. }
  1943. break;
  1944. //%PDDM-EXPAND FIELD_CASE2(String)
  1945. // This block of code is generated, do not edit it directly.
  1946. case GPBDataTypeString:
  1947. if (fieldType == GPBFieldTypeRepeated) {
  1948. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1949. [output writeStringArray:fieldNumber values:array];
  1950. } else if (fieldType == GPBFieldTypeSingle) {
  1951. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1952. // again.
  1953. [output writeString:fieldNumber
  1954. value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1955. } else { // fieldType == GPBFieldTypeMap
  1956. // Exact type here doesn't matter.
  1957. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1958. GPBDataType mapKeyDataType = field.mapKeyDataType;
  1959. if (mapKeyDataType == GPBDataTypeString) {
  1960. GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1961. } else {
  1962. [dict writeToCodedOutputStream:output asField:field];
  1963. }
  1964. }
  1965. break;
  1966. //%PDDM-EXPAND FIELD_CASE2(Message)
  1967. // This block of code is generated, do not edit it directly.
  1968. case GPBDataTypeMessage:
  1969. if (fieldType == GPBFieldTypeRepeated) {
  1970. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1971. [output writeMessageArray:fieldNumber values:array];
  1972. } else if (fieldType == GPBFieldTypeSingle) {
  1973. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1974. // again.
  1975. [output writeMessage:fieldNumber
  1976. value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1977. } else { // fieldType == GPBFieldTypeMap
  1978. // Exact type here doesn't matter.
  1979. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1980. GPBDataType mapKeyDataType = field.mapKeyDataType;
  1981. if (mapKeyDataType == GPBDataTypeString) {
  1982. GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1983. } else {
  1984. [dict writeToCodedOutputStream:output asField:field];
  1985. }
  1986. }
  1987. break;
  1988. //%PDDM-EXPAND FIELD_CASE2(Group)
  1989. // This block of code is generated, do not edit it directly.
  1990. case GPBDataTypeGroup:
  1991. if (fieldType == GPBFieldTypeRepeated) {
  1992. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1993. [output writeGroupArray:fieldNumber values:array];
  1994. } else if (fieldType == GPBFieldTypeSingle) {
  1995. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1996. // again.
  1997. [output writeGroup:fieldNumber
  1998. value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1999. } else { // fieldType == GPBFieldTypeMap
  2000. // Exact type here doesn't matter.
  2001. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  2002. GPBDataType mapKeyDataType = field.mapKeyDataType;
  2003. if (mapKeyDataType == GPBDataTypeString) {
  2004. GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  2005. } else {
  2006. [dict writeToCodedOutputStream:output asField:field];
  2007. }
  2008. }
  2009. break;
  2010. //%PDDM-EXPAND-END (18 expansions)
  2011. // clang-format on
  2012. }
  2013. }
  2014. #pragma mark - Extensions
  2015. - (id)getExtension:(GPBExtensionDescriptor *)extension {
  2016. CheckExtension(self, extension);
  2017. id value = [extensionMap_ objectForKey:extension];
  2018. if (value != nil) {
  2019. return value;
  2020. }
  2021. // No default for repeated.
  2022. if (extension.isRepeated) {
  2023. return nil;
  2024. }
  2025. // Non messages get their default.
  2026. if (!GPBExtensionIsMessage(extension)) {
  2027. return extension.defaultValue;
  2028. }
  2029. // Check for an autocreated value.
  2030. os_unfair_lock_lock(&readOnlyLock_);
  2031. value = [autocreatedExtensionMap_ objectForKey:extension];
  2032. if (!value) {
  2033. // Auto create the message extensions to match normal fields.
  2034. value = CreateMessageWithAutocreatorForExtension(extension.msgClass, self, extension);
  2035. if (autocreatedExtensionMap_ == nil) {
  2036. autocreatedExtensionMap_ = [[NSMutableDictionary alloc] init];
  2037. }
  2038. // We can't simply call setExtension here because that would clear the new
  2039. // value's autocreator.
  2040. [autocreatedExtensionMap_ setObject:value forKey:extension];
  2041. [value release];
  2042. }
  2043. os_unfair_lock_unlock(&readOnlyLock_);
  2044. return value;
  2045. }
  2046. - (id)getExistingExtension:(GPBExtensionDescriptor *)extension {
  2047. // This is an internal method so we don't need to call CheckExtension().
  2048. return [extensionMap_ objectForKey:extension];
  2049. }
  2050. - (BOOL)hasExtension:(GPBExtensionDescriptor *)extension {
  2051. #if defined(DEBUG) && DEBUG
  2052. CheckExtension(self, extension);
  2053. #endif // DEBUG
  2054. return nil != [extensionMap_ objectForKey:extension];
  2055. }
  2056. - (NSArray *)extensionsCurrentlySet {
  2057. return [extensionMap_ allKeys];
  2058. }
  2059. - (void)writeExtensionsToCodedOutputStream:(GPBCodedOutputStream *)output
  2060. range:(GPBExtensionRange)range
  2061. sortedExtensions:(NSArray *)sortedExtensions {
  2062. uint32_t start = range.start;
  2063. uint32_t end = range.end;
  2064. for (GPBExtensionDescriptor *extension in sortedExtensions) {
  2065. uint32_t fieldNumber = extension.fieldNumber;
  2066. if (fieldNumber < start) {
  2067. continue;
  2068. }
  2069. if (fieldNumber >= end) {
  2070. break;
  2071. }
  2072. id value = [extensionMap_ objectForKey:extension];
  2073. GPBWriteExtensionValueToOutputStream(extension, value, output);
  2074. }
  2075. }
  2076. - (void)setExtension:(GPBExtensionDescriptor *)extension value:(id)value {
  2077. if (!value) {
  2078. [self clearExtension:extension];
  2079. return;
  2080. }
  2081. CheckExtension(self, extension);
  2082. if (extension.repeated) {
  2083. [NSException raise:NSInvalidArgumentException
  2084. format:@"Must call addExtension() for repeated types."];
  2085. }
  2086. if (extensionMap_ == nil) {
  2087. extensionMap_ = [[NSMutableDictionary alloc] init];
  2088. }
  2089. // This pointless cast is for CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION.
  2090. // Without it, the compiler complains we're passing an id nullable when
  2091. // setObject:forKey: requires a id nonnull for the value. The check for
  2092. // !value at the start of the method ensures it isn't nil, but the check
  2093. // isn't smart enough to realize that.
  2094. [extensionMap_ setObject:(id)value forKey:extension];
  2095. GPBExtensionDescriptor *descriptor = extension;
  2096. if (GPBExtensionIsMessage(descriptor) && !descriptor.isRepeated) {
  2097. GPBMessage *autocreatedValue = [[autocreatedExtensionMap_ objectForKey:extension] retain];
  2098. // Must remove from the map before calling GPBClearMessageAutocreator() so
  2099. // that GPBClearMessageAutocreator() knows its safe to clear.
  2100. [autocreatedExtensionMap_ removeObjectForKey:extension];
  2101. GPBClearMessageAutocreator(autocreatedValue);
  2102. [autocreatedValue release];
  2103. }
  2104. GPBBecomeVisibleToAutocreator(self);
  2105. }
  2106. - (void)addExtension:(GPBExtensionDescriptor *)extension value:(id)value {
  2107. CheckExtension(self, extension);
  2108. if (!extension.repeated) {
  2109. [NSException raise:NSInvalidArgumentException
  2110. format:@"Must call setExtension() for singular types."];
  2111. }
  2112. if (extensionMap_ == nil) {
  2113. extensionMap_ = [[NSMutableDictionary alloc] init];
  2114. }
  2115. NSMutableArray *list = [extensionMap_ objectForKey:extension];
  2116. if (list == nil) {
  2117. list = [NSMutableArray array];
  2118. [extensionMap_ setObject:list forKey:extension];
  2119. }
  2120. [list addObject:value];
  2121. GPBBecomeVisibleToAutocreator(self);
  2122. }
  2123. - (void)setExtension:(GPBExtensionDescriptor *)extension index:(NSUInteger)idx value:(id)value {
  2124. CheckExtension(self, extension);
  2125. if (!extension.repeated) {
  2126. [NSException raise:NSInvalidArgumentException
  2127. format:@"Must call setExtension() for singular types."];
  2128. }
  2129. if (extensionMap_ == nil) {
  2130. extensionMap_ = [[NSMutableDictionary alloc] init];
  2131. }
  2132. NSMutableArray *list = [extensionMap_ objectForKey:extension];
  2133. [list replaceObjectAtIndex:idx withObject:value];
  2134. GPBBecomeVisibleToAutocreator(self);
  2135. }
  2136. - (void)clearExtension:(GPBExtensionDescriptor *)extension {
  2137. CheckExtension(self, extension);
  2138. // Only become visible if there was actually a value to clear.
  2139. if ([extensionMap_ objectForKey:extension]) {
  2140. [extensionMap_ removeObjectForKey:extension];
  2141. GPBBecomeVisibleToAutocreator(self);
  2142. }
  2143. }
  2144. #pragma mark - mergeFrom
  2145. - (void)mergeFromData:(NSData *)data extensionRegistry:(id<GPBExtensionRegistry>)extensionRegistry {
  2146. GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data];
  2147. @try {
  2148. [self mergeFromCodedInputStream:input extensionRegistry:extensionRegistry endingTag:0];
  2149. } @finally {
  2150. [input release];
  2151. }
  2152. }
  2153. - (BOOL)mergeFromData:(NSData *)data
  2154. extensionRegistry:(nullable id<GPBExtensionRegistry>)extensionRegistry
  2155. error:(NSError **)errorPtr {
  2156. GPBBecomeVisibleToAutocreator(self);
  2157. GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data];
  2158. @try {
  2159. [self mergeFromCodedInputStream:input extensionRegistry:extensionRegistry endingTag:0];
  2160. [input checkLastTagWas:0];
  2161. if (errorPtr) {
  2162. *errorPtr = nil;
  2163. }
  2164. } @catch (NSException *exception) {
  2165. [input release];
  2166. if (errorPtr) {
  2167. *errorPtr = ErrorFromException(exception);
  2168. }
  2169. return NO;
  2170. }
  2171. [input release];
  2172. return YES;
  2173. }
  2174. #pragma mark - Parse From Data Support
  2175. + (instancetype)parseFromData:(NSData *)data error:(NSError **)errorPtr {
  2176. return [self parseFromData:data extensionRegistry:nil error:errorPtr];
  2177. }
  2178. + (instancetype)parseFromData:(NSData *)data
  2179. extensionRegistry:(id<GPBExtensionRegistry>)extensionRegistry
  2180. error:(NSError **)errorPtr {
  2181. return [[[self alloc] initWithData:data extensionRegistry:extensionRegistry
  2182. error:errorPtr] autorelease];
  2183. }
  2184. + (instancetype)parseFromCodedInputStream:(GPBCodedInputStream *)input
  2185. extensionRegistry:(id<GPBExtensionRegistry>)extensionRegistry
  2186. error:(NSError **)errorPtr {
  2187. return [[[self alloc] initWithCodedInputStream:input
  2188. extensionRegistry:extensionRegistry
  2189. error:errorPtr] autorelease];
  2190. }
  2191. #pragma mark - Parse Delimited From Data Support
  2192. + (instancetype)parseDelimitedFromCodedInputStream:(GPBCodedInputStream *)input
  2193. extensionRegistry:(id<GPBExtensionRegistry>)extensionRegistry
  2194. error:(NSError **)errorPtr {
  2195. GPBCodedInputStreamState *state = &input->state_;
  2196. // This doesn't completely match the C++, but if the stream has nothing, just make an empty
  2197. // message.
  2198. if (GPBCodedInputStreamIsAtEnd(state)) {
  2199. return [[[self alloc] init] autorelease];
  2200. }
  2201. // Manually extract the data and parse it. If we read a varint and push a limit, that consumes
  2202. // some of the recursion buffer which isn't correct, it also can result in a change in error
  2203. // codes for attempts to parse partial data; and there are projects sensitive to that, so this
  2204. // maintains existing error flows.
  2205. // Extract the data, but in a "no copy" mode since we will immediately parse it so this NSData
  2206. // is transient.
  2207. NSData *data = nil;
  2208. @try {
  2209. data = GPBCodedInputStreamReadRetainedBytesNoCopy(state);
  2210. } @catch (NSException *exception) {
  2211. if (errorPtr) {
  2212. *errorPtr = ErrorFromException(exception);
  2213. }
  2214. return nil;
  2215. }
  2216. GPBMessage *result = [self parseFromData:data extensionRegistry:extensionRegistry error:errorPtr];
  2217. [data release];
  2218. if (result && errorPtr) {
  2219. *errorPtr = nil;
  2220. }
  2221. return result;
  2222. }
  2223. #pragma mark - Unknown Field Support
  2224. - (GPBUnknownFieldSet *)unknownFields {
  2225. @synchronized(self) {
  2226. if (unknownFieldData_) {
  2227. #if defined(DEBUG) && DEBUG
  2228. NSAssert(unknownFields_ == nil, @"Internal error both unknown states were set");
  2229. #endif
  2230. unknownFields_ = [[GPBUnknownFieldSet alloc] init];
  2231. MergeUnknownFieldDataIntoFieldSet(self, unknownFieldData_, nil);
  2232. [unknownFieldData_ release];
  2233. unknownFieldData_ = nil;
  2234. }
  2235. return unknownFields_;
  2236. } // @synchronized(self)
  2237. }
  2238. - (void)setUnknownFields:(GPBUnknownFieldSet *)unknownFields {
  2239. if (unknownFields != unknownFields_ || unknownFieldData_ != nil) {
  2240. // Changing sets or clearing.
  2241. [unknownFieldData_ release];
  2242. unknownFieldData_ = nil;
  2243. [unknownFields_ release];
  2244. unknownFields_ = [unknownFields copy];
  2245. GPBBecomeVisibleToAutocreator(self);
  2246. }
  2247. }
  2248. - (void)parseMessageSet:(GPBCodedInputStream *)input
  2249. extensionRegistry:(id<GPBExtensionRegistry>)extensionRegistry {
  2250. uint32_t typeId = 0;
  2251. NSData *rawBytes = nil;
  2252. GPBCodedInputStreamState *state = &input->state_;
  2253. BOOL gotType = NO;
  2254. BOOL gotBytes = NO;
  2255. while (true) {
  2256. uint32_t tag = GPBCodedInputStreamReadTag(state);
  2257. if (tag == GPBWireFormatMessageSetItemEndTag || tag == 0) {
  2258. break;
  2259. }
  2260. if (tag == GPBWireFormatMessageSetTypeIdTag) {
  2261. uint32_t tmp = GPBCodedInputStreamReadUInt32(state);
  2262. // Spec says only use the first value.
  2263. if (!gotType) {
  2264. gotType = YES;
  2265. typeId = tmp;
  2266. }
  2267. } else if (tag == GPBWireFormatMessageSetMessageTag) {
  2268. if (gotBytes) {
  2269. // Skip over the payload instead of collecting it.
  2270. [input skipField:tag];
  2271. } else {
  2272. rawBytes = [GPBCodedInputStreamReadRetainedBytesNoCopy(state) autorelease];
  2273. gotBytes = YES;
  2274. }
  2275. } else {
  2276. // Don't capture unknowns within the message set impl group.
  2277. if (![input skipField:tag]) {
  2278. break;
  2279. }
  2280. }
  2281. }
  2282. // If we get here because of end of input (tag zero) or the wrong end tag (within the skipField:),
  2283. // this will error.
  2284. GPBCodedInputStreamCheckLastTagWas(state, GPBWireFormatMessageSetItemEndTag);
  2285. if (!gotType || !gotBytes) {
  2286. // upb_Decoder_DecodeMessageSetItem does't keep this partial as an unknown field, it just drops
  2287. // it, so do the same thing.
  2288. return;
  2289. }
  2290. GPBExtensionDescriptor *extension = [extensionRegistry extensionForDescriptor:[self descriptor]
  2291. fieldNumber:typeId];
  2292. if (extension) {
  2293. #if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS)
  2294. NSAssert(extension.dataType == GPBDataTypeMessage,
  2295. @"Internal Error: MessageSet extension must be a message field.");
  2296. NSAssert(GPBExtensionIsWireFormat(extension->description_),
  2297. @"Internal Error: MessageSet extension must have message_set_wire_format set.");
  2298. NSAssert(!GPBExtensionIsRepeated(extension->description_),
  2299. @"Internal Error: MessageSet extension can't be repeated.");
  2300. #endif
  2301. // Look up the existing one to merge to or create a new one.
  2302. GPBMessage *targetMessage = [self getExistingExtension:extension];
  2303. if (!targetMessage) {
  2304. GPBDescriptor *descriptor = [extension.msgClass descriptor];
  2305. targetMessage = [[descriptor.messageClass alloc] init];
  2306. [self setExtension:extension value:targetMessage];
  2307. [targetMessage release];
  2308. }
  2309. GPBCodedInputStream *newInput = [[GPBCodedInputStream alloc] initWithData:rawBytes];
  2310. @try {
  2311. [targetMessage mergeFromCodedInputStream:newInput
  2312. extensionRegistry:extensionRegistry
  2313. endingTag:0];
  2314. } @finally {
  2315. [newInput release];
  2316. }
  2317. } else {
  2318. // The extension isn't in the registry, but it was well formed, so the whole group structure
  2319. // get preserved as an unknown field.
  2320. // rawBytes was created via a NoCopy, so it can be reusing a
  2321. // subrange of another NSData that might go out of scope as things
  2322. // unwind, so a copy is needed to ensure what is saved in the
  2323. // unknown fields stays valid.
  2324. NSData *cloned = [NSData dataWithData:rawBytes];
  2325. AddUnknownMessageSetEntry(self, typeId, cloned);
  2326. }
  2327. }
  2328. - (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data {
  2329. AddUnknownFieldLengthDelimited(self, fieldNum, data);
  2330. }
  2331. #pragma mark - MergeFromCodedInputStream Support
  2332. static void MergeSingleFieldFromCodedInputStream(GPBMessage *self, GPBFieldDescriptor *field,
  2333. GPBCodedInputStream *input,
  2334. id<GPBExtensionRegistry> extensionRegistry) {
  2335. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2336. switch (fieldDataType) {
  2337. #define CASE_SINGLE_POD(NAME, TYPE, FUNC_TYPE) \
  2338. case GPBDataType##NAME: { \
  2339. TYPE val = GPBCodedInputStreamRead##NAME(&input->state_); \
  2340. GPBSet##FUNC_TYPE##IvarWithFieldPrivate(self, field, val); \
  2341. break; \
  2342. }
  2343. #define CASE_SINGLE_OBJECT(NAME) \
  2344. case GPBDataType##NAME: { \
  2345. id val = GPBCodedInputStreamReadRetained##NAME(&input->state_); \
  2346. GPBSetRetainedObjectIvarWithFieldPrivate(self, field, val); \
  2347. break; \
  2348. }
  2349. CASE_SINGLE_POD(Bool, BOOL, Bool)
  2350. CASE_SINGLE_POD(Fixed32, uint32_t, UInt32)
  2351. CASE_SINGLE_POD(SFixed32, int32_t, Int32)
  2352. CASE_SINGLE_POD(Float, float, Float)
  2353. CASE_SINGLE_POD(Fixed64, uint64_t, UInt64)
  2354. CASE_SINGLE_POD(SFixed64, int64_t, Int64)
  2355. CASE_SINGLE_POD(Double, double, Double)
  2356. CASE_SINGLE_POD(Int32, int32_t, Int32)
  2357. CASE_SINGLE_POD(Int64, int64_t, Int64)
  2358. CASE_SINGLE_POD(SInt32, int32_t, Int32)
  2359. CASE_SINGLE_POD(SInt64, int64_t, Int64)
  2360. CASE_SINGLE_POD(UInt32, uint32_t, UInt32)
  2361. CASE_SINGLE_POD(UInt64, uint64_t, UInt64)
  2362. CASE_SINGLE_OBJECT(Bytes)
  2363. CASE_SINGLE_OBJECT(String)
  2364. #undef CASE_SINGLE_POD
  2365. #undef CASE_SINGLE_OBJECT
  2366. case GPBDataTypeMessage: {
  2367. if (GPBGetHasIvarField(self, field)) {
  2368. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has
  2369. // check again.
  2370. GPBMessage *message = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  2371. [input readMessage:message extensionRegistry:extensionRegistry];
  2372. } else {
  2373. GPBMessage *message = [[field.msgClass alloc] init];
  2374. GPBSetRetainedObjectIvarWithFieldPrivate(self, field, message);
  2375. [input readMessage:message extensionRegistry:extensionRegistry];
  2376. }
  2377. break;
  2378. }
  2379. case GPBDataTypeGroup: {
  2380. if (GPBGetHasIvarField(self, field)) {
  2381. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has
  2382. // check again.
  2383. GPBMessage *message = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  2384. [input readGroup:GPBFieldNumber(field) message:message extensionRegistry:extensionRegistry];
  2385. } else {
  2386. GPBMessage *message = [[field.msgClass alloc] init];
  2387. GPBSetRetainedObjectIvarWithFieldPrivate(self, field, message);
  2388. [input readGroup:GPBFieldNumber(field) message:message extensionRegistry:extensionRegistry];
  2389. }
  2390. break;
  2391. }
  2392. case GPBDataTypeEnum: {
  2393. int32_t val = GPBCodedInputStreamReadEnum(&input->state_);
  2394. if (!GPBFieldIsClosedEnum(field) || [field isValidEnumValue:val]) {
  2395. GPBSetInt32IvarWithFieldPrivate(self, field, val);
  2396. } else {
  2397. AddUnknownFieldVarint32(self, GPBFieldNumber(field), val);
  2398. }
  2399. }
  2400. } // switch
  2401. }
  2402. static void MergeRepeatedPackedFieldFromCodedInputStream(GPBMessage *self,
  2403. GPBFieldDescriptor *field,
  2404. GPBCodedInputStream *input) {
  2405. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2406. GPBCodedInputStreamState *state = &input->state_;
  2407. id genericArray = GetOrCreateArrayIvarWithField(self, field);
  2408. int32_t length = GPBCodedInputStreamReadInt32(state);
  2409. size_t limit = GPBCodedInputStreamPushLimit(state, length);
  2410. while (GPBCodedInputStreamBytesUntilLimit(state) > 0) {
  2411. switch (fieldDataType) {
  2412. #define CASE_REPEATED_PACKED_POD(NAME, TYPE, ARRAY_TYPE) \
  2413. case GPBDataType##NAME: { \
  2414. TYPE val = GPBCodedInputStreamRead##NAME(state); \
  2415. [(GPB##ARRAY_TYPE##Array *)genericArray addValue:val]; \
  2416. break; \
  2417. }
  2418. CASE_REPEATED_PACKED_POD(Bool, BOOL, Bool)
  2419. CASE_REPEATED_PACKED_POD(Fixed32, uint32_t, UInt32)
  2420. CASE_REPEATED_PACKED_POD(SFixed32, int32_t, Int32)
  2421. CASE_REPEATED_PACKED_POD(Float, float, Float)
  2422. CASE_REPEATED_PACKED_POD(Fixed64, uint64_t, UInt64)
  2423. CASE_REPEATED_PACKED_POD(SFixed64, int64_t, Int64)
  2424. CASE_REPEATED_PACKED_POD(Double, double, Double)
  2425. CASE_REPEATED_PACKED_POD(Int32, int32_t, Int32)
  2426. CASE_REPEATED_PACKED_POD(Int64, int64_t, Int64)
  2427. CASE_REPEATED_PACKED_POD(SInt32, int32_t, Int32)
  2428. CASE_REPEATED_PACKED_POD(SInt64, int64_t, Int64)
  2429. CASE_REPEATED_PACKED_POD(UInt32, uint32_t, UInt32)
  2430. CASE_REPEATED_PACKED_POD(UInt64, uint64_t, UInt64)
  2431. #undef CASE_REPEATED_PACKED_POD
  2432. case GPBDataTypeBytes:
  2433. case GPBDataTypeString:
  2434. case GPBDataTypeMessage:
  2435. case GPBDataTypeGroup:
  2436. NSCAssert(NO, @"Non primitive types can't be packed");
  2437. break;
  2438. case GPBDataTypeEnum: {
  2439. int32_t val = GPBCodedInputStreamReadEnum(state);
  2440. if (!GPBFieldIsClosedEnum(field) || [field isValidEnumValue:val]) {
  2441. [(GPBEnumArray *)genericArray addRawValue:val];
  2442. } else {
  2443. AddUnknownFieldVarint32(self, GPBFieldNumber(field), val);
  2444. }
  2445. break;
  2446. }
  2447. } // switch
  2448. } // while(BytesUntilLimit() > 0)
  2449. GPBCodedInputStreamPopLimit(state, limit);
  2450. }
  2451. static void MergeRepeatedNotPackedFieldFromCodedInputStream(
  2452. GPBMessage *self, GPBFieldDescriptor *field, GPBCodedInputStream *input,
  2453. id<GPBExtensionRegistry> extensionRegistry) {
  2454. GPBCodedInputStreamState *state = &input->state_;
  2455. id genericArray = GetOrCreateArrayIvarWithField(self, field);
  2456. switch (GPBGetFieldDataType(field)) {
  2457. #define CASE_REPEATED_NOT_PACKED_POD(NAME, TYPE, ARRAY_TYPE) \
  2458. case GPBDataType##NAME: { \
  2459. TYPE val = GPBCodedInputStreamRead##NAME(state); \
  2460. [(GPB##ARRAY_TYPE##Array *)genericArray addValue:val]; \
  2461. break; \
  2462. }
  2463. #define CASE_REPEATED_NOT_PACKED_OBJECT(NAME) \
  2464. case GPBDataType##NAME: { \
  2465. id val = GPBCodedInputStreamReadRetained##NAME(state); \
  2466. [(NSMutableArray *)genericArray addObject:val]; \
  2467. [val release]; \
  2468. break; \
  2469. }
  2470. CASE_REPEATED_NOT_PACKED_POD(Bool, BOOL, Bool)
  2471. CASE_REPEATED_NOT_PACKED_POD(Fixed32, uint32_t, UInt32)
  2472. CASE_REPEATED_NOT_PACKED_POD(SFixed32, int32_t, Int32)
  2473. CASE_REPEATED_NOT_PACKED_POD(Float, float, Float)
  2474. CASE_REPEATED_NOT_PACKED_POD(Fixed64, uint64_t, UInt64)
  2475. CASE_REPEATED_NOT_PACKED_POD(SFixed64, int64_t, Int64)
  2476. CASE_REPEATED_NOT_PACKED_POD(Double, double, Double)
  2477. CASE_REPEATED_NOT_PACKED_POD(Int32, int32_t, Int32)
  2478. CASE_REPEATED_NOT_PACKED_POD(Int64, int64_t, Int64)
  2479. CASE_REPEATED_NOT_PACKED_POD(SInt32, int32_t, Int32)
  2480. CASE_REPEATED_NOT_PACKED_POD(SInt64, int64_t, Int64)
  2481. CASE_REPEATED_NOT_PACKED_POD(UInt32, uint32_t, UInt32)
  2482. CASE_REPEATED_NOT_PACKED_POD(UInt64, uint64_t, UInt64)
  2483. CASE_REPEATED_NOT_PACKED_OBJECT(Bytes)
  2484. CASE_REPEATED_NOT_PACKED_OBJECT(String)
  2485. #undef CASE_REPEATED_NOT_PACKED_POD
  2486. #undef CASE_NOT_PACKED_OBJECT
  2487. case GPBDataTypeMessage: {
  2488. GPBMessage *message = [[field.msgClass alloc] init];
  2489. [(NSMutableArray *)genericArray addObject:message];
  2490. // The array will now retain message, so go ahead and release it in case
  2491. // -readMessage:extensionRegistry: throws so it won't be leaked.
  2492. [message release];
  2493. [input readMessage:message extensionRegistry:extensionRegistry];
  2494. break;
  2495. }
  2496. case GPBDataTypeGroup: {
  2497. GPBMessage *message = [[field.msgClass alloc] init];
  2498. [(NSMutableArray *)genericArray addObject:message];
  2499. // The array will now retain message, so go ahead and release it in case
  2500. // -readGroup:extensionRegistry: throws so it won't be leaked.
  2501. [message release];
  2502. [input readGroup:GPBFieldNumber(field) message:message extensionRegistry:extensionRegistry];
  2503. break;
  2504. }
  2505. case GPBDataTypeEnum: {
  2506. int32_t val = GPBCodedInputStreamReadEnum(state);
  2507. if (!GPBFieldIsClosedEnum(field) || [field isValidEnumValue:val]) {
  2508. [(GPBEnumArray *)genericArray addRawValue:val];
  2509. } else {
  2510. AddUnknownFieldVarint32(self, GPBFieldNumber(field), val);
  2511. }
  2512. break;
  2513. }
  2514. } // switch
  2515. }
  2516. - (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input
  2517. extensionRegistry:(id<GPBExtensionRegistry>)extensionRegistry
  2518. endingTag:(uint32_t)endingTag {
  2519. #if defined(DEBUG) && DEBUG
  2520. NSAssert(endingTag == 0 || GPBWireFormatGetTagWireType(endingTag) == GPBWireFormatEndGroup,
  2521. @"endingTag should have been an endGroup tag");
  2522. #endif // DEBUG
  2523. GPBDescriptor *descriptor = [self descriptor];
  2524. GPBCodedInputStreamState *state = &input->state_;
  2525. uint32_t tag = 0;
  2526. NSUInteger startingIndex = 0;
  2527. NSArray *fields = descriptor->fields_;
  2528. BOOL isMessageSetWireFormat = descriptor.isWireFormat;
  2529. NSUInteger numFields = fields.count;
  2530. while (YES) {
  2531. BOOL merged = NO;
  2532. tag = GPBCodedInputStreamReadTag(state);
  2533. if (tag == endingTag || tag == 0) {
  2534. // If we got to the end (tag zero), when we were expecting the end group, this will
  2535. // raise the error.
  2536. GPBCodedInputStreamCheckLastTagWas(state, endingTag);
  2537. return;
  2538. }
  2539. for (NSUInteger i = 0; i < numFields; ++i) {
  2540. if (startingIndex >= numFields) startingIndex = 0;
  2541. GPBFieldDescriptor *fieldDescriptor = fields[startingIndex];
  2542. if (GPBFieldTag(fieldDescriptor) == tag) {
  2543. GPBFieldType fieldType = fieldDescriptor.fieldType;
  2544. if (fieldType == GPBFieldTypeSingle) {
  2545. MergeSingleFieldFromCodedInputStream(self, fieldDescriptor, input, extensionRegistry);
  2546. // Well formed protos will only have a single field once, advance
  2547. // the starting index to the next field.
  2548. startingIndex += 1;
  2549. } else if (fieldType == GPBFieldTypeRepeated) {
  2550. if (fieldDescriptor.isPackable) {
  2551. MergeRepeatedPackedFieldFromCodedInputStream(self, fieldDescriptor, input);
  2552. // Well formed protos will only have a repeated field that is
  2553. // packed once, advance the starting index to the next field.
  2554. startingIndex += 1;
  2555. } else {
  2556. MergeRepeatedNotPackedFieldFromCodedInputStream(self, fieldDescriptor, input,
  2557. extensionRegistry);
  2558. }
  2559. } else { // fieldType == GPBFieldTypeMap
  2560. // GPB*Dictionary or NSDictionary, exact type doesn't matter at this
  2561. // point.
  2562. id map = GetOrCreateMapIvarWithField(self, fieldDescriptor);
  2563. [input readMapEntry:map
  2564. extensionRegistry:extensionRegistry
  2565. field:fieldDescriptor
  2566. parentMessage:self];
  2567. }
  2568. merged = YES;
  2569. break;
  2570. } else {
  2571. startingIndex += 1;
  2572. }
  2573. } // for(i < numFields)
  2574. if (merged) continue; // On to the next tag
  2575. // Primitive, repeated types can be packed or unpacked on the wire, and
  2576. // are parsed either way. The above loop covered tag in the preferred
  2577. // for, so this need to check the alternate form.
  2578. for (NSUInteger i = 0; i < numFields; ++i) {
  2579. if (startingIndex >= numFields) startingIndex = 0;
  2580. GPBFieldDescriptor *fieldDescriptor = fields[startingIndex];
  2581. if ((fieldDescriptor.fieldType == GPBFieldTypeRepeated) &&
  2582. !GPBFieldDataTypeIsObject(fieldDescriptor) &&
  2583. (GPBFieldAlternateTag(fieldDescriptor) == tag)) {
  2584. BOOL alternateIsPacked = !fieldDescriptor.isPackable;
  2585. if (alternateIsPacked) {
  2586. MergeRepeatedPackedFieldFromCodedInputStream(self, fieldDescriptor, input);
  2587. // Well formed protos will only have a repeated field that is
  2588. // packed once, advance the starting index to the next field.
  2589. startingIndex += 1;
  2590. } else {
  2591. MergeRepeatedNotPackedFieldFromCodedInputStream(self, fieldDescriptor, input,
  2592. extensionRegistry);
  2593. }
  2594. merged = YES;
  2595. break;
  2596. } else {
  2597. startingIndex += 1;
  2598. }
  2599. }
  2600. if (merged) continue; // On to the next tag
  2601. if (isMessageSetWireFormat) {
  2602. if (GPBWireFormatMessageSetItemTag == tag) {
  2603. [self parseMessageSet:input extensionRegistry:extensionRegistry];
  2604. continue; // On to the next tag
  2605. }
  2606. } else {
  2607. // ObjC Runtime currently doesn't track if a message supported extensions, so the check is
  2608. // always done.
  2609. GPBExtensionDescriptor *extension =
  2610. [extensionRegistry extensionForDescriptor:descriptor
  2611. fieldNumber:GPBWireFormatGetTagFieldNumber(tag)];
  2612. if (extension) {
  2613. GPBWireFormat wireType = GPBWireFormatGetTagWireType(tag);
  2614. if (extension.wireType == wireType) {
  2615. ExtensionMergeFromInputStream(extension, extension.packable, input, extensionRegistry,
  2616. self);
  2617. continue; // On to the next tag
  2618. }
  2619. // Primitive, repeated types can be packed on unpacked on the wire, and are
  2620. // parsed either way.
  2621. if ([extension isRepeated] && !GPBDataTypeIsObject(extension->description_->dataType) &&
  2622. (extension.alternateWireType == wireType)) {
  2623. ExtensionMergeFromInputStream(extension, !extension.packable, input, extensionRegistry,
  2624. self);
  2625. continue; // On to the next tag
  2626. }
  2627. }
  2628. }
  2629. ParseUnknownField(self, tag, input);
  2630. } // while(YES)
  2631. }
  2632. #pragma mark - MergeFrom Support
  2633. - (void)mergeFrom:(GPBMessage *)other {
  2634. Class selfClass = [self class];
  2635. Class otherClass = [other class];
  2636. if (!([selfClass isSubclassOfClass:otherClass] || [otherClass isSubclassOfClass:selfClass])) {
  2637. [NSException raise:NSInvalidArgumentException
  2638. format:@"Classes must match %@ != %@", selfClass, otherClass];
  2639. }
  2640. // We assume something will be done and become visible.
  2641. GPBBecomeVisibleToAutocreator(self);
  2642. GPBDescriptor *descriptor = [[self class] descriptor];
  2643. for (GPBFieldDescriptor *field in descriptor->fields_) {
  2644. GPBFieldType fieldType = field.fieldType;
  2645. if (fieldType == GPBFieldTypeSingle) {
  2646. int32_t hasIndex = GPBFieldHasIndex(field);
  2647. uint32_t fieldNumber = GPBFieldNumber(field);
  2648. if (!GPBGetHasIvar(other, hasIndex, fieldNumber)) {
  2649. // Other doesn't have the field set, on to the next.
  2650. continue;
  2651. }
  2652. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2653. switch (fieldDataType) {
  2654. case GPBDataTypeBool:
  2655. GPBSetBoolIvarWithFieldPrivate(self, field, GPBGetMessageBoolField(other, field));
  2656. break;
  2657. case GPBDataTypeSFixed32:
  2658. case GPBDataTypeEnum:
  2659. case GPBDataTypeInt32:
  2660. case GPBDataTypeSInt32:
  2661. GPBSetInt32IvarWithFieldPrivate(self, field, GPBGetMessageInt32Field(other, field));
  2662. break;
  2663. case GPBDataTypeFixed32:
  2664. case GPBDataTypeUInt32:
  2665. GPBSetUInt32IvarWithFieldPrivate(self, field, GPBGetMessageUInt32Field(other, field));
  2666. break;
  2667. case GPBDataTypeSFixed64:
  2668. case GPBDataTypeInt64:
  2669. case GPBDataTypeSInt64:
  2670. GPBSetInt64IvarWithFieldPrivate(self, field, GPBGetMessageInt64Field(other, field));
  2671. break;
  2672. case GPBDataTypeFixed64:
  2673. case GPBDataTypeUInt64:
  2674. GPBSetUInt64IvarWithFieldPrivate(self, field, GPBGetMessageUInt64Field(other, field));
  2675. break;
  2676. case GPBDataTypeFloat:
  2677. GPBSetFloatIvarWithFieldPrivate(self, field, GPBGetMessageFloatField(other, field));
  2678. break;
  2679. case GPBDataTypeDouble:
  2680. GPBSetDoubleIvarWithFieldPrivate(self, field, GPBGetMessageDoubleField(other, field));
  2681. break;
  2682. case GPBDataTypeBytes:
  2683. case GPBDataTypeString: {
  2684. id otherVal = GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2685. GPBSetObjectIvarWithFieldPrivate(self, field, otherVal);
  2686. break;
  2687. }
  2688. case GPBDataTypeMessage:
  2689. case GPBDataTypeGroup: {
  2690. id otherVal = GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2691. if (GPBGetHasIvar(self, hasIndex, fieldNumber)) {
  2692. GPBMessage *message = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  2693. [message mergeFrom:otherVal];
  2694. } else {
  2695. GPBMessage *message = [otherVal copy];
  2696. GPBSetRetainedObjectIvarWithFieldPrivate(self, field, message);
  2697. }
  2698. break;
  2699. }
  2700. } // switch()
  2701. } else if (fieldType == GPBFieldTypeRepeated) {
  2702. // In the case of a list, they need to be appended, and there is no
  2703. // _hasIvar to worry about setting.
  2704. id otherArray = GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2705. if (otherArray) {
  2706. GPBDataType fieldDataType = field->description_->dataType;
  2707. if (GPBDataTypeIsObject(fieldDataType)) {
  2708. NSMutableArray *resultArray = GetOrCreateArrayIvarWithField(self, field);
  2709. [resultArray addObjectsFromArray:otherArray];
  2710. } else if (fieldDataType == GPBDataTypeEnum) {
  2711. GPBEnumArray *resultArray = GetOrCreateArrayIvarWithField(self, field);
  2712. [resultArray addRawValuesFromArray:otherArray];
  2713. } else {
  2714. // The array type doesn't matter, that all implement
  2715. // -addValuesFromArray:.
  2716. GPBInt32Array *resultArray = GetOrCreateArrayIvarWithField(self, field);
  2717. [resultArray addValuesFromArray:otherArray];
  2718. }
  2719. }
  2720. } else { // fieldType = GPBFieldTypeMap
  2721. // In the case of a map, they need to be merged, and there is no
  2722. // _hasIvar to worry about setting.
  2723. id otherDict = GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2724. if (otherDict) {
  2725. GPBDataType keyDataType = field.mapKeyDataType;
  2726. GPBDataType valueDataType = field->description_->dataType;
  2727. if (GPBDataTypeIsObject(keyDataType) && GPBDataTypeIsObject(valueDataType)) {
  2728. NSMutableDictionary *resultDict = GetOrCreateMapIvarWithField(self, field);
  2729. [resultDict addEntriesFromDictionary:otherDict];
  2730. } else if (valueDataType == GPBDataTypeEnum) {
  2731. // The exact type doesn't matter, just need to know it is a
  2732. // GPB*EnumDictionary.
  2733. GPBInt32EnumDictionary *resultDict = GetOrCreateMapIvarWithField(self, field);
  2734. [resultDict addRawEntriesFromDictionary:otherDict];
  2735. } else {
  2736. // The exact type doesn't matter, they all implement
  2737. // -addEntriesFromDictionary:.
  2738. GPBInt32Int32Dictionary *resultDict = GetOrCreateMapIvarWithField(self, field);
  2739. [resultDict addEntriesFromDictionary:otherDict];
  2740. }
  2741. }
  2742. } // if (fieldType)..else if...else
  2743. } // for(fields)
  2744. // Unknown fields.
  2745. if (unknownFields_) {
  2746. #if defined(DEBUG) && DEBUG
  2747. NSAssert(unknownFieldData_ == nil, @"Internal error both unknown states were set");
  2748. #endif
  2749. @synchronized(other) {
  2750. if (other->unknownFields_) {
  2751. #if defined(DEBUG) && DEBUG
  2752. NSAssert(other->unknownFieldData_ == nil, @"Internal error both unknown states were set");
  2753. #endif
  2754. [unknownFields_ mergeUnknownFields:other->unknownFields_];
  2755. } else if (other->unknownFieldData_) {
  2756. MergeUnknownFieldDataIntoFieldSet(self, other->unknownFieldData_, nil);
  2757. }
  2758. } // @synchronized(other)
  2759. } else {
  2760. NSData *otherData = GPBMessageUnknownFieldsData(other);
  2761. if (otherData) {
  2762. if (unknownFieldData_) {
  2763. [unknownFieldData_ appendData:otherData];
  2764. } else {
  2765. unknownFieldData_ = [otherData mutableCopy];
  2766. }
  2767. }
  2768. }
  2769. // Extensions
  2770. if (other->extensionMap_.count == 0) {
  2771. return;
  2772. }
  2773. if (extensionMap_ == nil) {
  2774. extensionMap_ = CloneExtensionMap(other->extensionMap_, NSZoneFromPointer(self));
  2775. } else {
  2776. for (GPBExtensionDescriptor *extension in other->extensionMap_) {
  2777. id otherValue = [other->extensionMap_ objectForKey:extension];
  2778. id value = [extensionMap_ objectForKey:extension];
  2779. BOOL isMessageExtension = GPBExtensionIsMessage(extension);
  2780. if (extension.repeated) {
  2781. NSMutableArray *list = value;
  2782. if (list == nil) {
  2783. list = [[NSMutableArray alloc] init];
  2784. [extensionMap_ setObject:list forKey:extension];
  2785. [list release];
  2786. }
  2787. if (isMessageExtension) {
  2788. for (GPBMessage *otherListValue in otherValue) {
  2789. GPBMessage *copiedValue = [otherListValue copy];
  2790. [list addObject:copiedValue];
  2791. [copiedValue release];
  2792. }
  2793. } else {
  2794. [list addObjectsFromArray:otherValue];
  2795. }
  2796. } else {
  2797. if (isMessageExtension) {
  2798. if (value) {
  2799. [(GPBMessage *)value mergeFrom:(GPBMessage *)otherValue];
  2800. } else {
  2801. GPBMessage *copiedValue = [otherValue copy];
  2802. [extensionMap_ setObject:copiedValue forKey:extension];
  2803. [copiedValue release];
  2804. }
  2805. } else {
  2806. [extensionMap_ setObject:otherValue forKey:extension];
  2807. }
  2808. }
  2809. if (isMessageExtension && !extension.isRepeated) {
  2810. GPBMessage *autocreatedValue = [[autocreatedExtensionMap_ objectForKey:extension] retain];
  2811. // Must remove from the map before calling GPBClearMessageAutocreator()
  2812. // so that GPBClearMessageAutocreator() knows its safe to clear.
  2813. [autocreatedExtensionMap_ removeObjectForKey:extension];
  2814. GPBClearMessageAutocreator(autocreatedValue);
  2815. [autocreatedValue release];
  2816. }
  2817. }
  2818. }
  2819. }
  2820. #pragma mark - isEqual: & hash Support
  2821. - (BOOL)isEqual:(id)other {
  2822. if (other == self) {
  2823. return YES;
  2824. }
  2825. if (![other isKindOfClass:[GPBMessage class]]) {
  2826. return NO;
  2827. }
  2828. GPBMessage *otherMsg = other;
  2829. GPBDescriptor *descriptor = [[self class] descriptor];
  2830. if ([[otherMsg class] descriptor] != descriptor) {
  2831. return NO;
  2832. }
  2833. uint8_t *selfStorage = (uint8_t *)messageStorage_;
  2834. uint8_t *otherStorage = (uint8_t *)otherMsg->messageStorage_;
  2835. for (GPBFieldDescriptor *field in descriptor->fields_) {
  2836. if (GPBFieldIsMapOrArray(field)) {
  2837. // In the case of a list or map, there is no _hasIvar to worry about.
  2838. // NOTE: These are NSArray/GPB*Array or NSDictionary/GPB*Dictionary, but
  2839. // the type doesn't really matter as the objects all support -count and
  2840. // -isEqual:.
  2841. NSArray *resultMapOrArray = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  2842. NSArray *otherMapOrArray = GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2843. // nil and empty are equal
  2844. if (resultMapOrArray.count != 0 || otherMapOrArray.count != 0) {
  2845. if (![resultMapOrArray isEqual:otherMapOrArray]) {
  2846. return NO;
  2847. }
  2848. }
  2849. } else { // Single field
  2850. int32_t hasIndex = GPBFieldHasIndex(field);
  2851. uint32_t fieldNum = GPBFieldNumber(field);
  2852. BOOL selfHas = GPBGetHasIvar(self, hasIndex, fieldNum);
  2853. BOOL otherHas = GPBGetHasIvar(other, hasIndex, fieldNum);
  2854. if (selfHas != otherHas) {
  2855. return NO; // Differing has values, not equal.
  2856. }
  2857. if (!selfHas) {
  2858. // Same has values, was no, nothing else to check for this field.
  2859. continue;
  2860. }
  2861. // Now compare the values.
  2862. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2863. size_t fieldOffset = field->description_->offset;
  2864. switch (fieldDataType) {
  2865. case GPBDataTypeBool: {
  2866. // Bools are stored in has_bits to avoid needing explicit space in
  2867. // the storage structure.
  2868. // (the field number passed to the HasIvar helper doesn't really
  2869. // matter since the offset is never negative)
  2870. BOOL selfValue = GPBGetHasIvar(self, (int32_t)(fieldOffset), 0);
  2871. BOOL otherValue = GPBGetHasIvar(other, (int32_t)(fieldOffset), 0);
  2872. if (selfValue != otherValue) {
  2873. return NO;
  2874. }
  2875. break;
  2876. }
  2877. case GPBDataTypeSFixed32:
  2878. case GPBDataTypeInt32:
  2879. case GPBDataTypeSInt32:
  2880. case GPBDataTypeEnum:
  2881. case GPBDataTypeFixed32:
  2882. case GPBDataTypeUInt32:
  2883. case GPBDataTypeFloat: {
  2884. GPBInternalCompileAssert(sizeof(float) == sizeof(uint32_t), float_not_32_bits);
  2885. // These are all 32bit, signed/unsigned doesn't matter for equality.
  2886. uint32_t *selfValPtr = (uint32_t *)&selfStorage[fieldOffset];
  2887. uint32_t *otherValPtr = (uint32_t *)&otherStorage[fieldOffset];
  2888. if (*selfValPtr != *otherValPtr) {
  2889. return NO;
  2890. }
  2891. break;
  2892. }
  2893. case GPBDataTypeSFixed64:
  2894. case GPBDataTypeInt64:
  2895. case GPBDataTypeSInt64:
  2896. case GPBDataTypeFixed64:
  2897. case GPBDataTypeUInt64:
  2898. case GPBDataTypeDouble: {
  2899. GPBInternalCompileAssert(sizeof(double) == sizeof(uint64_t), double_not_64_bits);
  2900. // These are all 64bit, signed/unsigned doesn't matter for equality.
  2901. uint64_t *selfValPtr = (uint64_t *)&selfStorage[fieldOffset];
  2902. uint64_t *otherValPtr = (uint64_t *)&otherStorage[fieldOffset];
  2903. if (*selfValPtr != *otherValPtr) {
  2904. return NO;
  2905. }
  2906. break;
  2907. }
  2908. case GPBDataTypeBytes:
  2909. case GPBDataTypeString:
  2910. case GPBDataTypeMessage:
  2911. case GPBDataTypeGroup: {
  2912. // Type doesn't matter here, they all implement -isEqual:.
  2913. id *selfValPtr = (id *)&selfStorage[fieldOffset];
  2914. id *otherValPtr = (id *)&otherStorage[fieldOffset];
  2915. if (![*selfValPtr isEqual:*otherValPtr]) {
  2916. return NO;
  2917. }
  2918. break;
  2919. }
  2920. } // switch()
  2921. } // if(mapOrArray)...else
  2922. } // for(fields)
  2923. // nil and empty are equal
  2924. if (extensionMap_.count != 0 || otherMsg->extensionMap_.count != 0) {
  2925. if (![extensionMap_ isEqual:otherMsg->extensionMap_]) {
  2926. return NO;
  2927. }
  2928. }
  2929. // Mutation while another thread is doing read only access is invalid, so the only thing we
  2930. // need to guard against is concurrent r/o access, so we can grab the values (and retain them)
  2931. // so we have a version to compare against safely incase the second access causes the transform
  2932. // between internal states.
  2933. #pragma clang diagnostic push
  2934. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  2935. GPBUnknownFieldSet *selfUnknownFields;
  2936. NSData *selfUnknownFieldData;
  2937. @synchronized(self) {
  2938. selfUnknownFields = [unknownFields_ retain];
  2939. selfUnknownFieldData = [unknownFieldData_ retain];
  2940. }
  2941. GPBUnknownFieldSet *otherUnknownFields;
  2942. NSData *otherUnknownFieldData;
  2943. @synchronized(otherMsg) {
  2944. otherUnknownFields = [otherMsg->unknownFields_ retain];
  2945. otherUnknownFieldData = [otherMsg->unknownFieldData_ retain];
  2946. }
  2947. #pragma clang diagnostic pop
  2948. #if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS)
  2949. if (selfUnknownFields) {
  2950. NSAssert(selfUnknownFieldData == nil, @"Internal error both unknown states were set");
  2951. }
  2952. if (otherUnknownFields) {
  2953. NSAssert(otherUnknownFieldData == nil, @"Internal error both unknown states were set");
  2954. }
  2955. #endif
  2956. // Since a developer can set the legacy unknownFieldSet, treat nil and empty as the same.
  2957. if (selfUnknownFields && selfUnknownFields.countOfFields == 0) {
  2958. [selfUnknownFields release];
  2959. selfUnknownFields = nil;
  2960. }
  2961. if (otherUnknownFields && otherUnknownFields.countOfFields == 0) {
  2962. [otherUnknownFields release];
  2963. otherUnknownFields = nil;
  2964. }
  2965. BOOL result = YES;
  2966. if (selfUnknownFieldData && otherUnknownFieldData) {
  2967. // Both had data, compare it.
  2968. result = [selfUnknownFieldData isEqual:otherUnknownFieldData];
  2969. } else if (selfUnknownFields && otherUnknownFields) {
  2970. // Both had fields set, compare them.
  2971. result = [selfUnknownFields isEqual:otherUnknownFields];
  2972. } else {
  2973. // At this point, we're done to one have a set/nothing, and the other having data/nothing.
  2974. #pragma clang diagnostic push
  2975. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  2976. GPBUnknownFieldSet *theSet = selfUnknownFields ? selfUnknownFields : otherUnknownFields;
  2977. NSData *theData = selfUnknownFieldData ? selfUnknownFieldData : otherUnknownFieldData;
  2978. if (theSet) {
  2979. if (theData) {
  2980. GPBUnknownFieldSet *tempSet = [[GPBUnknownFieldSet alloc] init];
  2981. MergeUnknownFieldDataIntoFieldSet(self, theData, tempSet);
  2982. result = [tempSet isEqual:theSet];
  2983. [tempSet release];
  2984. } else {
  2985. result = NO;
  2986. }
  2987. } else {
  2988. // It was a data/nothing and nothing, so they equal if the other didn't have data.
  2989. result = theData == nil;
  2990. }
  2991. #pragma clang diagnostic pop
  2992. }
  2993. [selfUnknownFields release];
  2994. [selfUnknownFieldData release];
  2995. [otherUnknownFields release];
  2996. [otherUnknownFieldData release];
  2997. return result;
  2998. }
  2999. // It is very difficult to implement a generic hash for ProtoBuf messages that
  3000. // will perform well. If you need hashing on your ProtoBufs (eg you are using
  3001. // them as dictionary keys) you will probably want to implement a ProtoBuf
  3002. // message specific hash as a category on your protobuf class. Do not make it a
  3003. // category on GPBMessage as you will conflict with this hash, and will possibly
  3004. // override hash for all generated protobufs. A good implementation of hash will
  3005. // be really fast, so we would recommend only hashing protobufs that have an
  3006. // identifier field of some kind that you can easily hash. If you implement
  3007. // hash, we would strongly recommend overriding isEqual: in your category as
  3008. // well, as the default implementation of isEqual: is extremely slow, and may
  3009. // drastically affect performance in large sets.
  3010. - (NSUInteger)hash {
  3011. GPBDescriptor *descriptor = [[self class] descriptor];
  3012. const NSUInteger prime = 19;
  3013. uint8_t *storage = (uint8_t *)messageStorage_;
  3014. // Start with the descriptor and then mix it with some instance info.
  3015. // Hopefully that will give a spread based on classes and what fields are set.
  3016. NSUInteger result = (NSUInteger)descriptor;
  3017. for (GPBFieldDescriptor *field in descriptor->fields_) {
  3018. if (GPBFieldIsMapOrArray(field)) {
  3019. // Exact type doesn't matter, just check if there are any elements.
  3020. NSArray *mapOrArray = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  3021. NSUInteger count = mapOrArray.count;
  3022. if (count) {
  3023. // NSArray/NSDictionary use count, use the field number and the count.
  3024. result = prime * result + GPBFieldNumber(field);
  3025. result = prime * result + count;
  3026. }
  3027. } else if (GPBGetHasIvarField(self, field)) {
  3028. // Just using the field number seemed simple/fast, but then a small
  3029. // message class where all the same fields are always set (to different
  3030. // things would end up all with the same hash, so pull in some data).
  3031. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  3032. size_t fieldOffset = field->description_->offset;
  3033. switch (fieldDataType) {
  3034. case GPBDataTypeBool: {
  3035. // Bools are stored in has_bits to avoid needing explicit space in
  3036. // the storage structure.
  3037. // (the field number passed to the HasIvar helper doesn't really
  3038. // matter since the offset is never negative)
  3039. BOOL value = GPBGetHasIvar(self, (int32_t)(fieldOffset), 0);
  3040. result = prime * result + value;
  3041. break;
  3042. }
  3043. case GPBDataTypeSFixed32:
  3044. case GPBDataTypeInt32:
  3045. case GPBDataTypeSInt32:
  3046. case GPBDataTypeEnum:
  3047. case GPBDataTypeFixed32:
  3048. case GPBDataTypeUInt32:
  3049. case GPBDataTypeFloat: {
  3050. GPBInternalCompileAssert(sizeof(float) == sizeof(uint32_t), float_not_32_bits);
  3051. // These are all 32bit, just mix it in.
  3052. uint32_t *valPtr = (uint32_t *)&storage[fieldOffset];
  3053. result = prime * result + *valPtr;
  3054. break;
  3055. }
  3056. case GPBDataTypeSFixed64:
  3057. case GPBDataTypeInt64:
  3058. case GPBDataTypeSInt64:
  3059. case GPBDataTypeFixed64:
  3060. case GPBDataTypeUInt64:
  3061. case GPBDataTypeDouble: {
  3062. GPBInternalCompileAssert(sizeof(double) == sizeof(uint64_t), double_not_64_bits);
  3063. // These are all 64bit, just mix what fits into an NSUInteger in.
  3064. uint64_t *valPtr = (uint64_t *)&storage[fieldOffset];
  3065. result = prime * result + (NSUInteger)(*valPtr);
  3066. break;
  3067. }
  3068. case GPBDataTypeBytes:
  3069. case GPBDataTypeString: {
  3070. // Type doesn't matter here, they both implement -hash:.
  3071. id *valPtr = (id *)&storage[fieldOffset];
  3072. result = prime * result + [*valPtr hash];
  3073. break;
  3074. }
  3075. case GPBDataTypeMessage:
  3076. case GPBDataTypeGroup: {
  3077. GPBMessage **valPtr = (GPBMessage **)&storage[fieldOffset];
  3078. // Could call -hash on the sub message, but that could recurse pretty
  3079. // deep; follow the lead of NSArray/NSDictionary and don't really
  3080. // recurse for hash, instead use the field number and the descriptor
  3081. // of the sub message. Yes, this could suck for a bunch of messages
  3082. // where they all only differ in the sub messages, but if you are
  3083. // using a message with sub messages for something that needs -hash,
  3084. // odds are you are also copying them as keys, and that deep copy
  3085. // will also suck.
  3086. result = prime * result + GPBFieldNumber(field);
  3087. result = prime * result + (NSUInteger)[[*valPtr class] descriptor];
  3088. break;
  3089. }
  3090. } // switch()
  3091. }
  3092. }
  3093. // Unknowns and extensions are not included.
  3094. return result;
  3095. }
  3096. #pragma mark - Description Support
  3097. - (NSString *)description {
  3098. NSString *textFormat = GPBTextFormatForMessage(self, @" ");
  3099. NSString *description =
  3100. [NSString stringWithFormat:@"<%@ %p>: {\n%@}", [self class], self, textFormat];
  3101. return description;
  3102. }
  3103. #if defined(DEBUG) && DEBUG
  3104. // Xcode 5.1 added support for custom quick look info.
  3105. // https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/CustomClassDisplay_in_QuickLook/CH01-quick_look_for_custom_objects/CH01-quick_look_for_custom_objects.html#//apple_ref/doc/uid/TP40014001-CH2-SW1
  3106. - (id)debugQuickLookObject {
  3107. return GPBTextFormatForMessage(self, nil);
  3108. }
  3109. #endif // DEBUG
  3110. #pragma mark - SerializedSize
  3111. - (size_t)serializedSize {
  3112. GPBDescriptor *descriptor = [[self class] descriptor];
  3113. size_t result = 0;
  3114. // Has check is done explicitly, so GPBGetObjectIvarWithFieldNoAutocreate()
  3115. // avoids doing the has check again.
  3116. // Fields.
  3117. for (GPBFieldDescriptor *fieldDescriptor in descriptor->fields_) {
  3118. GPBFieldType fieldType = fieldDescriptor.fieldType;
  3119. GPBDataType fieldDataType = GPBGetFieldDataType(fieldDescriptor);
  3120. // Single Fields
  3121. if (fieldType == GPBFieldTypeSingle) {
  3122. BOOL selfHas = GPBGetHasIvarField(self, fieldDescriptor);
  3123. if (!selfHas) {
  3124. continue; // Nothing to do.
  3125. }
  3126. uint32_t fieldNumber = GPBFieldNumber(fieldDescriptor);
  3127. switch (fieldDataType) {
  3128. #define CASE_SINGLE_POD(NAME, TYPE, FUNC_TYPE) \
  3129. case GPBDataType##NAME: { \
  3130. TYPE fieldVal = GPBGetMessage##FUNC_TYPE##Field(self, fieldDescriptor); \
  3131. result += GPBCompute##NAME##Size(fieldNumber, fieldVal); \
  3132. break; \
  3133. }
  3134. #define CASE_SINGLE_OBJECT(NAME) \
  3135. case GPBDataType##NAME: { \
  3136. id fieldVal = GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor); \
  3137. result += GPBCompute##NAME##Size(fieldNumber, fieldVal); \
  3138. break; \
  3139. }
  3140. CASE_SINGLE_POD(Bool, BOOL, Bool)
  3141. CASE_SINGLE_POD(Fixed32, uint32_t, UInt32)
  3142. CASE_SINGLE_POD(SFixed32, int32_t, Int32)
  3143. CASE_SINGLE_POD(Float, float, Float)
  3144. CASE_SINGLE_POD(Fixed64, uint64_t, UInt64)
  3145. CASE_SINGLE_POD(SFixed64, int64_t, Int64)
  3146. CASE_SINGLE_POD(Double, double, Double)
  3147. CASE_SINGLE_POD(Int32, int32_t, Int32)
  3148. CASE_SINGLE_POD(Int64, int64_t, Int64)
  3149. CASE_SINGLE_POD(SInt32, int32_t, Int32)
  3150. CASE_SINGLE_POD(SInt64, int64_t, Int64)
  3151. CASE_SINGLE_POD(UInt32, uint32_t, UInt32)
  3152. CASE_SINGLE_POD(UInt64, uint64_t, UInt64)
  3153. CASE_SINGLE_OBJECT(Bytes)
  3154. CASE_SINGLE_OBJECT(String)
  3155. CASE_SINGLE_OBJECT(Message)
  3156. CASE_SINGLE_OBJECT(Group)
  3157. CASE_SINGLE_POD(Enum, int32_t, Int32)
  3158. #undef CASE_SINGLE_POD
  3159. #undef CASE_SINGLE_OBJECT
  3160. }
  3161. // Repeated Fields
  3162. } else if (fieldType == GPBFieldTypeRepeated) {
  3163. id genericArray = GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor);
  3164. NSUInteger count = [genericArray count];
  3165. if (count == 0) {
  3166. continue; // Nothing to add.
  3167. }
  3168. __block size_t dataSize = 0;
  3169. switch (fieldDataType) {
  3170. #define CASE_REPEATED_POD(NAME, TYPE, ARRAY_TYPE) CASE_REPEATED_POD_EXTRA(NAME, TYPE, ARRAY_TYPE, )
  3171. #define CASE_REPEATED_POD_EXTRA(NAME, TYPE, ARRAY_TYPE, ARRAY_ACCESSOR_NAME) \
  3172. case GPBDataType##NAME: { \
  3173. GPB##ARRAY_TYPE##Array *array = genericArray; \
  3174. [array enumerate##ARRAY_ACCESSOR_NAME## \
  3175. ValuesWithBlock:^(TYPE value, __unused NSUInteger idx, __unused BOOL * stop) { \
  3176. dataSize += GPBCompute##NAME##SizeNoTag(value); \
  3177. }]; \
  3178. break; \
  3179. }
  3180. #define CASE_REPEATED_OBJECT(NAME) \
  3181. case GPBDataType##NAME: { \
  3182. for (id value in genericArray) { \
  3183. dataSize += GPBCompute##NAME##SizeNoTag(value); \
  3184. } \
  3185. break; \
  3186. }
  3187. CASE_REPEATED_POD(Bool, BOOL, Bool)
  3188. CASE_REPEATED_POD(Fixed32, uint32_t, UInt32)
  3189. CASE_REPEATED_POD(SFixed32, int32_t, Int32)
  3190. CASE_REPEATED_POD(Float, float, Float)
  3191. CASE_REPEATED_POD(Fixed64, uint64_t, UInt64)
  3192. CASE_REPEATED_POD(SFixed64, int64_t, Int64)
  3193. CASE_REPEATED_POD(Double, double, Double)
  3194. CASE_REPEATED_POD(Int32, int32_t, Int32)
  3195. CASE_REPEATED_POD(Int64, int64_t, Int64)
  3196. CASE_REPEATED_POD(SInt32, int32_t, Int32)
  3197. CASE_REPEATED_POD(SInt64, int64_t, Int64)
  3198. CASE_REPEATED_POD(UInt32, uint32_t, UInt32)
  3199. CASE_REPEATED_POD(UInt64, uint64_t, UInt64)
  3200. CASE_REPEATED_OBJECT(Bytes)
  3201. CASE_REPEATED_OBJECT(String)
  3202. CASE_REPEATED_OBJECT(Message)
  3203. CASE_REPEATED_OBJECT(Group)
  3204. CASE_REPEATED_POD_EXTRA(Enum, int32_t, Enum, Raw)
  3205. #undef CASE_REPEATED_POD
  3206. #undef CASE_REPEATED_POD_EXTRA
  3207. #undef CASE_REPEATED_OBJECT
  3208. } // switch
  3209. result += dataSize;
  3210. size_t tagSize = GPBComputeTagSize(GPBFieldNumber(fieldDescriptor));
  3211. if (fieldDataType == GPBDataTypeGroup) {
  3212. // Groups have both a start and an end tag.
  3213. tagSize *= 2;
  3214. }
  3215. if (fieldDescriptor.isPackable) {
  3216. result += tagSize;
  3217. result += GPBComputeSizeTSizeAsInt32NoTag(dataSize);
  3218. } else {
  3219. result += count * tagSize;
  3220. }
  3221. // Map<> Fields
  3222. } else { // fieldType == GPBFieldTypeMap
  3223. if (GPBDataTypeIsObject(fieldDataType) &&
  3224. (fieldDescriptor.mapKeyDataType == GPBDataTypeString)) {
  3225. // If key type was string, then the map is an NSDictionary.
  3226. NSDictionary *map = GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor);
  3227. if (map) {
  3228. result += GPBDictionaryComputeSizeInternalHelper(map, fieldDescriptor);
  3229. }
  3230. } else {
  3231. // Type will be GPB*GroupDictionary, exact type doesn't matter.
  3232. GPBInt32Int32Dictionary *map = GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor);
  3233. result += [map computeSerializedSizeAsField:fieldDescriptor];
  3234. }
  3235. }
  3236. } // for(fields)
  3237. // Add any unknown fields.
  3238. @synchronized(self) {
  3239. if (unknownFieldData_) {
  3240. #if defined(DEBUG) && DEBUG
  3241. NSAssert(unknownFields_ == nil, @"Internal error both unknown states were set");
  3242. #endif
  3243. result += [unknownFieldData_ length];
  3244. } else {
  3245. if (descriptor.wireFormat) {
  3246. result += [unknownFields_ serializedSizeAsMessageSet];
  3247. } else {
  3248. result += [unknownFields_ serializedSize];
  3249. }
  3250. }
  3251. } // @synchronized(self)
  3252. // Add any extensions.
  3253. for (GPBExtensionDescriptor *extension in extensionMap_) {
  3254. id value = [extensionMap_ objectForKey:extension];
  3255. result += GPBComputeExtensionSerializedSizeIncludingTag(extension, value);
  3256. }
  3257. return result;
  3258. }
  3259. #pragma mark - Resolve Methods Support
  3260. typedef struct ResolveIvarAccessorMethodResult {
  3261. IMP impToAdd;
  3262. SEL encodingSelector;
  3263. } ResolveIvarAccessorMethodResult;
  3264. // |field| can be __unsafe_unretained because they are created at startup
  3265. // and are essentially global. No need to pay for retain/release when
  3266. // they are captured in blocks.
  3267. static void ResolveIvarGet(__unsafe_unretained GPBFieldDescriptor *field,
  3268. ResolveIvarAccessorMethodResult *result) {
  3269. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  3270. switch (fieldDataType) {
  3271. #define CASE_GET(NAME, TYPE, TRUE_NAME) \
  3272. case GPBDataType##NAME: { \
  3273. result->impToAdd = imp_implementationWithBlock(^(id obj) { \
  3274. return GPBGetMessage##TRUE_NAME##Field(obj, field); \
  3275. }); \
  3276. result->encodingSelector = @selector(get##NAME); \
  3277. break; \
  3278. }
  3279. #define CASE_GET_OBJECT(NAME, TYPE, TRUE_NAME) \
  3280. case GPBDataType##NAME: { \
  3281. result->impToAdd = imp_implementationWithBlock(^(id obj) { \
  3282. return GPBGetObjectIvarWithField(obj, field); \
  3283. }); \
  3284. result->encodingSelector = @selector(get##NAME); \
  3285. break; \
  3286. }
  3287. CASE_GET(Bool, BOOL, Bool)
  3288. CASE_GET(Fixed32, uint32_t, UInt32)
  3289. CASE_GET(SFixed32, int32_t, Int32)
  3290. CASE_GET(Float, float, Float)
  3291. CASE_GET(Fixed64, uint64_t, UInt64)
  3292. CASE_GET(SFixed64, int64_t, Int64)
  3293. CASE_GET(Double, double, Double)
  3294. CASE_GET(Int32, int32_t, Int32)
  3295. CASE_GET(Int64, int64_t, Int64)
  3296. CASE_GET(SInt32, int32_t, Int32)
  3297. CASE_GET(SInt64, int64_t, Int64)
  3298. CASE_GET(UInt32, uint32_t, UInt32)
  3299. CASE_GET(UInt64, uint64_t, UInt64)
  3300. CASE_GET_OBJECT(Bytes, id, Object)
  3301. CASE_GET_OBJECT(String, id, Object)
  3302. CASE_GET_OBJECT(Message, id, Object)
  3303. CASE_GET_OBJECT(Group, id, Object)
  3304. CASE_GET(Enum, int32_t, Enum)
  3305. #undef CASE_GET
  3306. }
  3307. }
  3308. // See comment about __unsafe_unretained on ResolveIvarGet.
  3309. static void ResolveIvarSet(__unsafe_unretained GPBFieldDescriptor *field,
  3310. ResolveIvarAccessorMethodResult *result) {
  3311. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  3312. switch (fieldDataType) {
  3313. #define CASE_SET(NAME, TYPE, TRUE_NAME) \
  3314. case GPBDataType##NAME: { \
  3315. result->impToAdd = imp_implementationWithBlock(^(id obj, TYPE value) { \
  3316. return GPBSet##TRUE_NAME##IvarWithFieldPrivate(obj, field, value); \
  3317. }); \
  3318. result->encodingSelector = @selector(set##NAME:); \
  3319. break; \
  3320. }
  3321. #define CASE_SET_COPY(NAME) \
  3322. case GPBDataType##NAME: { \
  3323. result->impToAdd = imp_implementationWithBlock(^(id obj, id value) { \
  3324. return GPBSetRetainedObjectIvarWithFieldPrivate(obj, field, [value copy]); \
  3325. }); \
  3326. result->encodingSelector = @selector(set##NAME:); \
  3327. break; \
  3328. }
  3329. CASE_SET(Bool, BOOL, Bool)
  3330. CASE_SET(Fixed32, uint32_t, UInt32)
  3331. CASE_SET(SFixed32, int32_t, Int32)
  3332. CASE_SET(Float, float, Float)
  3333. CASE_SET(Fixed64, uint64_t, UInt64)
  3334. CASE_SET(SFixed64, int64_t, Int64)
  3335. CASE_SET(Double, double, Double)
  3336. CASE_SET(Int32, int32_t, Int32)
  3337. CASE_SET(Int64, int64_t, Int64)
  3338. CASE_SET(SInt32, int32_t, Int32)
  3339. CASE_SET(SInt64, int64_t, Int64)
  3340. CASE_SET(UInt32, uint32_t, UInt32)
  3341. CASE_SET(UInt64, uint64_t, UInt64)
  3342. CASE_SET_COPY(Bytes)
  3343. CASE_SET_COPY(String)
  3344. CASE_SET(Message, id, Object)
  3345. CASE_SET(Group, id, Object)
  3346. CASE_SET(Enum, int32_t, Enum)
  3347. #undef CASE_SET
  3348. }
  3349. }
  3350. // Highly optimized routines for determining selector types.
  3351. // Meant to only be used by GPBMessage when resolving selectors in
  3352. // `+ (BOOL)resolveInstanceMethod:(SEL)sel`.
  3353. // These routines are intended to make negative decisions as fast as possible.
  3354. GPB_INLINE char GPBFastToUpper(char c) { return (c >= 'a' && c <= 'z') ? (c - 'a' + 'A') : c; }
  3355. GPB_INLINE BOOL GPBIsGetSelForField(const char *selName, GPBFieldDescriptor *descriptor) {
  3356. // Does 'selName' == '<name>'?
  3357. // selName and <name> have to be at least two characters long (i.e. ('a', '\0')" is the shortest
  3358. // selector you can have).
  3359. return (selName[0] == descriptor->description_->name[0]) &&
  3360. (selName[1] == descriptor->description_->name[1]) &&
  3361. (strcmp(selName + 1, descriptor->description_->name + 1) == 0);
  3362. }
  3363. GPB_INLINE BOOL GPBIsSetSelForField(const char *selName, size_t selNameLength,
  3364. GPBFieldDescriptor *descriptor) {
  3365. // Does 'selName' == 'set<Name>:'?
  3366. // Do fastest compares up front
  3367. const size_t kSetLength = strlen("set");
  3368. // kSetLength is 3 and one for the colon.
  3369. if (selNameLength <= kSetLength + 1) {
  3370. return NO;
  3371. }
  3372. if (selName[kSetLength] != GPBFastToUpper(descriptor->description_->name[0])) {
  3373. return NO;
  3374. }
  3375. // NB we check for "set" and the colon later in this routine because we have already checked for
  3376. // starting with "s" and ending with ":" in `+resolveInstanceMethod:` before we get here.
  3377. if (selName[0] != 's' || selName[1] != 'e' || selName[2] != 't') {
  3378. return NO;
  3379. }
  3380. if (selName[selNameLength - 1] != ':') {
  3381. return NO;
  3382. }
  3383. // Slow path.
  3384. size_t nameLength = strlen(descriptor->description_->name);
  3385. size_t setSelLength = nameLength + kSetLength + 1;
  3386. if (selNameLength != setSelLength) {
  3387. return NO;
  3388. }
  3389. if (strncmp(&selName[kSetLength + 1], descriptor->description_->name + 1, nameLength - 1) != 0) {
  3390. return NO;
  3391. }
  3392. return YES;
  3393. }
  3394. GPB_INLINE BOOL GPBFieldHasHas(GPBFieldDescriptor *descriptor) {
  3395. // It gets has/setHas selectors if...
  3396. // - not in a oneof (negative has index)
  3397. // - not clearing on zero
  3398. return (descriptor->description_->hasIndex >= 0) &&
  3399. ((descriptor->description_->flags & GPBFieldClearHasIvarOnZero) == 0);
  3400. }
  3401. GPB_INLINE BOOL GPBIsHasSelForField(const char *selName, size_t selNameLength,
  3402. GPBFieldDescriptor *descriptor) {
  3403. // Does 'selName' == 'has<Name>'?
  3404. // Do fastest compares up front.
  3405. const size_t kHasLength = strlen("has");
  3406. if (selNameLength <= kHasLength) {
  3407. return NO;
  3408. }
  3409. if (selName[0] != 'h' || selName[1] != 'a' || selName[2] != 's') {
  3410. return NO;
  3411. }
  3412. if (selName[kHasLength] != GPBFastToUpper(descriptor->description_->name[0])) {
  3413. return NO;
  3414. }
  3415. if (!GPBFieldHasHas(descriptor)) {
  3416. return NO;
  3417. }
  3418. // Slow path.
  3419. size_t nameLength = strlen(descriptor->description_->name);
  3420. size_t setSelLength = nameLength + kHasLength;
  3421. if (selNameLength != setSelLength) {
  3422. return NO;
  3423. }
  3424. if (strncmp(&selName[kHasLength + 1], descriptor->description_->name + 1, nameLength - 1) != 0) {
  3425. return NO;
  3426. }
  3427. return YES;
  3428. }
  3429. GPB_INLINE BOOL GPBIsCountSelForField(const char *selName, size_t selNameLength,
  3430. GPBFieldDescriptor *descriptor) {
  3431. // Does 'selName' == '<name>_Count'?
  3432. // Do fastest compares up front.
  3433. if (selName[0] != descriptor->description_->name[0]) {
  3434. return NO;
  3435. }
  3436. const size_t kCountLength = strlen("_Count");
  3437. if (selNameLength <= kCountLength) {
  3438. return NO;
  3439. }
  3440. if (selName[selNameLength - kCountLength] != '_') {
  3441. return NO;
  3442. }
  3443. // Slow path.
  3444. size_t nameLength = strlen(descriptor->description_->name);
  3445. size_t setSelLength = nameLength + kCountLength;
  3446. if (selNameLength != setSelLength) {
  3447. return NO;
  3448. }
  3449. if (strncmp(selName, descriptor->description_->name, nameLength) != 0) {
  3450. return NO;
  3451. }
  3452. if (strncmp(&selName[nameLength], "_Count", kCountLength) != 0) {
  3453. return NO;
  3454. }
  3455. return YES;
  3456. }
  3457. GPB_INLINE BOOL GPBIsSetHasSelForField(const char *selName, size_t selNameLength,
  3458. GPBFieldDescriptor *descriptor) {
  3459. // Does 'selName' == 'setHas<Name>:'?
  3460. // Do fastest compares up front.
  3461. const size_t kSetHasLength = strlen("setHas");
  3462. // kSetHasLength is 6 and one for the colon.
  3463. if (selNameLength <= kSetHasLength + 1) {
  3464. return NO;
  3465. }
  3466. if (selName[selNameLength - 1] != ':') {
  3467. return NO;
  3468. }
  3469. if (selName[kSetHasLength] != GPBFastToUpper(descriptor->description_->name[0])) {
  3470. return NO;
  3471. }
  3472. if (selName[0] != 's' || selName[1] != 'e' || selName[2] != 't' || selName[3] != 'H' ||
  3473. selName[4] != 'a' || selName[5] != 's') {
  3474. return NO;
  3475. }
  3476. if (!GPBFieldHasHas(descriptor)) {
  3477. return NO;
  3478. }
  3479. // Slow path.
  3480. size_t nameLength = strlen(descriptor->description_->name);
  3481. size_t setHasSelLength = nameLength + kSetHasLength + 1;
  3482. if (selNameLength != setHasSelLength) {
  3483. return NO;
  3484. }
  3485. if (strncmp(&selName[kSetHasLength + 1], descriptor->description_->name + 1, nameLength - 1) !=
  3486. 0) {
  3487. return NO;
  3488. }
  3489. return YES;
  3490. }
  3491. GPB_INLINE BOOL GPBIsCaseOfSelForOneOf(const char *selName, size_t selNameLength,
  3492. GPBOneofDescriptor *descriptor) {
  3493. // Does 'selName' == '<name>OneOfCase'?
  3494. // Do fastest compares up front.
  3495. if (selName[0] != descriptor->name_[0]) {
  3496. return NO;
  3497. }
  3498. const size_t kOneOfCaseLength = strlen("OneOfCase");
  3499. if (selNameLength <= kOneOfCaseLength) {
  3500. return NO;
  3501. }
  3502. if (selName[selNameLength - kOneOfCaseLength] != 'O') {
  3503. return NO;
  3504. }
  3505. // Slow path.
  3506. size_t nameLength = strlen(descriptor->name_);
  3507. size_t setSelLength = nameLength + kOneOfCaseLength;
  3508. if (selNameLength != setSelLength) {
  3509. return NO;
  3510. }
  3511. if (strncmp(&selName[nameLength], "OneOfCase", kOneOfCaseLength) != 0) {
  3512. return NO;
  3513. }
  3514. if (strncmp(selName, descriptor->name_, nameLength) != 0) {
  3515. return NO;
  3516. }
  3517. return YES;
  3518. }
  3519. + (BOOL)resolveInstanceMethod:(SEL)sel {
  3520. const GPBDescriptor *descriptor = [self descriptor];
  3521. if (!descriptor) {
  3522. return [super resolveInstanceMethod:sel];
  3523. }
  3524. ResolveIvarAccessorMethodResult result = {NULL, NULL};
  3525. const char *selName = sel_getName(sel);
  3526. const size_t selNameLength = strlen(selName);
  3527. // A setter has a leading 's' and a trailing ':' (e.g. 'setFoo:' or 'setHasFoo:').
  3528. BOOL couldBeSetter = selName[0] == 's' && selName[selNameLength - 1] == ':';
  3529. if (couldBeSetter) {
  3530. // See comment about __unsafe_unretained on ResolveIvarGet.
  3531. for (__unsafe_unretained GPBFieldDescriptor *field in descriptor->fields_) {
  3532. BOOL isMapOrArray = GPBFieldIsMapOrArray(field);
  3533. if (GPBIsSetSelForField(selName, selNameLength, field)) {
  3534. if (isMapOrArray) {
  3535. // Local for syntax so the block can directly capture it and not the
  3536. // full lookup.
  3537. result.impToAdd = imp_implementationWithBlock(^(id obj, id value) {
  3538. GPBSetObjectIvarWithFieldPrivate(obj, field, value);
  3539. });
  3540. result.encodingSelector = @selector(setArray:);
  3541. } else {
  3542. ResolveIvarSet(field, &result);
  3543. }
  3544. break;
  3545. } else if (!isMapOrArray && GPBIsSetHasSelForField(selName, selNameLength, field)) {
  3546. result.impToAdd = imp_implementationWithBlock(^(id obj, BOOL value) {
  3547. if (value) {
  3548. [NSException raise:NSInvalidArgumentException
  3549. format:@"%@: %@ can only be set to NO (to clear field).", [obj class],
  3550. NSStringFromSelector(sel)];
  3551. }
  3552. GPBClearMessageField(obj, field);
  3553. });
  3554. result.encodingSelector = @selector(setBool:);
  3555. break;
  3556. }
  3557. }
  3558. } else {
  3559. // See comment about __unsafe_unretained on ResolveIvarGet.
  3560. for (__unsafe_unretained GPBFieldDescriptor *field in descriptor->fields_) {
  3561. BOOL isMapOrArray = GPBFieldIsMapOrArray(field);
  3562. if (GPBIsGetSelForField(selName, field)) {
  3563. if (isMapOrArray) {
  3564. if (field.fieldType == GPBFieldTypeRepeated) {
  3565. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  3566. return GetArrayIvarWithField(obj, field);
  3567. });
  3568. } else {
  3569. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  3570. return GetMapIvarWithField(obj, field);
  3571. });
  3572. }
  3573. result.encodingSelector = @selector(getArray);
  3574. } else {
  3575. ResolveIvarGet(field, &result);
  3576. }
  3577. break;
  3578. }
  3579. if (!isMapOrArray) {
  3580. if (GPBIsHasSelForField(selName, selNameLength, field)) {
  3581. int32_t index = GPBFieldHasIndex(field);
  3582. uint32_t fieldNum = GPBFieldNumber(field);
  3583. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  3584. return GPBGetHasIvar(obj, index, fieldNum);
  3585. });
  3586. result.encodingSelector = @selector(getBool);
  3587. break;
  3588. } else {
  3589. GPBOneofDescriptor *oneof = field->containingOneof_;
  3590. if (oneof && GPBIsCaseOfSelForOneOf(selName, selNameLength, oneof)) {
  3591. int32_t index = GPBFieldHasIndex(field);
  3592. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  3593. return GPBGetHasOneof(obj, index);
  3594. });
  3595. result.encodingSelector = @selector(getEnum);
  3596. break;
  3597. }
  3598. }
  3599. } else {
  3600. if (GPBIsCountSelForField(selName, selNameLength, field)) {
  3601. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  3602. // Type doesn't matter, all *Array and *Dictionary types support
  3603. // -count.
  3604. NSArray *arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(obj, field);
  3605. return [arrayOrMap count];
  3606. });
  3607. result.encodingSelector = @selector(getArrayCount);
  3608. break;
  3609. }
  3610. }
  3611. }
  3612. }
  3613. if (result.impToAdd) {
  3614. const char *encoding = GPBMessageEncodingForSelector(result.encodingSelector, YES);
  3615. Class msgClass = descriptor.messageClass;
  3616. BOOL methodAdded = class_addMethod(msgClass, sel, result.impToAdd, encoding);
  3617. // class_addMethod() is documented as also failing if the method was already
  3618. // added; so we check if the method is already there and return success so
  3619. // the method dispatch will still happen. Why would it already be added?
  3620. // Two threads could cause the same method to be bound at the same time,
  3621. // but only one will actually bind it; the other still needs to return true
  3622. // so things will dispatch.
  3623. if (!methodAdded) {
  3624. methodAdded = GPBClassHasSel(msgClass, sel);
  3625. }
  3626. return methodAdded;
  3627. }
  3628. return [super resolveInstanceMethod:sel];
  3629. }
  3630. + (BOOL)resolveClassMethod:(SEL)sel {
  3631. // Extensions scoped to a Message and looked up via class methods.
  3632. if (GPBResolveExtensionClassMethod(self, sel)) {
  3633. return YES;
  3634. }
  3635. return [super resolveClassMethod:sel];
  3636. }
  3637. #pragma mark - NSCoding Support
  3638. + (BOOL)supportsSecureCoding {
  3639. return YES;
  3640. }
  3641. - (instancetype)initWithCoder:(NSCoder *)aDecoder {
  3642. self = [self init];
  3643. if (self) {
  3644. NSData *data = [aDecoder decodeObjectOfClass:[NSData class] forKey:kGPBDataCoderKey];
  3645. if (data.length) {
  3646. GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data];
  3647. @try {
  3648. [self mergeFromCodedInputStream:input extensionRegistry:nil endingTag:0];
  3649. } @finally {
  3650. [input release];
  3651. }
  3652. }
  3653. }
  3654. return self;
  3655. }
  3656. - (void)encodeWithCoder:(NSCoder *)aCoder {
  3657. #if defined(DEBUG) && DEBUG
  3658. if (extensionMap_.count) {
  3659. // Hint to go along with the docs on GPBMessage about this.
  3660. //
  3661. // Note: This is incomplete, in that it only checked the "root" message,
  3662. // if a sub message in a field has extensions, the issue still exists. A
  3663. // recursive check could be done here (like the work in
  3664. // GPBMessageDropUnknownFieldsRecursively()), but that has the potential to
  3665. // be expensive and could slow down serialization in DEBUG enough to cause
  3666. // developers other problems.
  3667. NSLog(@"Warning: writing out a GPBMessage (%@) via NSCoding and it"
  3668. @" has %ld extensions; when read back in, those fields will be"
  3669. @" in the unknownFields property instead.",
  3670. [self class], (long)extensionMap_.count);
  3671. }
  3672. #endif
  3673. NSData *data = [self data];
  3674. if (data.length) {
  3675. [aCoder encodeObject:data forKey:kGPBDataCoderKey];
  3676. }
  3677. }
  3678. #pragma mark - KVC Support
  3679. + (BOOL)accessInstanceVariablesDirectly {
  3680. // Make sure KVC doesn't use instance variables.
  3681. return NO;
  3682. }
  3683. @end
  3684. #pragma mark - Messages from GPBUtilities.h but defined here for access to helpers.
  3685. // Only exists for public api, no core code should use this.
  3686. id GPBGetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field) {
  3687. #if defined(DEBUG) && DEBUG
  3688. if (field.fieldType != GPBFieldTypeRepeated) {
  3689. [NSException raise:NSInvalidArgumentException
  3690. format:@"%@.%@ is not a repeated field.", [self class], field.name];
  3691. }
  3692. #endif
  3693. return GetOrCreateArrayIvarWithField(self, field);
  3694. }
  3695. // Only exists for public api, no core code should use this.
  3696. id GPBGetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field) {
  3697. #if defined(DEBUG) && DEBUG
  3698. if (field.fieldType != GPBFieldTypeMap) {
  3699. [NSException raise:NSInvalidArgumentException
  3700. format:@"%@.%@ is not a map<> field.", [self class], field.name];
  3701. }
  3702. #endif
  3703. return GetOrCreateMapIvarWithField(self, field);
  3704. }
  3705. id GPBGetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
  3706. NSCAssert(!GPBFieldIsMapOrArray(field), @"Shouldn't get here");
  3707. if (!GPBFieldDataTypeIsMessage(field)) {
  3708. if (GPBGetHasIvarField(self, field)) {
  3709. uint8_t *storage = (uint8_t *)self->messageStorage_;
  3710. id *typePtr = (id *)&storage[field->description_->offset];
  3711. return *typePtr;
  3712. }
  3713. // Not set...non messages (string/data), get their default.
  3714. return field.defaultValue.valueMessage;
  3715. }
  3716. uint8_t *storage = (uint8_t *)self->messageStorage_;
  3717. _Atomic(id) *typePtr = (_Atomic(id) *)&storage[field->description_->offset];
  3718. id msg = atomic_load(typePtr);
  3719. if (msg) {
  3720. return msg;
  3721. }
  3722. id expected = nil;
  3723. id autocreated = GPBCreateMessageWithAutocreator(field.msgClass, self, field);
  3724. if (atomic_compare_exchange_strong(typePtr, &expected, autocreated)) {
  3725. // Value was set, return it.
  3726. return autocreated;
  3727. }
  3728. // Some other thread set it, release the one created and return what got set.
  3729. GPBClearMessageAutocreator(autocreated);
  3730. [autocreated release];
  3731. return expected;
  3732. }
  3733. NSData *GPBMessageUnknownFieldsData(GPBMessage *self) {
  3734. NSData *result = nil;
  3735. @synchronized(self) {
  3736. #pragma clang diagnostic push
  3737. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  3738. GPBUnknownFieldSet *unknownFields = self->unknownFields_;
  3739. #pragma clang diagnostic pop
  3740. if (unknownFields) {
  3741. #if defined(DEBUG) && DEBUG
  3742. NSCAssert(self->unknownFieldData_ == nil, @"Internal error both unknown states were set");
  3743. #endif
  3744. if (self.descriptor.isWireFormat) {
  3745. NSMutableData *mutableData =
  3746. [NSMutableData dataWithLength:unknownFields.serializedSizeAsMessageSet];
  3747. GPBCodedOutputStream *output = [[GPBCodedOutputStream alloc] initWithData:mutableData];
  3748. [unknownFields writeAsMessageSetTo:output];
  3749. [output flush];
  3750. [output release];
  3751. result = mutableData;
  3752. } else {
  3753. result = [unknownFields data];
  3754. }
  3755. } else {
  3756. // Internally we can borrow it without a copy since this is immediately used by callers
  3757. // and multithreaded access with any mutation is not allow on messages.
  3758. result = self->unknownFieldData_;
  3759. }
  3760. } // @synchronized(self)
  3761. return result;
  3762. }
  3763. #pragma clang diagnostic pop