GPBMessage.m 127 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. #import "GPBMessage_PackagePrivate.h"
  31. #import <objc/runtime.h>
  32. #import <objc/message.h>
  33. #import <stdatomic.h>
  34. #import "GPBArray_PackagePrivate.h"
  35. #import "GPBCodedInputStream_PackagePrivate.h"
  36. #import "GPBCodedOutputStream_PackagePrivate.h"
  37. #import "GPBDescriptor_PackagePrivate.h"
  38. #import "GPBDictionary_PackagePrivate.h"
  39. #import "GPBExtensionInternals.h"
  40. #import "GPBExtensionRegistry.h"
  41. #import "GPBRootObject_PackagePrivate.h"
  42. #import "GPBUnknownFieldSet_PackagePrivate.h"
  43. #import "GPBUtilities_PackagePrivate.h"
  44. // Direct access is use for speed, to avoid even internally declaring things
  45. // read/write, etc. The warning is enabled in the project to ensure code calling
  46. // protos can turn on -Wdirect-ivar-access without issues.
  47. #pragma clang diagnostic push
  48. #pragma clang diagnostic ignored "-Wdirect-ivar-access"
  49. NSString *const GPBMessageErrorDomain =
  50. GPBNSStringifySymbol(GPBMessageErrorDomain);
  51. NSString *const GPBErrorReasonKey = @"Reason";
  52. static NSString *const kGPBDataCoderKey = @"GPBData";
  53. //
  54. // PLEASE REMEMBER:
  55. //
  56. // This is the base class for *all* messages generated, so any selector defined,
  57. // *public* or *private* could end up colliding with a proto message field. So
  58. // avoid using selectors that could match a property, use C functions to hide
  59. // them, etc.
  60. //
  61. @interface GPBMessage () {
  62. @package
  63. GPBUnknownFieldSet *unknownFields_;
  64. NSMutableDictionary *extensionMap_;
  65. NSMutableDictionary *autocreatedExtensionMap_;
  66. // If the object was autocreated, we remember the creator so that if we get
  67. // mutated, we can inform the creator to make our field visible.
  68. GPBMessage *autocreator_;
  69. GPBFieldDescriptor *autocreatorField_;
  70. GPBExtensionDescriptor *autocreatorExtension_;
  71. // A lock to provide mutual exclusion from internal data that can be modified
  72. // by *read* operations such as getters (autocreation of message fields and
  73. // message extensions, not setting of values). Used to guarantee thread safety
  74. // for concurrent reads on the message.
  75. // NOTE: OSSpinLock may seem like a good fit here but Apple engineers have
  76. // pointed out that they are vulnerable to live locking on iOS in cases of
  77. // priority inversion:
  78. // http://mjtsai.com/blog/2015/12/16/osspinlock-is-unsafe/
  79. // https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000372.html
  80. // Use of readOnlySemaphore_ must be prefaced by a call to
  81. // GPBPrepareReadOnlySemaphore to ensure it has been created. This allows
  82. // readOnlySemaphore_ to be only created when actually needed.
  83. _Atomic(dispatch_semaphore_t) readOnlySemaphore_;
  84. }
  85. @end
  86. static id CreateArrayForField(GPBFieldDescriptor *field,
  87. GPBMessage *autocreator)
  88. __attribute__((ns_returns_retained));
  89. static id GetOrCreateArrayIvarWithField(GPBMessage *self,
  90. GPBFieldDescriptor *field,
  91. GPBFileSyntax syntax);
  92. static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
  93. static id CreateMapForField(GPBFieldDescriptor *field,
  94. GPBMessage *autocreator)
  95. __attribute__((ns_returns_retained));
  96. static id GetOrCreateMapIvarWithField(GPBMessage *self,
  97. GPBFieldDescriptor *field,
  98. GPBFileSyntax syntax);
  99. static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
  100. static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap,
  101. NSZone *zone)
  102. __attribute__((ns_returns_retained));
  103. #ifdef DEBUG
  104. static NSError *MessageError(NSInteger code, NSDictionary *userInfo) {
  105. return [NSError errorWithDomain:GPBMessageErrorDomain
  106. code:code
  107. userInfo:userInfo];
  108. }
  109. #endif
  110. static NSError *ErrorFromException(NSException *exception) {
  111. NSError *error = nil;
  112. if ([exception.name isEqual:GPBCodedInputStreamException]) {
  113. NSDictionary *exceptionInfo = exception.userInfo;
  114. error = exceptionInfo[GPBCodedInputStreamUnderlyingErrorKey];
  115. }
  116. if (!error) {
  117. NSString *reason = exception.reason;
  118. NSDictionary *userInfo = nil;
  119. if ([reason length]) {
  120. userInfo = @{ GPBErrorReasonKey : reason };
  121. }
  122. error = [NSError errorWithDomain:GPBMessageErrorDomain
  123. code:GPBMessageErrorCodeOther
  124. userInfo:userInfo];
  125. }
  126. return error;
  127. }
  128. static void CheckExtension(GPBMessage *self,
  129. GPBExtensionDescriptor *extension) {
  130. if (![self isKindOfClass:extension.containingMessageClass]) {
  131. [NSException
  132. raise:NSInvalidArgumentException
  133. format:@"Extension %@ used on wrong class (%@ instead of %@)",
  134. extension.singletonName,
  135. [self class], extension.containingMessageClass];
  136. }
  137. }
  138. static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap,
  139. NSZone *zone) {
  140. if (extensionMap.count == 0) {
  141. return nil;
  142. }
  143. NSMutableDictionary *result = [[NSMutableDictionary allocWithZone:zone]
  144. initWithCapacity:extensionMap.count];
  145. for (GPBExtensionDescriptor *extension in extensionMap) {
  146. id value = [extensionMap objectForKey:extension];
  147. BOOL isMessageExtension = GPBExtensionIsMessage(extension);
  148. if (extension.repeated) {
  149. if (isMessageExtension) {
  150. NSMutableArray *list =
  151. [[NSMutableArray alloc] initWithCapacity:[value count]];
  152. for (GPBMessage *listValue in value) {
  153. GPBMessage *copiedValue = [listValue copyWithZone:zone];
  154. [list addObject:copiedValue];
  155. [copiedValue release];
  156. }
  157. [result setObject:list forKey:extension];
  158. [list release];
  159. } else {
  160. NSMutableArray *copiedValue = [value mutableCopyWithZone:zone];
  161. [result setObject:copiedValue forKey:extension];
  162. [copiedValue release];
  163. }
  164. } else {
  165. if (isMessageExtension) {
  166. GPBMessage *copiedValue = [value copyWithZone:zone];
  167. [result setObject:copiedValue forKey:extension];
  168. [copiedValue release];
  169. } else {
  170. [result setObject:value forKey:extension];
  171. }
  172. }
  173. }
  174. return result;
  175. }
  176. static id CreateArrayForField(GPBFieldDescriptor *field,
  177. GPBMessage *autocreator) {
  178. id result;
  179. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  180. switch (fieldDataType) {
  181. case GPBDataTypeBool:
  182. result = [[GPBBoolArray alloc] init];
  183. break;
  184. case GPBDataTypeFixed32:
  185. case GPBDataTypeUInt32:
  186. result = [[GPBUInt32Array alloc] init];
  187. break;
  188. case GPBDataTypeInt32:
  189. case GPBDataTypeSFixed32:
  190. case GPBDataTypeSInt32:
  191. result = [[GPBInt32Array alloc] init];
  192. break;
  193. case GPBDataTypeFixed64:
  194. case GPBDataTypeUInt64:
  195. result = [[GPBUInt64Array alloc] init];
  196. break;
  197. case GPBDataTypeInt64:
  198. case GPBDataTypeSFixed64:
  199. case GPBDataTypeSInt64:
  200. result = [[GPBInt64Array alloc] init];
  201. break;
  202. case GPBDataTypeFloat:
  203. result = [[GPBFloatArray alloc] init];
  204. break;
  205. case GPBDataTypeDouble:
  206. result = [[GPBDoubleArray alloc] init];
  207. break;
  208. case GPBDataTypeEnum:
  209. result = [[GPBEnumArray alloc]
  210. initWithValidationFunction:field.enumDescriptor.enumVerifier];
  211. break;
  212. case GPBDataTypeBytes:
  213. case GPBDataTypeGroup:
  214. case GPBDataTypeMessage:
  215. case GPBDataTypeString:
  216. if (autocreator) {
  217. result = [[GPBAutocreatedArray alloc] init];
  218. } else {
  219. result = [[NSMutableArray alloc] init];
  220. }
  221. break;
  222. }
  223. if (autocreator) {
  224. if (GPBDataTypeIsObject(fieldDataType)) {
  225. GPBAutocreatedArray *autoArray = result;
  226. autoArray->_autocreator = autocreator;
  227. } else {
  228. GPBInt32Array *gpbArray = result;
  229. gpbArray->_autocreator = autocreator;
  230. }
  231. }
  232. return result;
  233. }
  234. static id CreateMapForField(GPBFieldDescriptor *field,
  235. GPBMessage *autocreator) {
  236. id result;
  237. GPBDataType keyDataType = field.mapKeyDataType;
  238. GPBDataType valueDataType = GPBGetFieldDataType(field);
  239. switch (keyDataType) {
  240. case GPBDataTypeBool:
  241. switch (valueDataType) {
  242. case GPBDataTypeBool:
  243. result = [[GPBBoolBoolDictionary alloc] init];
  244. break;
  245. case GPBDataTypeFixed32:
  246. case GPBDataTypeUInt32:
  247. result = [[GPBBoolUInt32Dictionary alloc] init];
  248. break;
  249. case GPBDataTypeInt32:
  250. case GPBDataTypeSFixed32:
  251. case GPBDataTypeSInt32:
  252. result = [[GPBBoolInt32Dictionary alloc] init];
  253. break;
  254. case GPBDataTypeFixed64:
  255. case GPBDataTypeUInt64:
  256. result = [[GPBBoolUInt64Dictionary alloc] init];
  257. break;
  258. case GPBDataTypeInt64:
  259. case GPBDataTypeSFixed64:
  260. case GPBDataTypeSInt64:
  261. result = [[GPBBoolInt64Dictionary alloc] init];
  262. break;
  263. case GPBDataTypeFloat:
  264. result = [[GPBBoolFloatDictionary alloc] init];
  265. break;
  266. case GPBDataTypeDouble:
  267. result = [[GPBBoolDoubleDictionary alloc] init];
  268. break;
  269. case GPBDataTypeEnum:
  270. result = [[GPBBoolEnumDictionary alloc]
  271. initWithValidationFunction:field.enumDescriptor.enumVerifier];
  272. break;
  273. case GPBDataTypeBytes:
  274. case GPBDataTypeMessage:
  275. case GPBDataTypeString:
  276. result = [[GPBBoolObjectDictionary alloc] init];
  277. break;
  278. case GPBDataTypeGroup:
  279. NSCAssert(NO, @"shouldn't happen");
  280. return nil;
  281. }
  282. break;
  283. case GPBDataTypeFixed32:
  284. case GPBDataTypeUInt32:
  285. switch (valueDataType) {
  286. case GPBDataTypeBool:
  287. result = [[GPBUInt32BoolDictionary alloc] init];
  288. break;
  289. case GPBDataTypeFixed32:
  290. case GPBDataTypeUInt32:
  291. result = [[GPBUInt32UInt32Dictionary alloc] init];
  292. break;
  293. case GPBDataTypeInt32:
  294. case GPBDataTypeSFixed32:
  295. case GPBDataTypeSInt32:
  296. result = [[GPBUInt32Int32Dictionary alloc] init];
  297. break;
  298. case GPBDataTypeFixed64:
  299. case GPBDataTypeUInt64:
  300. result = [[GPBUInt32UInt64Dictionary alloc] init];
  301. break;
  302. case GPBDataTypeInt64:
  303. case GPBDataTypeSFixed64:
  304. case GPBDataTypeSInt64:
  305. result = [[GPBUInt32Int64Dictionary alloc] init];
  306. break;
  307. case GPBDataTypeFloat:
  308. result = [[GPBUInt32FloatDictionary alloc] init];
  309. break;
  310. case GPBDataTypeDouble:
  311. result = [[GPBUInt32DoubleDictionary alloc] init];
  312. break;
  313. case GPBDataTypeEnum:
  314. result = [[GPBUInt32EnumDictionary alloc]
  315. initWithValidationFunction:field.enumDescriptor.enumVerifier];
  316. break;
  317. case GPBDataTypeBytes:
  318. case GPBDataTypeMessage:
  319. case GPBDataTypeString:
  320. result = [[GPBUInt32ObjectDictionary alloc] init];
  321. break;
  322. case GPBDataTypeGroup:
  323. NSCAssert(NO, @"shouldn't happen");
  324. return nil;
  325. }
  326. break;
  327. case GPBDataTypeInt32:
  328. case GPBDataTypeSFixed32:
  329. case GPBDataTypeSInt32:
  330. switch (valueDataType) {
  331. case GPBDataTypeBool:
  332. result = [[GPBInt32BoolDictionary alloc] init];
  333. break;
  334. case GPBDataTypeFixed32:
  335. case GPBDataTypeUInt32:
  336. result = [[GPBInt32UInt32Dictionary alloc] init];
  337. break;
  338. case GPBDataTypeInt32:
  339. case GPBDataTypeSFixed32:
  340. case GPBDataTypeSInt32:
  341. result = [[GPBInt32Int32Dictionary alloc] init];
  342. break;
  343. case GPBDataTypeFixed64:
  344. case GPBDataTypeUInt64:
  345. result = [[GPBInt32UInt64Dictionary alloc] init];
  346. break;
  347. case GPBDataTypeInt64:
  348. case GPBDataTypeSFixed64:
  349. case GPBDataTypeSInt64:
  350. result = [[GPBInt32Int64Dictionary alloc] init];
  351. break;
  352. case GPBDataTypeFloat:
  353. result = [[GPBInt32FloatDictionary alloc] init];
  354. break;
  355. case GPBDataTypeDouble:
  356. result = [[GPBInt32DoubleDictionary alloc] init];
  357. break;
  358. case GPBDataTypeEnum:
  359. result = [[GPBInt32EnumDictionary alloc]
  360. initWithValidationFunction:field.enumDescriptor.enumVerifier];
  361. break;
  362. case GPBDataTypeBytes:
  363. case GPBDataTypeMessage:
  364. case GPBDataTypeString:
  365. result = [[GPBInt32ObjectDictionary alloc] init];
  366. break;
  367. case GPBDataTypeGroup:
  368. NSCAssert(NO, @"shouldn't happen");
  369. return nil;
  370. }
  371. break;
  372. case GPBDataTypeFixed64:
  373. case GPBDataTypeUInt64:
  374. switch (valueDataType) {
  375. case GPBDataTypeBool:
  376. result = [[GPBUInt64BoolDictionary alloc] init];
  377. break;
  378. case GPBDataTypeFixed32:
  379. case GPBDataTypeUInt32:
  380. result = [[GPBUInt64UInt32Dictionary alloc] init];
  381. break;
  382. case GPBDataTypeInt32:
  383. case GPBDataTypeSFixed32:
  384. case GPBDataTypeSInt32:
  385. result = [[GPBUInt64Int32Dictionary alloc] init];
  386. break;
  387. case GPBDataTypeFixed64:
  388. case GPBDataTypeUInt64:
  389. result = [[GPBUInt64UInt64Dictionary alloc] init];
  390. break;
  391. case GPBDataTypeInt64:
  392. case GPBDataTypeSFixed64:
  393. case GPBDataTypeSInt64:
  394. result = [[GPBUInt64Int64Dictionary alloc] init];
  395. break;
  396. case GPBDataTypeFloat:
  397. result = [[GPBUInt64FloatDictionary alloc] init];
  398. break;
  399. case GPBDataTypeDouble:
  400. result = [[GPBUInt64DoubleDictionary alloc] init];
  401. break;
  402. case GPBDataTypeEnum:
  403. result = [[GPBUInt64EnumDictionary alloc]
  404. initWithValidationFunction:field.enumDescriptor.enumVerifier];
  405. break;
  406. case GPBDataTypeBytes:
  407. case GPBDataTypeMessage:
  408. case GPBDataTypeString:
  409. result = [[GPBUInt64ObjectDictionary alloc] init];
  410. break;
  411. case GPBDataTypeGroup:
  412. NSCAssert(NO, @"shouldn't happen");
  413. return nil;
  414. }
  415. break;
  416. case GPBDataTypeInt64:
  417. case GPBDataTypeSFixed64:
  418. case GPBDataTypeSInt64:
  419. switch (valueDataType) {
  420. case GPBDataTypeBool:
  421. result = [[GPBInt64BoolDictionary alloc] init];
  422. break;
  423. case GPBDataTypeFixed32:
  424. case GPBDataTypeUInt32:
  425. result = [[GPBInt64UInt32Dictionary alloc] init];
  426. break;
  427. case GPBDataTypeInt32:
  428. case GPBDataTypeSFixed32:
  429. case GPBDataTypeSInt32:
  430. result = [[GPBInt64Int32Dictionary alloc] init];
  431. break;
  432. case GPBDataTypeFixed64:
  433. case GPBDataTypeUInt64:
  434. result = [[GPBInt64UInt64Dictionary alloc] init];
  435. break;
  436. case GPBDataTypeInt64:
  437. case GPBDataTypeSFixed64:
  438. case GPBDataTypeSInt64:
  439. result = [[GPBInt64Int64Dictionary alloc] init];
  440. break;
  441. case GPBDataTypeFloat:
  442. result = [[GPBInt64FloatDictionary alloc] init];
  443. break;
  444. case GPBDataTypeDouble:
  445. result = [[GPBInt64DoubleDictionary alloc] init];
  446. break;
  447. case GPBDataTypeEnum:
  448. result = [[GPBInt64EnumDictionary alloc]
  449. initWithValidationFunction:field.enumDescriptor.enumVerifier];
  450. break;
  451. case GPBDataTypeBytes:
  452. case GPBDataTypeMessage:
  453. case GPBDataTypeString:
  454. result = [[GPBInt64ObjectDictionary alloc] init];
  455. break;
  456. case GPBDataTypeGroup:
  457. NSCAssert(NO, @"shouldn't happen");
  458. return nil;
  459. }
  460. break;
  461. case GPBDataTypeString:
  462. switch (valueDataType) {
  463. case GPBDataTypeBool:
  464. result = [[GPBStringBoolDictionary alloc] init];
  465. break;
  466. case GPBDataTypeFixed32:
  467. case GPBDataTypeUInt32:
  468. result = [[GPBStringUInt32Dictionary alloc] init];
  469. break;
  470. case GPBDataTypeInt32:
  471. case GPBDataTypeSFixed32:
  472. case GPBDataTypeSInt32:
  473. result = [[GPBStringInt32Dictionary alloc] init];
  474. break;
  475. case GPBDataTypeFixed64:
  476. case GPBDataTypeUInt64:
  477. result = [[GPBStringUInt64Dictionary alloc] init];
  478. break;
  479. case GPBDataTypeInt64:
  480. case GPBDataTypeSFixed64:
  481. case GPBDataTypeSInt64:
  482. result = [[GPBStringInt64Dictionary alloc] init];
  483. break;
  484. case GPBDataTypeFloat:
  485. result = [[GPBStringFloatDictionary alloc] init];
  486. break;
  487. case GPBDataTypeDouble:
  488. result = [[GPBStringDoubleDictionary alloc] init];
  489. break;
  490. case GPBDataTypeEnum:
  491. result = [[GPBStringEnumDictionary alloc]
  492. initWithValidationFunction:field.enumDescriptor.enumVerifier];
  493. break;
  494. case GPBDataTypeBytes:
  495. case GPBDataTypeMessage:
  496. case GPBDataTypeString:
  497. if (autocreator) {
  498. result = [[GPBAutocreatedDictionary alloc] init];
  499. } else {
  500. result = [[NSMutableDictionary alloc] init];
  501. }
  502. break;
  503. case GPBDataTypeGroup:
  504. NSCAssert(NO, @"shouldn't happen");
  505. return nil;
  506. }
  507. break;
  508. case GPBDataTypeFloat:
  509. case GPBDataTypeDouble:
  510. case GPBDataTypeEnum:
  511. case GPBDataTypeBytes:
  512. case GPBDataTypeGroup:
  513. case GPBDataTypeMessage:
  514. NSCAssert(NO, @"shouldn't happen");
  515. return nil;
  516. }
  517. if (autocreator) {
  518. if ((keyDataType == GPBDataTypeString) &&
  519. GPBDataTypeIsObject(valueDataType)) {
  520. GPBAutocreatedDictionary *autoDict = result;
  521. autoDict->_autocreator = autocreator;
  522. } else {
  523. GPBInt32Int32Dictionary *gpbDict = result;
  524. gpbDict->_autocreator = autocreator;
  525. }
  526. }
  527. return result;
  528. }
  529. #if !defined(__clang_analyzer__)
  530. // These functions are blocked from the analyzer because the analyzer sees the
  531. // GPBSetRetainedObjectIvarWithFieldInternal() call as consuming the array/map,
  532. // so use of the array/map after the call returns is flagged as a use after
  533. // free.
  534. // But GPBSetRetainedObjectIvarWithFieldInternal() is "consuming" the retain
  535. // count be holding onto the object (it is transferring it), the object is
  536. // still valid after returning from the call. The other way to avoid this
  537. // would be to add a -retain/-autorelease, but that would force every
  538. // repeated/map field parsed into the autorelease pool which is both a memory
  539. // and performance hit.
  540. static id GetOrCreateArrayIvarWithField(GPBMessage *self,
  541. GPBFieldDescriptor *field,
  542. GPBFileSyntax syntax) {
  543. id array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  544. if (!array) {
  545. // No lock needed, this is called from places expecting to mutate
  546. // so no threading protection is needed.
  547. array = CreateArrayForField(field, nil);
  548. GPBSetRetainedObjectIvarWithFieldInternal(self, field, array, syntax);
  549. }
  550. return array;
  551. }
  552. // This is like GPBGetObjectIvarWithField(), but for arrays, it should
  553. // only be used to wire the method into the class.
  554. static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
  555. id array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  556. if (!array) {
  557. // Check again after getting the lock.
  558. GPBPrepareReadOnlySemaphore(self);
  559. dispatch_semaphore_wait(self->readOnlySemaphore_, DISPATCH_TIME_FOREVER);
  560. array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  561. if (!array) {
  562. array = CreateArrayForField(field, self);
  563. GPBSetAutocreatedRetainedObjectIvarWithField(self, field, array);
  564. }
  565. dispatch_semaphore_signal(self->readOnlySemaphore_);
  566. }
  567. return array;
  568. }
  569. static id GetOrCreateMapIvarWithField(GPBMessage *self,
  570. GPBFieldDescriptor *field,
  571. GPBFileSyntax syntax) {
  572. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  573. if (!dict) {
  574. // No lock needed, this is called from places expecting to mutate
  575. // so no threading protection is needed.
  576. dict = CreateMapForField(field, nil);
  577. GPBSetRetainedObjectIvarWithFieldInternal(self, field, dict, syntax);
  578. }
  579. return dict;
  580. }
  581. // This is like GPBGetObjectIvarWithField(), but for maps, it should
  582. // only be used to wire the method into the class.
  583. static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
  584. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  585. if (!dict) {
  586. // Check again after getting the lock.
  587. GPBPrepareReadOnlySemaphore(self);
  588. dispatch_semaphore_wait(self->readOnlySemaphore_, DISPATCH_TIME_FOREVER);
  589. dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  590. if (!dict) {
  591. dict = CreateMapForField(field, self);
  592. GPBSetAutocreatedRetainedObjectIvarWithField(self, field, dict);
  593. }
  594. dispatch_semaphore_signal(self->readOnlySemaphore_);
  595. }
  596. return dict;
  597. }
  598. #endif // !defined(__clang_analyzer__)
  599. GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass,
  600. GPBMessage *autocreator,
  601. GPBFieldDescriptor *field) {
  602. GPBMessage *message = [[msgClass alloc] init];
  603. message->autocreator_ = autocreator;
  604. message->autocreatorField_ = [field retain];
  605. return message;
  606. }
  607. static GPBMessage *CreateMessageWithAutocreatorForExtension(
  608. Class msgClass, GPBMessage *autocreator, GPBExtensionDescriptor *extension)
  609. __attribute__((ns_returns_retained));
  610. static GPBMessage *CreateMessageWithAutocreatorForExtension(
  611. Class msgClass, GPBMessage *autocreator,
  612. GPBExtensionDescriptor *extension) {
  613. GPBMessage *message = [[msgClass alloc] init];
  614. message->autocreator_ = autocreator;
  615. message->autocreatorExtension_ = [extension retain];
  616. return message;
  617. }
  618. BOOL GPBWasMessageAutocreatedBy(GPBMessage *message, GPBMessage *parent) {
  619. return (message->autocreator_ == parent);
  620. }
  621. void GPBBecomeVisibleToAutocreator(GPBMessage *self) {
  622. // Message objects that are implicitly created by accessing a message field
  623. // are initially not visible via the hasX selector. This method makes them
  624. // visible.
  625. if (self->autocreator_) {
  626. // This will recursively make all parent messages visible until it reaches a
  627. // super-creator that's visible.
  628. if (self->autocreatorField_) {
  629. GPBFileSyntax syntax = [self->autocreator_ descriptor].file.syntax;
  630. GPBSetObjectIvarWithFieldInternal(self->autocreator_,
  631. self->autocreatorField_, self, syntax);
  632. } else {
  633. [self->autocreator_ setExtension:self->autocreatorExtension_ value:self];
  634. }
  635. }
  636. }
  637. void GPBAutocreatedArrayModified(GPBMessage *self, id array) {
  638. // When one of our autocreated arrays adds elements, make it visible.
  639. GPBDescriptor *descriptor = [[self class] descriptor];
  640. for (GPBFieldDescriptor *field in descriptor->fields_) {
  641. if (field.fieldType == GPBFieldTypeRepeated) {
  642. id curArray = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  643. if (curArray == array) {
  644. if (GPBFieldDataTypeIsObject(field)) {
  645. GPBAutocreatedArray *autoArray = array;
  646. autoArray->_autocreator = nil;
  647. } else {
  648. GPBInt32Array *gpbArray = array;
  649. gpbArray->_autocreator = nil;
  650. }
  651. GPBBecomeVisibleToAutocreator(self);
  652. return;
  653. }
  654. }
  655. }
  656. NSCAssert(NO, @"Unknown autocreated %@ for %@.", [array class], self);
  657. }
  658. void GPBAutocreatedDictionaryModified(GPBMessage *self, id dictionary) {
  659. // When one of our autocreated dicts adds elements, make it visible.
  660. GPBDescriptor *descriptor = [[self class] descriptor];
  661. for (GPBFieldDescriptor *field in descriptor->fields_) {
  662. if (field.fieldType == GPBFieldTypeMap) {
  663. id curDict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  664. if (curDict == dictionary) {
  665. if ((field.mapKeyDataType == GPBDataTypeString) &&
  666. GPBFieldDataTypeIsObject(field)) {
  667. GPBAutocreatedDictionary *autoDict = dictionary;
  668. autoDict->_autocreator = nil;
  669. } else {
  670. GPBInt32Int32Dictionary *gpbDict = dictionary;
  671. gpbDict->_autocreator = nil;
  672. }
  673. GPBBecomeVisibleToAutocreator(self);
  674. return;
  675. }
  676. }
  677. }
  678. NSCAssert(NO, @"Unknown autocreated %@ for %@.", [dictionary class], self);
  679. }
  680. void GPBClearMessageAutocreator(GPBMessage *self) {
  681. if ((self == nil) || !self->autocreator_) {
  682. return;
  683. }
  684. #if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS)
  685. // Either the autocreator must have its "has" flag set to YES, or it must be
  686. // NO and not equal to ourselves.
  687. BOOL autocreatorHas =
  688. (self->autocreatorField_
  689. ? GPBGetHasIvarField(self->autocreator_, self->autocreatorField_)
  690. : [self->autocreator_ hasExtension:self->autocreatorExtension_]);
  691. GPBMessage *autocreatorFieldValue =
  692. (self->autocreatorField_
  693. ? GPBGetObjectIvarWithFieldNoAutocreate(self->autocreator_,
  694. self->autocreatorField_)
  695. : [self->autocreator_->autocreatedExtensionMap_
  696. objectForKey:self->autocreatorExtension_]);
  697. NSCAssert(autocreatorHas || autocreatorFieldValue != self,
  698. @"Cannot clear autocreator because it still refers to self, self: %@.",
  699. self);
  700. #endif // DEBUG && !defined(NS_BLOCK_ASSERTIONS)
  701. self->autocreator_ = nil;
  702. [self->autocreatorField_ release];
  703. self->autocreatorField_ = nil;
  704. [self->autocreatorExtension_ release];
  705. self->autocreatorExtension_ = nil;
  706. }
  707. // Call this before using the readOnlySemaphore_. This ensures it is created only once.
  708. void GPBPrepareReadOnlySemaphore(GPBMessage *self) {
  709. #pragma clang diagnostic push
  710. #pragma clang diagnostic ignored "-Wdirect-ivar-access"
  711. // Create the semaphore on demand (rather than init) as developers might not cause them
  712. // to be needed, and the heap usage can add up. The atomic swap is used to avoid needing
  713. // another lock around creating it.
  714. if (self->readOnlySemaphore_ == nil) {
  715. dispatch_semaphore_t worker = dispatch_semaphore_create(1);
  716. dispatch_semaphore_t expected = nil;
  717. if (!atomic_compare_exchange_strong(&self->readOnlySemaphore_, &expected, worker)) {
  718. dispatch_release(worker);
  719. }
  720. #if defined(__clang_analyzer__)
  721. // The Xcode 9.2 (and 9.3 beta) static analyzer thinks worker is leaked
  722. // (doesn't seem to know about atomic_compare_exchange_strong); so just
  723. // for the analyzer, let it think worker is also released in this case.
  724. else { dispatch_release(worker); }
  725. #endif
  726. }
  727. #pragma clang diagnostic pop
  728. }
  729. static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
  730. if (!self->unknownFields_) {
  731. self->unknownFields_ = [[GPBUnknownFieldSet alloc] init];
  732. GPBBecomeVisibleToAutocreator(self);
  733. }
  734. return self->unknownFields_;
  735. }
  736. @implementation GPBMessage
  737. + (void)initialize {
  738. Class pbMessageClass = [GPBMessage class];
  739. if ([self class] == pbMessageClass) {
  740. // This is here to start up the "base" class descriptor.
  741. [self descriptor];
  742. // Message shares extension method resolving with GPBRootObject so insure
  743. // it is started up at the same time.
  744. (void)[GPBRootObject class];
  745. } else if ([self superclass] == pbMessageClass) {
  746. // This is here to start up all the "message" subclasses. Just needs to be
  747. // done for the messages, not any of the subclasses.
  748. // This must be done in initialize to enforce thread safety of start up of
  749. // the protocol buffer library.
  750. // Note: The generated code for -descriptor calls
  751. // +[GPBDescriptor allocDescriptorForClass:...], passing the GPBRootObject
  752. // subclass for the file. That call chain is what ensures that *Root class
  753. // is started up to support extension resolution off the message class
  754. // (+resolveClassMethod: below) in a thread safe manner.
  755. [self descriptor];
  756. }
  757. }
  758. + (instancetype)allocWithZone:(NSZone *)zone {
  759. // Override alloc to allocate our classes with the additional storage
  760. // required for the instance variables.
  761. GPBDescriptor *descriptor = [self descriptor];
  762. return NSAllocateObject(self, descriptor->storageSize_, zone);
  763. }
  764. + (instancetype)alloc {
  765. return [self allocWithZone:nil];
  766. }
  767. + (GPBDescriptor *)descriptor {
  768. // This is thread safe because it is called from +initialize.
  769. static GPBDescriptor *descriptor = NULL;
  770. static GPBFileDescriptor *fileDescriptor = NULL;
  771. if (!descriptor) {
  772. // Use a dummy file that marks it as proto2 syntax so when used generically
  773. // it supports unknowns/etc.
  774. fileDescriptor =
  775. [[GPBFileDescriptor alloc] initWithPackage:@"internal"
  776. syntax:GPBFileSyntaxProto2];
  777. descriptor = [GPBDescriptor allocDescriptorForClass:[GPBMessage class]
  778. rootClass:Nil
  779. file:fileDescriptor
  780. fields:NULL
  781. fieldCount:0
  782. storageSize:0
  783. flags:0];
  784. }
  785. return descriptor;
  786. }
  787. + (instancetype)message {
  788. return [[[self alloc] init] autorelease];
  789. }
  790. - (instancetype)init {
  791. if ((self = [super init])) {
  792. messageStorage_ = (GPBMessage_StoragePtr)(
  793. ((uint8_t *)self) + class_getInstanceSize([self class]));
  794. }
  795. return self;
  796. }
  797. - (instancetype)initWithData:(NSData *)data error:(NSError **)errorPtr {
  798. return [self initWithData:data extensionRegistry:nil error:errorPtr];
  799. }
  800. - (instancetype)initWithData:(NSData *)data
  801. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry
  802. error:(NSError **)errorPtr {
  803. if ((self = [self init])) {
  804. @try {
  805. [self mergeFromData:data extensionRegistry:extensionRegistry];
  806. if (errorPtr) {
  807. *errorPtr = nil;
  808. }
  809. }
  810. @catch (NSException *exception) {
  811. [self release];
  812. self = nil;
  813. if (errorPtr) {
  814. *errorPtr = ErrorFromException(exception);
  815. }
  816. }
  817. #ifdef DEBUG
  818. if (self && !self.initialized) {
  819. [self release];
  820. self = nil;
  821. if (errorPtr) {
  822. *errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil);
  823. }
  824. }
  825. #endif
  826. }
  827. return self;
  828. }
  829. - (instancetype)initWithCodedInputStream:(GPBCodedInputStream *)input
  830. extensionRegistry:
  831. (GPBExtensionRegistry *)extensionRegistry
  832. error:(NSError **)errorPtr {
  833. if ((self = [self init])) {
  834. @try {
  835. [self mergeFromCodedInputStream:input extensionRegistry:extensionRegistry];
  836. if (errorPtr) {
  837. *errorPtr = nil;
  838. }
  839. }
  840. @catch (NSException *exception) {
  841. [self release];
  842. self = nil;
  843. if (errorPtr) {
  844. *errorPtr = ErrorFromException(exception);
  845. }
  846. }
  847. #ifdef DEBUG
  848. if (self && !self.initialized) {
  849. [self release];
  850. self = nil;
  851. if (errorPtr) {
  852. *errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil);
  853. }
  854. }
  855. #endif
  856. }
  857. return self;
  858. }
  859. - (void)dealloc {
  860. [self internalClear:NO];
  861. NSCAssert(!autocreator_, @"Autocreator was not cleared before dealloc.");
  862. if (readOnlySemaphore_) {
  863. dispatch_release(readOnlySemaphore_);
  864. }
  865. [super dealloc];
  866. }
  867. - (void)copyFieldsInto:(GPBMessage *)message
  868. zone:(NSZone *)zone
  869. descriptor:(GPBDescriptor *)descriptor {
  870. // Copy all the storage...
  871. memcpy(message->messageStorage_, messageStorage_, descriptor->storageSize_);
  872. GPBFileSyntax syntax = descriptor.file.syntax;
  873. // Loop over the fields doing fixup...
  874. for (GPBFieldDescriptor *field in descriptor->fields_) {
  875. if (GPBFieldIsMapOrArray(field)) {
  876. id value = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  877. if (value) {
  878. // We need to copy the array/map, but the catch is for message fields,
  879. // we also need to ensure all the messages as those need copying also.
  880. id newValue;
  881. if (GPBFieldDataTypeIsMessage(field)) {
  882. if (field.fieldType == GPBFieldTypeRepeated) {
  883. NSArray *existingArray = (NSArray *)value;
  884. NSMutableArray *newArray =
  885. [[NSMutableArray alloc] initWithCapacity:existingArray.count];
  886. newValue = newArray;
  887. for (GPBMessage *msg in existingArray) {
  888. GPBMessage *copiedMsg = [msg copyWithZone:zone];
  889. [newArray addObject:copiedMsg];
  890. [copiedMsg release];
  891. }
  892. } else {
  893. if (field.mapKeyDataType == GPBDataTypeString) {
  894. // Map is an NSDictionary.
  895. NSDictionary *existingDict = value;
  896. NSMutableDictionary *newDict = [[NSMutableDictionary alloc]
  897. initWithCapacity:existingDict.count];
  898. newValue = newDict;
  899. [existingDict enumerateKeysAndObjectsUsingBlock:^(NSString *key,
  900. GPBMessage *msg,
  901. BOOL *stop) {
  902. #pragma unused(stop)
  903. GPBMessage *copiedMsg = [msg copyWithZone:zone];
  904. [newDict setObject:copiedMsg forKey:key];
  905. [copiedMsg release];
  906. }];
  907. } else {
  908. // Is one of the GPB*ObjectDictionary classes. Type doesn't
  909. // matter, just need one to invoke the selector.
  910. GPBInt32ObjectDictionary *existingDict = value;
  911. newValue = [existingDict deepCopyWithZone:zone];
  912. }
  913. }
  914. } else {
  915. // Not messages (but is a map/array)...
  916. if (field.fieldType == GPBFieldTypeRepeated) {
  917. if (GPBFieldDataTypeIsObject(field)) {
  918. // NSArray
  919. newValue = [value mutableCopyWithZone:zone];
  920. } else {
  921. // GPB*Array
  922. newValue = [value copyWithZone:zone];
  923. }
  924. } else {
  925. if ((field.mapKeyDataType == GPBDataTypeString) &&
  926. GPBFieldDataTypeIsObject(field)) {
  927. // NSDictionary
  928. newValue = [value mutableCopyWithZone:zone];
  929. } else {
  930. // Is one of the GPB*Dictionary classes. Type doesn't matter,
  931. // just need one to invoke the selector.
  932. GPBInt32Int32Dictionary *existingDict = value;
  933. newValue = [existingDict copyWithZone:zone];
  934. }
  935. }
  936. }
  937. // We retain here because the memcpy picked up the pointer value and
  938. // the next call to SetRetainedObject... will release the current value.
  939. [value retain];
  940. GPBSetRetainedObjectIvarWithFieldInternal(message, field, newValue,
  941. syntax);
  942. }
  943. } else if (GPBFieldDataTypeIsMessage(field)) {
  944. // For object types, if we have a value, copy it. If we don't,
  945. // zero it to remove the pointer to something that was autocreated
  946. // (and the ptr just got memcpyed).
  947. if (GPBGetHasIvarField(self, field)) {
  948. GPBMessage *value = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  949. GPBMessage *newValue = [value copyWithZone:zone];
  950. // We retain here because the memcpy picked up the pointer value and
  951. // the next call to SetRetainedObject... will release the current value.
  952. [value retain];
  953. GPBSetRetainedObjectIvarWithFieldInternal(message, field, newValue,
  954. syntax);
  955. } else {
  956. uint8_t *storage = (uint8_t *)message->messageStorage_;
  957. id *typePtr = (id *)&storage[field->description_->offset];
  958. *typePtr = NULL;
  959. }
  960. } else if (GPBFieldDataTypeIsObject(field) &&
  961. GPBGetHasIvarField(self, field)) {
  962. // A set string/data value (message picked off above), copy it.
  963. id value = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  964. id newValue = [value copyWithZone:zone];
  965. // We retain here because the memcpy picked up the pointer value and
  966. // the next call to SetRetainedObject... will release the current value.
  967. [value retain];
  968. GPBSetRetainedObjectIvarWithFieldInternal(message, field, newValue,
  969. syntax);
  970. } else {
  971. // memcpy took care of the rest of the primitive fields if they were set.
  972. }
  973. } // for (field in descriptor->fields_)
  974. }
  975. - (id)copyWithZone:(NSZone *)zone {
  976. GPBDescriptor *descriptor = [self descriptor];
  977. GPBMessage *result = [[descriptor.messageClass allocWithZone:zone] init];
  978. [self copyFieldsInto:result zone:zone descriptor:descriptor];
  979. // Make immutable copies of the extra bits.
  980. result->unknownFields_ = [unknownFields_ copyWithZone:zone];
  981. result->extensionMap_ = CloneExtensionMap(extensionMap_, zone);
  982. return result;
  983. }
  984. - (void)clear {
  985. [self internalClear:YES];
  986. }
  987. - (void)internalClear:(BOOL)zeroStorage {
  988. GPBDescriptor *descriptor = [self descriptor];
  989. for (GPBFieldDescriptor *field in descriptor->fields_) {
  990. if (GPBFieldIsMapOrArray(field)) {
  991. id arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  992. if (arrayOrMap) {
  993. if (field.fieldType == GPBFieldTypeRepeated) {
  994. if (GPBFieldDataTypeIsObject(field)) {
  995. if ([arrayOrMap isKindOfClass:[GPBAutocreatedArray class]]) {
  996. GPBAutocreatedArray *autoArray = arrayOrMap;
  997. if (autoArray->_autocreator == self) {
  998. autoArray->_autocreator = nil;
  999. }
  1000. }
  1001. } else {
  1002. // Type doesn't matter, it is a GPB*Array.
  1003. GPBInt32Array *gpbArray = arrayOrMap;
  1004. if (gpbArray->_autocreator == self) {
  1005. gpbArray->_autocreator = nil;
  1006. }
  1007. }
  1008. } else {
  1009. if ((field.mapKeyDataType == GPBDataTypeString) &&
  1010. GPBFieldDataTypeIsObject(field)) {
  1011. if ([arrayOrMap isKindOfClass:[GPBAutocreatedDictionary class]]) {
  1012. GPBAutocreatedDictionary *autoDict = arrayOrMap;
  1013. if (autoDict->_autocreator == self) {
  1014. autoDict->_autocreator = nil;
  1015. }
  1016. }
  1017. } else {
  1018. // Type doesn't matter, it is a GPB*Dictionary.
  1019. GPBInt32Int32Dictionary *gpbDict = arrayOrMap;
  1020. if (gpbDict->_autocreator == self) {
  1021. gpbDict->_autocreator = nil;
  1022. }
  1023. }
  1024. }
  1025. [arrayOrMap release];
  1026. }
  1027. } else if (GPBFieldDataTypeIsMessage(field)) {
  1028. GPBClearAutocreatedMessageIvarWithField(self, field);
  1029. GPBMessage *value = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1030. [value release];
  1031. } else if (GPBFieldDataTypeIsObject(field) &&
  1032. GPBGetHasIvarField(self, field)) {
  1033. id value = GPBGetObjectIvarWithField(self, field);
  1034. [value release];
  1035. }
  1036. }
  1037. // GPBClearMessageAutocreator() expects that its caller has already been
  1038. // removed from autocreatedExtensionMap_ so we set to nil first.
  1039. NSArray *autocreatedValues = [autocreatedExtensionMap_ allValues];
  1040. [autocreatedExtensionMap_ release];
  1041. autocreatedExtensionMap_ = nil;
  1042. // Since we're clearing all of our extensions, make sure that we clear the
  1043. // autocreator on any that we've created so they no longer refer to us.
  1044. for (GPBMessage *value in autocreatedValues) {
  1045. NSCAssert(GPBWasMessageAutocreatedBy(value, self),
  1046. @"Autocreated extension does not refer back to self.");
  1047. GPBClearMessageAutocreator(value);
  1048. }
  1049. [extensionMap_ release];
  1050. extensionMap_ = nil;
  1051. [unknownFields_ release];
  1052. unknownFields_ = nil;
  1053. // Note that clearing does not affect autocreator_. If we are being cleared
  1054. // because of a dealloc, then autocreator_ should be nil anyway. If we are
  1055. // being cleared because someone explicitly clears us, we don't want to
  1056. // sever our relationship with our autocreator.
  1057. if (zeroStorage) {
  1058. memset(messageStorage_, 0, descriptor->storageSize_);
  1059. }
  1060. }
  1061. - (BOOL)isInitialized {
  1062. GPBDescriptor *descriptor = [self descriptor];
  1063. for (GPBFieldDescriptor *field in descriptor->fields_) {
  1064. if (field.isRequired) {
  1065. if (!GPBGetHasIvarField(self, field)) {
  1066. return NO;
  1067. }
  1068. }
  1069. if (GPBFieldDataTypeIsMessage(field)) {
  1070. GPBFieldType fieldType = field.fieldType;
  1071. if (fieldType == GPBFieldTypeSingle) {
  1072. if (field.isRequired) {
  1073. GPBMessage *message = GPBGetMessageMessageField(self, field);
  1074. if (!message.initialized) {
  1075. return NO;
  1076. }
  1077. } else {
  1078. NSAssert(field.isOptional,
  1079. @"%@: Single message field %@ not required or optional?",
  1080. [self class], field.name);
  1081. if (GPBGetHasIvarField(self, field)) {
  1082. GPBMessage *message = GPBGetMessageMessageField(self, field);
  1083. if (!message.initialized) {
  1084. return NO;
  1085. }
  1086. }
  1087. }
  1088. } else if (fieldType == GPBFieldTypeRepeated) {
  1089. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1090. for (GPBMessage *message in array) {
  1091. if (!message.initialized) {
  1092. return NO;
  1093. }
  1094. }
  1095. } else { // fieldType == GPBFieldTypeMap
  1096. if (field.mapKeyDataType == GPBDataTypeString) {
  1097. NSDictionary *map =
  1098. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1099. if (map && !GPBDictionaryIsInitializedInternalHelper(map, field)) {
  1100. return NO;
  1101. }
  1102. } else {
  1103. // Real type is GPB*ObjectDictionary, exact type doesn't matter.
  1104. GPBInt32ObjectDictionary *map =
  1105. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1106. if (map && ![map isInitialized]) {
  1107. return NO;
  1108. }
  1109. }
  1110. }
  1111. }
  1112. }
  1113. __block BOOL result = YES;
  1114. [extensionMap_
  1115. enumerateKeysAndObjectsUsingBlock:^(GPBExtensionDescriptor *extension,
  1116. id obj,
  1117. BOOL *stop) {
  1118. if (GPBExtensionIsMessage(extension)) {
  1119. if (extension.isRepeated) {
  1120. for (GPBMessage *msg in obj) {
  1121. if (!msg.initialized) {
  1122. result = NO;
  1123. *stop = YES;
  1124. break;
  1125. }
  1126. }
  1127. } else {
  1128. GPBMessage *asMsg = obj;
  1129. if (!asMsg.initialized) {
  1130. result = NO;
  1131. *stop = YES;
  1132. }
  1133. }
  1134. }
  1135. }];
  1136. return result;
  1137. }
  1138. - (GPBDescriptor *)descriptor {
  1139. return [[self class] descriptor];
  1140. }
  1141. - (NSData *)data {
  1142. #ifdef DEBUG
  1143. if (!self.initialized) {
  1144. return nil;
  1145. }
  1146. #endif
  1147. NSMutableData *data = [NSMutableData dataWithLength:[self serializedSize]];
  1148. GPBCodedOutputStream *stream =
  1149. [[GPBCodedOutputStream alloc] initWithData:data];
  1150. @try {
  1151. [self writeToCodedOutputStream:stream];
  1152. }
  1153. @catch (NSException *exception) {
  1154. // This really shouldn't happen. The only way writeToCodedOutputStream:
  1155. // could throw is if something in the library has a bug and the
  1156. // serializedSize was wrong.
  1157. #ifdef DEBUG
  1158. NSLog(@"%@: Internal exception while building message data: %@",
  1159. [self class], exception);
  1160. #endif
  1161. data = nil;
  1162. }
  1163. [stream release];
  1164. return data;
  1165. }
  1166. - (NSData *)delimitedData {
  1167. size_t serializedSize = [self serializedSize];
  1168. size_t varintSize = GPBComputeRawVarint32SizeForInteger(serializedSize);
  1169. NSMutableData *data =
  1170. [NSMutableData dataWithLength:(serializedSize + varintSize)];
  1171. GPBCodedOutputStream *stream =
  1172. [[GPBCodedOutputStream alloc] initWithData:data];
  1173. @try {
  1174. [self writeDelimitedToCodedOutputStream:stream];
  1175. }
  1176. @catch (NSException *exception) {
  1177. // This really shouldn't happen. The only way writeToCodedOutputStream:
  1178. // could throw is if something in the library has a bug and the
  1179. // serializedSize was wrong.
  1180. #ifdef DEBUG
  1181. NSLog(@"%@: Internal exception while building message delimitedData: %@",
  1182. [self class], exception);
  1183. #endif
  1184. // If it happens, truncate.
  1185. data.length = 0;
  1186. }
  1187. [stream release];
  1188. return data;
  1189. }
  1190. - (void)writeToOutputStream:(NSOutputStream *)output {
  1191. GPBCodedOutputStream *stream =
  1192. [[GPBCodedOutputStream alloc] initWithOutputStream:output];
  1193. [self writeToCodedOutputStream:stream];
  1194. [stream release];
  1195. }
  1196. - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output {
  1197. GPBDescriptor *descriptor = [self descriptor];
  1198. NSArray *fieldsArray = descriptor->fields_;
  1199. NSUInteger fieldCount = fieldsArray.count;
  1200. const GPBExtensionRange *extensionRanges = descriptor.extensionRanges;
  1201. NSUInteger extensionRangesCount = descriptor.extensionRangesCount;
  1202. NSArray *sortedExtensions =
  1203. [[extensionMap_ allKeys] sortedArrayUsingSelector:@selector(compareByFieldNumber:)];
  1204. for (NSUInteger i = 0, j = 0; i < fieldCount || j < extensionRangesCount;) {
  1205. if (i == fieldCount) {
  1206. [self writeExtensionsToCodedOutputStream:output
  1207. range:extensionRanges[j++]
  1208. sortedExtensions:sortedExtensions];
  1209. } else if (j == extensionRangesCount ||
  1210. GPBFieldNumber(fieldsArray[i]) < extensionRanges[j].start) {
  1211. [self writeField:fieldsArray[i++] toCodedOutputStream:output];
  1212. } else {
  1213. [self writeExtensionsToCodedOutputStream:output
  1214. range:extensionRanges[j++]
  1215. sortedExtensions:sortedExtensions];
  1216. }
  1217. }
  1218. if (descriptor.isWireFormat) {
  1219. [unknownFields_ writeAsMessageSetTo:output];
  1220. } else {
  1221. [unknownFields_ writeToCodedOutputStream:output];
  1222. }
  1223. }
  1224. - (void)writeDelimitedToOutputStream:(NSOutputStream *)output {
  1225. GPBCodedOutputStream *codedOutput =
  1226. [[GPBCodedOutputStream alloc] initWithOutputStream:output];
  1227. [self writeDelimitedToCodedOutputStream:codedOutput];
  1228. [codedOutput release];
  1229. }
  1230. - (void)writeDelimitedToCodedOutputStream:(GPBCodedOutputStream *)output {
  1231. [output writeRawVarintSizeTAs32:[self serializedSize]];
  1232. [self writeToCodedOutputStream:output];
  1233. }
  1234. - (void)writeField:(GPBFieldDescriptor *)field
  1235. toCodedOutputStream:(GPBCodedOutputStream *)output {
  1236. GPBFieldType fieldType = field.fieldType;
  1237. if (fieldType == GPBFieldTypeSingle) {
  1238. BOOL has = GPBGetHasIvarField(self, field);
  1239. if (!has) {
  1240. return;
  1241. }
  1242. }
  1243. uint32_t fieldNumber = GPBFieldNumber(field);
  1244. //%PDDM-DEFINE FIELD_CASE(TYPE, REAL_TYPE)
  1245. //%FIELD_CASE_FULL(TYPE, REAL_TYPE, REAL_TYPE)
  1246. //%PDDM-DEFINE FIELD_CASE_FULL(TYPE, REAL_TYPE, ARRAY_TYPE)
  1247. //% case GPBDataType##TYPE:
  1248. //% if (fieldType == GPBFieldTypeRepeated) {
  1249. //% uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1250. //% GPB##ARRAY_TYPE##Array *array =
  1251. //% GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1252. //% [output write##TYPE##Array:fieldNumber values:array tag:tag];
  1253. //% } else if (fieldType == GPBFieldTypeSingle) {
  1254. //% [output write##TYPE:fieldNumber
  1255. //% TYPE$S value:GPBGetMessage##REAL_TYPE##Field(self, field)];
  1256. //% } else { // fieldType == GPBFieldTypeMap
  1257. //% // Exact type here doesn't matter.
  1258. //% GPBInt32##ARRAY_TYPE##Dictionary *dict =
  1259. //% GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1260. //% [dict writeToCodedOutputStream:output asField:field];
  1261. //% }
  1262. //% break;
  1263. //%
  1264. //%PDDM-DEFINE FIELD_CASE2(TYPE)
  1265. //% case GPBDataType##TYPE:
  1266. //% if (fieldType == GPBFieldTypeRepeated) {
  1267. //% NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1268. //% [output write##TYPE##Array:fieldNumber values:array];
  1269. //% } else if (fieldType == GPBFieldTypeSingle) {
  1270. //% // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1271. //% // again.
  1272. //% [output write##TYPE:fieldNumber
  1273. //% TYPE$S value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1274. //% } else { // fieldType == GPBFieldTypeMap
  1275. //% // Exact type here doesn't matter.
  1276. //% id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1277. //% GPBDataType mapKeyDataType = field.mapKeyDataType;
  1278. //% if (mapKeyDataType == GPBDataTypeString) {
  1279. //% GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1280. //% } else {
  1281. //% [dict writeToCodedOutputStream:output asField:field];
  1282. //% }
  1283. //% }
  1284. //% break;
  1285. //%
  1286. switch (GPBGetFieldDataType(field)) {
  1287. //%PDDM-EXPAND FIELD_CASE(Bool, Bool)
  1288. // This block of code is generated, do not edit it directly.
  1289. // clang-format off
  1290. case GPBDataTypeBool:
  1291. if (fieldType == GPBFieldTypeRepeated) {
  1292. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1293. GPBBoolArray *array =
  1294. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1295. [output writeBoolArray:fieldNumber values:array tag:tag];
  1296. } else if (fieldType == GPBFieldTypeSingle) {
  1297. [output writeBool:fieldNumber
  1298. value:GPBGetMessageBoolField(self, field)];
  1299. } else { // fieldType == GPBFieldTypeMap
  1300. // Exact type here doesn't matter.
  1301. GPBInt32BoolDictionary *dict =
  1302. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1303. [dict writeToCodedOutputStream:output asField:field];
  1304. }
  1305. break;
  1306. // clang-format on
  1307. //%PDDM-EXPAND FIELD_CASE(Fixed32, UInt32)
  1308. // This block of code is generated, do not edit it directly.
  1309. // clang-format off
  1310. case GPBDataTypeFixed32:
  1311. if (fieldType == GPBFieldTypeRepeated) {
  1312. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1313. GPBUInt32Array *array =
  1314. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1315. [output writeFixed32Array:fieldNumber values:array tag:tag];
  1316. } else if (fieldType == GPBFieldTypeSingle) {
  1317. [output writeFixed32:fieldNumber
  1318. value:GPBGetMessageUInt32Field(self, field)];
  1319. } else { // fieldType == GPBFieldTypeMap
  1320. // Exact type here doesn't matter.
  1321. GPBInt32UInt32Dictionary *dict =
  1322. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1323. [dict writeToCodedOutputStream:output asField:field];
  1324. }
  1325. break;
  1326. // clang-format on
  1327. //%PDDM-EXPAND FIELD_CASE(SFixed32, Int32)
  1328. // This block of code is generated, do not edit it directly.
  1329. // clang-format off
  1330. case GPBDataTypeSFixed32:
  1331. if (fieldType == GPBFieldTypeRepeated) {
  1332. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1333. GPBInt32Array *array =
  1334. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1335. [output writeSFixed32Array:fieldNumber values:array tag:tag];
  1336. } else if (fieldType == GPBFieldTypeSingle) {
  1337. [output writeSFixed32:fieldNumber
  1338. value:GPBGetMessageInt32Field(self, field)];
  1339. } else { // fieldType == GPBFieldTypeMap
  1340. // Exact type here doesn't matter.
  1341. GPBInt32Int32Dictionary *dict =
  1342. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1343. [dict writeToCodedOutputStream:output asField:field];
  1344. }
  1345. break;
  1346. // clang-format on
  1347. //%PDDM-EXPAND FIELD_CASE(Float, Float)
  1348. // This block of code is generated, do not edit it directly.
  1349. // clang-format off
  1350. case GPBDataTypeFloat:
  1351. if (fieldType == GPBFieldTypeRepeated) {
  1352. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1353. GPBFloatArray *array =
  1354. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1355. [output writeFloatArray:fieldNumber values:array tag:tag];
  1356. } else if (fieldType == GPBFieldTypeSingle) {
  1357. [output writeFloat:fieldNumber
  1358. value:GPBGetMessageFloatField(self, field)];
  1359. } else { // fieldType == GPBFieldTypeMap
  1360. // Exact type here doesn't matter.
  1361. GPBInt32FloatDictionary *dict =
  1362. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1363. [dict writeToCodedOutputStream:output asField:field];
  1364. }
  1365. break;
  1366. // clang-format on
  1367. //%PDDM-EXPAND FIELD_CASE(Fixed64, UInt64)
  1368. // This block of code is generated, do not edit it directly.
  1369. // clang-format off
  1370. case GPBDataTypeFixed64:
  1371. if (fieldType == GPBFieldTypeRepeated) {
  1372. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1373. GPBUInt64Array *array =
  1374. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1375. [output writeFixed64Array:fieldNumber values:array tag:tag];
  1376. } else if (fieldType == GPBFieldTypeSingle) {
  1377. [output writeFixed64:fieldNumber
  1378. value:GPBGetMessageUInt64Field(self, field)];
  1379. } else { // fieldType == GPBFieldTypeMap
  1380. // Exact type here doesn't matter.
  1381. GPBInt32UInt64Dictionary *dict =
  1382. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1383. [dict writeToCodedOutputStream:output asField:field];
  1384. }
  1385. break;
  1386. // clang-format on
  1387. //%PDDM-EXPAND FIELD_CASE(SFixed64, Int64)
  1388. // This block of code is generated, do not edit it directly.
  1389. // clang-format off
  1390. case GPBDataTypeSFixed64:
  1391. if (fieldType == GPBFieldTypeRepeated) {
  1392. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1393. GPBInt64Array *array =
  1394. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1395. [output writeSFixed64Array:fieldNumber values:array tag:tag];
  1396. } else if (fieldType == GPBFieldTypeSingle) {
  1397. [output writeSFixed64:fieldNumber
  1398. value:GPBGetMessageInt64Field(self, field)];
  1399. } else { // fieldType == GPBFieldTypeMap
  1400. // Exact type here doesn't matter.
  1401. GPBInt32Int64Dictionary *dict =
  1402. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1403. [dict writeToCodedOutputStream:output asField:field];
  1404. }
  1405. break;
  1406. // clang-format on
  1407. //%PDDM-EXPAND FIELD_CASE(Double, Double)
  1408. // This block of code is generated, do not edit it directly.
  1409. // clang-format off
  1410. case GPBDataTypeDouble:
  1411. if (fieldType == GPBFieldTypeRepeated) {
  1412. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1413. GPBDoubleArray *array =
  1414. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1415. [output writeDoubleArray:fieldNumber values:array tag:tag];
  1416. } else if (fieldType == GPBFieldTypeSingle) {
  1417. [output writeDouble:fieldNumber
  1418. value:GPBGetMessageDoubleField(self, field)];
  1419. } else { // fieldType == GPBFieldTypeMap
  1420. // Exact type here doesn't matter.
  1421. GPBInt32DoubleDictionary *dict =
  1422. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1423. [dict writeToCodedOutputStream:output asField:field];
  1424. }
  1425. break;
  1426. // clang-format on
  1427. //%PDDM-EXPAND FIELD_CASE(Int32, Int32)
  1428. // This block of code is generated, do not edit it directly.
  1429. // clang-format off
  1430. case GPBDataTypeInt32:
  1431. if (fieldType == GPBFieldTypeRepeated) {
  1432. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1433. GPBInt32Array *array =
  1434. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1435. [output writeInt32Array:fieldNumber values:array tag:tag];
  1436. } else if (fieldType == GPBFieldTypeSingle) {
  1437. [output writeInt32:fieldNumber
  1438. value:GPBGetMessageInt32Field(self, field)];
  1439. } else { // fieldType == GPBFieldTypeMap
  1440. // Exact type here doesn't matter.
  1441. GPBInt32Int32Dictionary *dict =
  1442. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1443. [dict writeToCodedOutputStream:output asField:field];
  1444. }
  1445. break;
  1446. // clang-format on
  1447. //%PDDM-EXPAND FIELD_CASE(Int64, Int64)
  1448. // This block of code is generated, do not edit it directly.
  1449. // clang-format off
  1450. case GPBDataTypeInt64:
  1451. if (fieldType == GPBFieldTypeRepeated) {
  1452. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1453. GPBInt64Array *array =
  1454. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1455. [output writeInt64Array:fieldNumber values:array tag:tag];
  1456. } else if (fieldType == GPBFieldTypeSingle) {
  1457. [output writeInt64:fieldNumber
  1458. value:GPBGetMessageInt64Field(self, field)];
  1459. } else { // fieldType == GPBFieldTypeMap
  1460. // Exact type here doesn't matter.
  1461. GPBInt32Int64Dictionary *dict =
  1462. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1463. [dict writeToCodedOutputStream:output asField:field];
  1464. }
  1465. break;
  1466. // clang-format on
  1467. //%PDDM-EXPAND FIELD_CASE(SInt32, Int32)
  1468. // This block of code is generated, do not edit it directly.
  1469. // clang-format off
  1470. case GPBDataTypeSInt32:
  1471. if (fieldType == GPBFieldTypeRepeated) {
  1472. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1473. GPBInt32Array *array =
  1474. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1475. [output writeSInt32Array:fieldNumber values:array tag:tag];
  1476. } else if (fieldType == GPBFieldTypeSingle) {
  1477. [output writeSInt32:fieldNumber
  1478. value:GPBGetMessageInt32Field(self, field)];
  1479. } else { // fieldType == GPBFieldTypeMap
  1480. // Exact type here doesn't matter.
  1481. GPBInt32Int32Dictionary *dict =
  1482. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1483. [dict writeToCodedOutputStream:output asField:field];
  1484. }
  1485. break;
  1486. // clang-format on
  1487. //%PDDM-EXPAND FIELD_CASE(SInt64, Int64)
  1488. // This block of code is generated, do not edit it directly.
  1489. // clang-format off
  1490. case GPBDataTypeSInt64:
  1491. if (fieldType == GPBFieldTypeRepeated) {
  1492. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1493. GPBInt64Array *array =
  1494. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1495. [output writeSInt64Array:fieldNumber values:array tag:tag];
  1496. } else if (fieldType == GPBFieldTypeSingle) {
  1497. [output writeSInt64:fieldNumber
  1498. value:GPBGetMessageInt64Field(self, field)];
  1499. } else { // fieldType == GPBFieldTypeMap
  1500. // Exact type here doesn't matter.
  1501. GPBInt32Int64Dictionary *dict =
  1502. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1503. [dict writeToCodedOutputStream:output asField:field];
  1504. }
  1505. break;
  1506. // clang-format on
  1507. //%PDDM-EXPAND FIELD_CASE(UInt32, UInt32)
  1508. // This block of code is generated, do not edit it directly.
  1509. // clang-format off
  1510. case GPBDataTypeUInt32:
  1511. if (fieldType == GPBFieldTypeRepeated) {
  1512. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1513. GPBUInt32Array *array =
  1514. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1515. [output writeUInt32Array:fieldNumber values:array tag:tag];
  1516. } else if (fieldType == GPBFieldTypeSingle) {
  1517. [output writeUInt32:fieldNumber
  1518. value:GPBGetMessageUInt32Field(self, field)];
  1519. } else { // fieldType == GPBFieldTypeMap
  1520. // Exact type here doesn't matter.
  1521. GPBInt32UInt32Dictionary *dict =
  1522. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1523. [dict writeToCodedOutputStream:output asField:field];
  1524. }
  1525. break;
  1526. // clang-format on
  1527. //%PDDM-EXPAND FIELD_CASE(UInt64, UInt64)
  1528. // This block of code is generated, do not edit it directly.
  1529. // clang-format off
  1530. case GPBDataTypeUInt64:
  1531. if (fieldType == GPBFieldTypeRepeated) {
  1532. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1533. GPBUInt64Array *array =
  1534. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1535. [output writeUInt64Array:fieldNumber values:array tag:tag];
  1536. } else if (fieldType == GPBFieldTypeSingle) {
  1537. [output writeUInt64:fieldNumber
  1538. value:GPBGetMessageUInt64Field(self, field)];
  1539. } else { // fieldType == GPBFieldTypeMap
  1540. // Exact type here doesn't matter.
  1541. GPBInt32UInt64Dictionary *dict =
  1542. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1543. [dict writeToCodedOutputStream:output asField:field];
  1544. }
  1545. break;
  1546. // clang-format on
  1547. //%PDDM-EXPAND FIELD_CASE_FULL(Enum, Int32, Enum)
  1548. // This block of code is generated, do not edit it directly.
  1549. // clang-format off
  1550. case GPBDataTypeEnum:
  1551. if (fieldType == GPBFieldTypeRepeated) {
  1552. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1553. GPBEnumArray *array =
  1554. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1555. [output writeEnumArray:fieldNumber values:array tag:tag];
  1556. } else if (fieldType == GPBFieldTypeSingle) {
  1557. [output writeEnum:fieldNumber
  1558. value:GPBGetMessageInt32Field(self, field)];
  1559. } else { // fieldType == GPBFieldTypeMap
  1560. // Exact type here doesn't matter.
  1561. GPBInt32EnumDictionary *dict =
  1562. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1563. [dict writeToCodedOutputStream:output asField:field];
  1564. }
  1565. break;
  1566. // clang-format on
  1567. //%PDDM-EXPAND FIELD_CASE2(Bytes)
  1568. // This block of code is generated, do not edit it directly.
  1569. // clang-format off
  1570. case GPBDataTypeBytes:
  1571. if (fieldType == GPBFieldTypeRepeated) {
  1572. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1573. [output writeBytesArray:fieldNumber values:array];
  1574. } else if (fieldType == GPBFieldTypeSingle) {
  1575. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1576. // again.
  1577. [output writeBytes:fieldNumber
  1578. value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1579. } else { // fieldType == GPBFieldTypeMap
  1580. // Exact type here doesn't matter.
  1581. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1582. GPBDataType mapKeyDataType = field.mapKeyDataType;
  1583. if (mapKeyDataType == GPBDataTypeString) {
  1584. GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1585. } else {
  1586. [dict writeToCodedOutputStream:output asField:field];
  1587. }
  1588. }
  1589. break;
  1590. // clang-format on
  1591. //%PDDM-EXPAND FIELD_CASE2(String)
  1592. // This block of code is generated, do not edit it directly.
  1593. // clang-format off
  1594. case GPBDataTypeString:
  1595. if (fieldType == GPBFieldTypeRepeated) {
  1596. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1597. [output writeStringArray:fieldNumber values:array];
  1598. } else if (fieldType == GPBFieldTypeSingle) {
  1599. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1600. // again.
  1601. [output writeString:fieldNumber
  1602. value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1603. } else { // fieldType == GPBFieldTypeMap
  1604. // Exact type here doesn't matter.
  1605. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1606. GPBDataType mapKeyDataType = field.mapKeyDataType;
  1607. if (mapKeyDataType == GPBDataTypeString) {
  1608. GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1609. } else {
  1610. [dict writeToCodedOutputStream:output asField:field];
  1611. }
  1612. }
  1613. break;
  1614. // clang-format on
  1615. //%PDDM-EXPAND FIELD_CASE2(Message)
  1616. // This block of code is generated, do not edit it directly.
  1617. // clang-format off
  1618. case GPBDataTypeMessage:
  1619. if (fieldType == GPBFieldTypeRepeated) {
  1620. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1621. [output writeMessageArray:fieldNumber values:array];
  1622. } else if (fieldType == GPBFieldTypeSingle) {
  1623. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1624. // again.
  1625. [output writeMessage:fieldNumber
  1626. value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1627. } else { // fieldType == GPBFieldTypeMap
  1628. // Exact type here doesn't matter.
  1629. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1630. GPBDataType mapKeyDataType = field.mapKeyDataType;
  1631. if (mapKeyDataType == GPBDataTypeString) {
  1632. GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1633. } else {
  1634. [dict writeToCodedOutputStream:output asField:field];
  1635. }
  1636. }
  1637. break;
  1638. // clang-format on
  1639. //%PDDM-EXPAND FIELD_CASE2(Group)
  1640. // This block of code is generated, do not edit it directly.
  1641. // clang-format off
  1642. case GPBDataTypeGroup:
  1643. if (fieldType == GPBFieldTypeRepeated) {
  1644. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1645. [output writeGroupArray:fieldNumber values:array];
  1646. } else if (fieldType == GPBFieldTypeSingle) {
  1647. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1648. // again.
  1649. [output writeGroup:fieldNumber
  1650. value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1651. } else { // fieldType == GPBFieldTypeMap
  1652. // Exact type here doesn't matter.
  1653. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1654. GPBDataType mapKeyDataType = field.mapKeyDataType;
  1655. if (mapKeyDataType == GPBDataTypeString) {
  1656. GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1657. } else {
  1658. [dict writeToCodedOutputStream:output asField:field];
  1659. }
  1660. }
  1661. break;
  1662. // clang-format on
  1663. //%PDDM-EXPAND-END (18 expansions)
  1664. }
  1665. }
  1666. #pragma mark - Extensions
  1667. - (id)getExtension:(GPBExtensionDescriptor *)extension {
  1668. CheckExtension(self, extension);
  1669. id value = [extensionMap_ objectForKey:extension];
  1670. if (value != nil) {
  1671. return value;
  1672. }
  1673. // No default for repeated.
  1674. if (extension.isRepeated) {
  1675. return nil;
  1676. }
  1677. // Non messages get their default.
  1678. if (!GPBExtensionIsMessage(extension)) {
  1679. return extension.defaultValue;
  1680. }
  1681. // Check for an autocreated value.
  1682. GPBPrepareReadOnlySemaphore(self);
  1683. dispatch_semaphore_wait(readOnlySemaphore_, DISPATCH_TIME_FOREVER);
  1684. value = [autocreatedExtensionMap_ objectForKey:extension];
  1685. if (!value) {
  1686. // Auto create the message extensions to match normal fields.
  1687. value = CreateMessageWithAutocreatorForExtension(extension.msgClass, self,
  1688. extension);
  1689. if (autocreatedExtensionMap_ == nil) {
  1690. autocreatedExtensionMap_ = [[NSMutableDictionary alloc] init];
  1691. }
  1692. // We can't simply call setExtension here because that would clear the new
  1693. // value's autocreator.
  1694. [autocreatedExtensionMap_ setObject:value forKey:extension];
  1695. [value release];
  1696. }
  1697. dispatch_semaphore_signal(readOnlySemaphore_);
  1698. return value;
  1699. }
  1700. - (id)getExistingExtension:(GPBExtensionDescriptor *)extension {
  1701. // This is an internal method so we don't need to call CheckExtension().
  1702. return [extensionMap_ objectForKey:extension];
  1703. }
  1704. - (BOOL)hasExtension:(GPBExtensionDescriptor *)extension {
  1705. #if defined(DEBUG) && DEBUG
  1706. CheckExtension(self, extension);
  1707. #endif // DEBUG
  1708. return nil != [extensionMap_ objectForKey:extension];
  1709. }
  1710. - (NSArray *)extensionsCurrentlySet {
  1711. return [extensionMap_ allKeys];
  1712. }
  1713. - (void)writeExtensionsToCodedOutputStream:(GPBCodedOutputStream *)output
  1714. range:(GPBExtensionRange)range
  1715. sortedExtensions:(NSArray *)sortedExtensions {
  1716. uint32_t start = range.start;
  1717. uint32_t end = range.end;
  1718. for (GPBExtensionDescriptor *extension in sortedExtensions) {
  1719. uint32_t fieldNumber = extension.fieldNumber;
  1720. if (fieldNumber < start) {
  1721. continue;
  1722. }
  1723. if (fieldNumber >= end) {
  1724. break;
  1725. }
  1726. id value = [extensionMap_ objectForKey:extension];
  1727. GPBWriteExtensionValueToOutputStream(extension, value, output);
  1728. }
  1729. }
  1730. - (void)setExtension:(GPBExtensionDescriptor *)extension value:(id)value {
  1731. if (!value) {
  1732. [self clearExtension:extension];
  1733. return;
  1734. }
  1735. CheckExtension(self, extension);
  1736. if (extension.repeated) {
  1737. [NSException raise:NSInvalidArgumentException
  1738. format:@"Must call addExtension() for repeated types."];
  1739. }
  1740. if (extensionMap_ == nil) {
  1741. extensionMap_ = [[NSMutableDictionary alloc] init];
  1742. }
  1743. // This pointless cast is for CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION.
  1744. // Without it, the compiler complains we're passing an id nullable when
  1745. // setObject:forKey: requires a id nonnull for the value. The check for
  1746. // !value at the start of the method ensures it isn't nil, but the check
  1747. // isn't smart enough to realize that.
  1748. [extensionMap_ setObject:(id)value forKey:extension];
  1749. GPBExtensionDescriptor *descriptor = extension;
  1750. if (GPBExtensionIsMessage(descriptor) && !descriptor.isRepeated) {
  1751. GPBMessage *autocreatedValue =
  1752. [[autocreatedExtensionMap_ objectForKey:extension] retain];
  1753. // Must remove from the map before calling GPBClearMessageAutocreator() so
  1754. // that GPBClearMessageAutocreator() knows its safe to clear.
  1755. [autocreatedExtensionMap_ removeObjectForKey:extension];
  1756. GPBClearMessageAutocreator(autocreatedValue);
  1757. [autocreatedValue release];
  1758. }
  1759. GPBBecomeVisibleToAutocreator(self);
  1760. }
  1761. - (void)addExtension:(GPBExtensionDescriptor *)extension value:(id)value {
  1762. CheckExtension(self, extension);
  1763. if (!extension.repeated) {
  1764. [NSException raise:NSInvalidArgumentException
  1765. format:@"Must call setExtension() for singular types."];
  1766. }
  1767. if (extensionMap_ == nil) {
  1768. extensionMap_ = [[NSMutableDictionary alloc] init];
  1769. }
  1770. NSMutableArray *list = [extensionMap_ objectForKey:extension];
  1771. if (list == nil) {
  1772. list = [NSMutableArray array];
  1773. [extensionMap_ setObject:list forKey:extension];
  1774. }
  1775. [list addObject:value];
  1776. GPBBecomeVisibleToAutocreator(self);
  1777. }
  1778. - (void)setExtension:(GPBExtensionDescriptor *)extension
  1779. index:(NSUInteger)idx
  1780. value:(id)value {
  1781. CheckExtension(self, extension);
  1782. if (!extension.repeated) {
  1783. [NSException raise:NSInvalidArgumentException
  1784. format:@"Must call setExtension() for singular types."];
  1785. }
  1786. if (extensionMap_ == nil) {
  1787. extensionMap_ = [[NSMutableDictionary alloc] init];
  1788. }
  1789. NSMutableArray *list = [extensionMap_ objectForKey:extension];
  1790. [list replaceObjectAtIndex:idx withObject:value];
  1791. GPBBecomeVisibleToAutocreator(self);
  1792. }
  1793. - (void)clearExtension:(GPBExtensionDescriptor *)extension {
  1794. CheckExtension(self, extension);
  1795. // Only become visible if there was actually a value to clear.
  1796. if ([extensionMap_ objectForKey:extension]) {
  1797. [extensionMap_ removeObjectForKey:extension];
  1798. GPBBecomeVisibleToAutocreator(self);
  1799. }
  1800. }
  1801. #pragma mark - mergeFrom
  1802. - (void)mergeFromData:(NSData *)data
  1803. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
  1804. GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data];
  1805. [self mergeFromCodedInputStream:input extensionRegistry:extensionRegistry];
  1806. [input checkLastTagWas:0];
  1807. [input release];
  1808. }
  1809. #pragma mark - mergeDelimitedFrom
  1810. - (void)mergeDelimitedFromCodedInputStream:(GPBCodedInputStream *)input
  1811. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
  1812. GPBCodedInputStreamState *state = &input->state_;
  1813. if (GPBCodedInputStreamIsAtEnd(state)) {
  1814. return;
  1815. }
  1816. NSData *data = GPBCodedInputStreamReadRetainedBytesNoCopy(state);
  1817. if (data == nil) {
  1818. return;
  1819. }
  1820. [self mergeFromData:data extensionRegistry:extensionRegistry];
  1821. [data release];
  1822. }
  1823. #pragma mark - Parse From Data Support
  1824. + (instancetype)parseFromData:(NSData *)data error:(NSError **)errorPtr {
  1825. return [self parseFromData:data extensionRegistry:nil error:errorPtr];
  1826. }
  1827. + (instancetype)parseFromData:(NSData *)data
  1828. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry
  1829. error:(NSError **)errorPtr {
  1830. return [[[self alloc] initWithData:data
  1831. extensionRegistry:extensionRegistry
  1832. error:errorPtr] autorelease];
  1833. }
  1834. + (instancetype)parseFromCodedInputStream:(GPBCodedInputStream *)input
  1835. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry
  1836. error:(NSError **)errorPtr {
  1837. return
  1838. [[[self alloc] initWithCodedInputStream:input
  1839. extensionRegistry:extensionRegistry
  1840. error:errorPtr] autorelease];
  1841. }
  1842. #pragma mark - Parse Delimited From Data Support
  1843. + (instancetype)parseDelimitedFromCodedInputStream:(GPBCodedInputStream *)input
  1844. extensionRegistry:
  1845. (GPBExtensionRegistry *)extensionRegistry
  1846. error:(NSError **)errorPtr {
  1847. GPBMessage *message = [[[self alloc] init] autorelease];
  1848. @try {
  1849. [message mergeDelimitedFromCodedInputStream:input
  1850. extensionRegistry:extensionRegistry];
  1851. if (errorPtr) {
  1852. *errorPtr = nil;
  1853. }
  1854. }
  1855. @catch (NSException *exception) {
  1856. message = nil;
  1857. if (errorPtr) {
  1858. *errorPtr = ErrorFromException(exception);
  1859. }
  1860. }
  1861. #ifdef DEBUG
  1862. if (message && !message.initialized) {
  1863. message = nil;
  1864. if (errorPtr) {
  1865. *errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil);
  1866. }
  1867. }
  1868. #endif
  1869. return message;
  1870. }
  1871. #pragma mark - Unknown Field Support
  1872. - (GPBUnknownFieldSet *)unknownFields {
  1873. return unknownFields_;
  1874. }
  1875. - (void)setUnknownFields:(GPBUnknownFieldSet *)unknownFields {
  1876. if (unknownFields != unknownFields_) {
  1877. [unknownFields_ release];
  1878. unknownFields_ = [unknownFields copy];
  1879. GPBBecomeVisibleToAutocreator(self);
  1880. }
  1881. }
  1882. - (void)parseMessageSet:(GPBCodedInputStream *)input
  1883. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
  1884. uint32_t typeId = 0;
  1885. NSData *rawBytes = nil;
  1886. GPBExtensionDescriptor *extension = nil;
  1887. GPBCodedInputStreamState *state = &input->state_;
  1888. while (true) {
  1889. uint32_t tag = GPBCodedInputStreamReadTag(state);
  1890. if (tag == 0) {
  1891. break;
  1892. }
  1893. if (tag == GPBWireFormatMessageSetTypeIdTag) {
  1894. typeId = GPBCodedInputStreamReadUInt32(state);
  1895. if (typeId != 0) {
  1896. extension = [extensionRegistry extensionForDescriptor:[self descriptor]
  1897. fieldNumber:typeId];
  1898. }
  1899. } else if (tag == GPBWireFormatMessageSetMessageTag) {
  1900. rawBytes =
  1901. [GPBCodedInputStreamReadRetainedBytesNoCopy(state) autorelease];
  1902. } else {
  1903. if (![input skipField:tag]) {
  1904. break;
  1905. }
  1906. }
  1907. }
  1908. [input checkLastTagWas:GPBWireFormatMessageSetItemEndTag];
  1909. if (rawBytes != nil && typeId != 0) {
  1910. if (extension != nil) {
  1911. GPBCodedInputStream *newInput =
  1912. [[GPBCodedInputStream alloc] initWithData:rawBytes];
  1913. GPBExtensionMergeFromInputStream(extension,
  1914. extension.packable,
  1915. newInput,
  1916. extensionRegistry,
  1917. self);
  1918. [newInput release];
  1919. } else {
  1920. GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
  1921. // rawBytes was created via a NoCopy, so it can be reusing a
  1922. // subrange of another NSData that might go out of scope as things
  1923. // unwind, so a copy is needed to ensure what is saved in the
  1924. // unknown fields stays valid.
  1925. NSData *cloned = [NSData dataWithData:rawBytes];
  1926. [unknownFields mergeMessageSetMessage:typeId data:cloned];
  1927. }
  1928. }
  1929. }
  1930. - (BOOL)parseUnknownField:(GPBCodedInputStream *)input
  1931. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry
  1932. tag:(uint32_t)tag {
  1933. GPBWireFormat wireType = GPBWireFormatGetTagWireType(tag);
  1934. int32_t fieldNumber = GPBWireFormatGetTagFieldNumber(tag);
  1935. GPBDescriptor *descriptor = [self descriptor];
  1936. GPBExtensionDescriptor *extension =
  1937. [extensionRegistry extensionForDescriptor:descriptor
  1938. fieldNumber:fieldNumber];
  1939. if (extension == nil) {
  1940. if (descriptor.wireFormat && GPBWireFormatMessageSetItemTag == tag) {
  1941. [self parseMessageSet:input extensionRegistry:extensionRegistry];
  1942. return YES;
  1943. }
  1944. } else {
  1945. if (extension.wireType == wireType) {
  1946. GPBExtensionMergeFromInputStream(extension,
  1947. extension.packable,
  1948. input,
  1949. extensionRegistry,
  1950. self);
  1951. return YES;
  1952. }
  1953. // Primitive, repeated types can be packed on unpacked on the wire, and are
  1954. // parsed either way.
  1955. if ([extension isRepeated] &&
  1956. !GPBDataTypeIsObject(extension->description_->dataType) &&
  1957. (extension.alternateWireType == wireType)) {
  1958. GPBExtensionMergeFromInputStream(extension,
  1959. !extension.packable,
  1960. input,
  1961. extensionRegistry,
  1962. self);
  1963. return YES;
  1964. }
  1965. }
  1966. if ([GPBUnknownFieldSet isFieldTag:tag]) {
  1967. GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
  1968. return [unknownFields mergeFieldFrom:tag input:input];
  1969. } else {
  1970. return NO;
  1971. }
  1972. }
  1973. - (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data {
  1974. GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
  1975. [unknownFields addUnknownMapEntry:fieldNum value:data];
  1976. }
  1977. #pragma mark - MergeFromCodedInputStream Support
  1978. static void MergeSingleFieldFromCodedInputStream(
  1979. GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax,
  1980. GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry) {
  1981. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  1982. switch (fieldDataType) {
  1983. #define CASE_SINGLE_POD(NAME, TYPE, FUNC_TYPE) \
  1984. case GPBDataType##NAME: { \
  1985. TYPE val = GPBCodedInputStreamRead##NAME(&input->state_); \
  1986. GPBSet##FUNC_TYPE##IvarWithFieldInternal(self, field, val, syntax); \
  1987. break; \
  1988. }
  1989. #define CASE_SINGLE_OBJECT(NAME) \
  1990. case GPBDataType##NAME: { \
  1991. id val = GPBCodedInputStreamReadRetained##NAME(&input->state_); \
  1992. GPBSetRetainedObjectIvarWithFieldInternal(self, field, val, syntax); \
  1993. break; \
  1994. }
  1995. CASE_SINGLE_POD(Bool, BOOL, Bool)
  1996. CASE_SINGLE_POD(Fixed32, uint32_t, UInt32)
  1997. CASE_SINGLE_POD(SFixed32, int32_t, Int32)
  1998. CASE_SINGLE_POD(Float, float, Float)
  1999. CASE_SINGLE_POD(Fixed64, uint64_t, UInt64)
  2000. CASE_SINGLE_POD(SFixed64, int64_t, Int64)
  2001. CASE_SINGLE_POD(Double, double, Double)
  2002. CASE_SINGLE_POD(Int32, int32_t, Int32)
  2003. CASE_SINGLE_POD(Int64, int64_t, Int64)
  2004. CASE_SINGLE_POD(SInt32, int32_t, Int32)
  2005. CASE_SINGLE_POD(SInt64, int64_t, Int64)
  2006. CASE_SINGLE_POD(UInt32, uint32_t, UInt32)
  2007. CASE_SINGLE_POD(UInt64, uint64_t, UInt64)
  2008. CASE_SINGLE_OBJECT(Bytes)
  2009. CASE_SINGLE_OBJECT(String)
  2010. #undef CASE_SINGLE_POD
  2011. #undef CASE_SINGLE_OBJECT
  2012. case GPBDataTypeMessage: {
  2013. if (GPBGetHasIvarField(self, field)) {
  2014. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has
  2015. // check again.
  2016. GPBMessage *message =
  2017. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  2018. [input readMessage:message extensionRegistry:extensionRegistry];
  2019. } else {
  2020. GPBMessage *message = [[field.msgClass alloc] init];
  2021. [input readMessage:message extensionRegistry:extensionRegistry];
  2022. GPBSetRetainedObjectIvarWithFieldInternal(self, field, message, syntax);
  2023. }
  2024. break;
  2025. }
  2026. case GPBDataTypeGroup: {
  2027. if (GPBGetHasIvarField(self, field)) {
  2028. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has
  2029. // check again.
  2030. GPBMessage *message =
  2031. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  2032. [input readGroup:GPBFieldNumber(field)
  2033. message:message
  2034. extensionRegistry:extensionRegistry];
  2035. } else {
  2036. GPBMessage *message = [[field.msgClass alloc] init];
  2037. [input readGroup:GPBFieldNumber(field)
  2038. message:message
  2039. extensionRegistry:extensionRegistry];
  2040. GPBSetRetainedObjectIvarWithFieldInternal(self, field, message, syntax);
  2041. }
  2042. break;
  2043. }
  2044. case GPBDataTypeEnum: {
  2045. int32_t val = GPBCodedInputStreamReadEnum(&input->state_);
  2046. if (GPBHasPreservingUnknownEnumSemantics(syntax) ||
  2047. [field isValidEnumValue:val]) {
  2048. GPBSetInt32IvarWithFieldInternal(self, field, val, syntax);
  2049. } else {
  2050. GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
  2051. [unknownFields mergeVarintField:GPBFieldNumber(field) value:val];
  2052. }
  2053. }
  2054. } // switch
  2055. }
  2056. static void MergeRepeatedPackedFieldFromCodedInputStream(
  2057. GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax,
  2058. GPBCodedInputStream *input) {
  2059. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2060. GPBCodedInputStreamState *state = &input->state_;
  2061. id genericArray = GetOrCreateArrayIvarWithField(self, field, syntax);
  2062. int32_t length = GPBCodedInputStreamReadInt32(state);
  2063. size_t limit = GPBCodedInputStreamPushLimit(state, length);
  2064. while (GPBCodedInputStreamBytesUntilLimit(state) > 0) {
  2065. switch (fieldDataType) {
  2066. #define CASE_REPEATED_PACKED_POD(NAME, TYPE, ARRAY_TYPE) \
  2067. case GPBDataType##NAME: { \
  2068. TYPE val = GPBCodedInputStreamRead##NAME(state); \
  2069. [(GPB##ARRAY_TYPE##Array *)genericArray addValue:val]; \
  2070. break; \
  2071. }
  2072. CASE_REPEATED_PACKED_POD(Bool, BOOL, Bool)
  2073. CASE_REPEATED_PACKED_POD(Fixed32, uint32_t, UInt32)
  2074. CASE_REPEATED_PACKED_POD(SFixed32, int32_t, Int32)
  2075. CASE_REPEATED_PACKED_POD(Float, float, Float)
  2076. CASE_REPEATED_PACKED_POD(Fixed64, uint64_t, UInt64)
  2077. CASE_REPEATED_PACKED_POD(SFixed64, int64_t, Int64)
  2078. CASE_REPEATED_PACKED_POD(Double, double, Double)
  2079. CASE_REPEATED_PACKED_POD(Int32, int32_t, Int32)
  2080. CASE_REPEATED_PACKED_POD(Int64, int64_t, Int64)
  2081. CASE_REPEATED_PACKED_POD(SInt32, int32_t, Int32)
  2082. CASE_REPEATED_PACKED_POD(SInt64, int64_t, Int64)
  2083. CASE_REPEATED_PACKED_POD(UInt32, uint32_t, UInt32)
  2084. CASE_REPEATED_PACKED_POD(UInt64, uint64_t, UInt64)
  2085. #undef CASE_REPEATED_PACKED_POD
  2086. case GPBDataTypeBytes:
  2087. case GPBDataTypeString:
  2088. case GPBDataTypeMessage:
  2089. case GPBDataTypeGroup:
  2090. NSCAssert(NO, @"Non primitive types can't be packed");
  2091. break;
  2092. case GPBDataTypeEnum: {
  2093. int32_t val = GPBCodedInputStreamReadEnum(state);
  2094. if (GPBHasPreservingUnknownEnumSemantics(syntax) ||
  2095. [field isValidEnumValue:val]) {
  2096. [(GPBEnumArray*)genericArray addRawValue:val];
  2097. } else {
  2098. GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
  2099. [unknownFields mergeVarintField:GPBFieldNumber(field) value:val];
  2100. }
  2101. break;
  2102. }
  2103. } // switch
  2104. } // while(BytesUntilLimit() > 0)
  2105. GPBCodedInputStreamPopLimit(state, limit);
  2106. }
  2107. static void MergeRepeatedNotPackedFieldFromCodedInputStream(
  2108. GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax,
  2109. GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry) {
  2110. GPBCodedInputStreamState *state = &input->state_;
  2111. id genericArray = GetOrCreateArrayIvarWithField(self, field, syntax);
  2112. switch (GPBGetFieldDataType(field)) {
  2113. #define CASE_REPEATED_NOT_PACKED_POD(NAME, TYPE, ARRAY_TYPE) \
  2114. case GPBDataType##NAME: { \
  2115. TYPE val = GPBCodedInputStreamRead##NAME(state); \
  2116. [(GPB##ARRAY_TYPE##Array *)genericArray addValue:val]; \
  2117. break; \
  2118. }
  2119. #define CASE_REPEATED_NOT_PACKED_OBJECT(NAME) \
  2120. case GPBDataType##NAME: { \
  2121. id val = GPBCodedInputStreamReadRetained##NAME(state); \
  2122. [(NSMutableArray*)genericArray addObject:val]; \
  2123. [val release]; \
  2124. break; \
  2125. }
  2126. CASE_REPEATED_NOT_PACKED_POD(Bool, BOOL, Bool)
  2127. CASE_REPEATED_NOT_PACKED_POD(Fixed32, uint32_t, UInt32)
  2128. CASE_REPEATED_NOT_PACKED_POD(SFixed32, int32_t, Int32)
  2129. CASE_REPEATED_NOT_PACKED_POD(Float, float, Float)
  2130. CASE_REPEATED_NOT_PACKED_POD(Fixed64, uint64_t, UInt64)
  2131. CASE_REPEATED_NOT_PACKED_POD(SFixed64, int64_t, Int64)
  2132. CASE_REPEATED_NOT_PACKED_POD(Double, double, Double)
  2133. CASE_REPEATED_NOT_PACKED_POD(Int32, int32_t, Int32)
  2134. CASE_REPEATED_NOT_PACKED_POD(Int64, int64_t, Int64)
  2135. CASE_REPEATED_NOT_PACKED_POD(SInt32, int32_t, Int32)
  2136. CASE_REPEATED_NOT_PACKED_POD(SInt64, int64_t, Int64)
  2137. CASE_REPEATED_NOT_PACKED_POD(UInt32, uint32_t, UInt32)
  2138. CASE_REPEATED_NOT_PACKED_POD(UInt64, uint64_t, UInt64)
  2139. CASE_REPEATED_NOT_PACKED_OBJECT(Bytes)
  2140. CASE_REPEATED_NOT_PACKED_OBJECT(String)
  2141. #undef CASE_REPEATED_NOT_PACKED_POD
  2142. #undef CASE_NOT_PACKED_OBJECT
  2143. case GPBDataTypeMessage: {
  2144. GPBMessage *message = [[field.msgClass alloc] init];
  2145. [input readMessage:message extensionRegistry:extensionRegistry];
  2146. [(NSMutableArray*)genericArray addObject:message];
  2147. [message release];
  2148. break;
  2149. }
  2150. case GPBDataTypeGroup: {
  2151. GPBMessage *message = [[field.msgClass alloc] init];
  2152. [input readGroup:GPBFieldNumber(field)
  2153. message:message
  2154. extensionRegistry:extensionRegistry];
  2155. [(NSMutableArray*)genericArray addObject:message];
  2156. [message release];
  2157. break;
  2158. }
  2159. case GPBDataTypeEnum: {
  2160. int32_t val = GPBCodedInputStreamReadEnum(state);
  2161. if (GPBHasPreservingUnknownEnumSemantics(syntax) ||
  2162. [field isValidEnumValue:val]) {
  2163. [(GPBEnumArray*)genericArray addRawValue:val];
  2164. } else {
  2165. GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
  2166. [unknownFields mergeVarintField:GPBFieldNumber(field) value:val];
  2167. }
  2168. break;
  2169. }
  2170. } // switch
  2171. }
  2172. - (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input
  2173. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
  2174. GPBDescriptor *descriptor = [self descriptor];
  2175. GPBFileSyntax syntax = descriptor.file.syntax;
  2176. GPBCodedInputStreamState *state = &input->state_;
  2177. uint32_t tag = 0;
  2178. NSUInteger startingIndex = 0;
  2179. NSArray *fields = descriptor->fields_;
  2180. NSUInteger numFields = fields.count;
  2181. while (YES) {
  2182. BOOL merged = NO;
  2183. tag = GPBCodedInputStreamReadTag(state);
  2184. if (tag == 0) {
  2185. break; // Reached end.
  2186. }
  2187. for (NSUInteger i = 0; i < numFields; ++i) {
  2188. if (startingIndex >= numFields) startingIndex = 0;
  2189. GPBFieldDescriptor *fieldDescriptor = fields[startingIndex];
  2190. if (GPBFieldTag(fieldDescriptor) == tag) {
  2191. GPBFieldType fieldType = fieldDescriptor.fieldType;
  2192. if (fieldType == GPBFieldTypeSingle) {
  2193. MergeSingleFieldFromCodedInputStream(self, fieldDescriptor, syntax,
  2194. input, extensionRegistry);
  2195. // Well formed protos will only have a single field once, advance
  2196. // the starting index to the next field.
  2197. startingIndex += 1;
  2198. } else if (fieldType == GPBFieldTypeRepeated) {
  2199. if (fieldDescriptor.isPackable) {
  2200. MergeRepeatedPackedFieldFromCodedInputStream(
  2201. self, fieldDescriptor, syntax, input);
  2202. // Well formed protos will only have a repeated field that is
  2203. // packed once, advance the starting index to the next field.
  2204. startingIndex += 1;
  2205. } else {
  2206. MergeRepeatedNotPackedFieldFromCodedInputStream(
  2207. self, fieldDescriptor, syntax, input, extensionRegistry);
  2208. }
  2209. } else { // fieldType == GPBFieldTypeMap
  2210. // GPB*Dictionary or NSDictionary, exact type doesn't matter at this
  2211. // point.
  2212. id map = GetOrCreateMapIvarWithField(self, fieldDescriptor, syntax);
  2213. [input readMapEntry:map
  2214. extensionRegistry:extensionRegistry
  2215. field:fieldDescriptor
  2216. parentMessage:self];
  2217. }
  2218. merged = YES;
  2219. break;
  2220. } else {
  2221. startingIndex += 1;
  2222. }
  2223. } // for(i < numFields)
  2224. if (!merged && (tag != 0)) {
  2225. // Primitive, repeated types can be packed on unpacked on the wire, and
  2226. // are parsed either way. The above loop covered tag in the preferred
  2227. // for, so this need to check the alternate form.
  2228. for (NSUInteger i = 0; i < numFields; ++i) {
  2229. if (startingIndex >= numFields) startingIndex = 0;
  2230. GPBFieldDescriptor *fieldDescriptor = fields[startingIndex];
  2231. if ((fieldDescriptor.fieldType == GPBFieldTypeRepeated) &&
  2232. !GPBFieldDataTypeIsObject(fieldDescriptor) &&
  2233. (GPBFieldAlternateTag(fieldDescriptor) == tag)) {
  2234. BOOL alternateIsPacked = !fieldDescriptor.isPackable;
  2235. if (alternateIsPacked) {
  2236. MergeRepeatedPackedFieldFromCodedInputStream(
  2237. self, fieldDescriptor, syntax, input);
  2238. // Well formed protos will only have a repeated field that is
  2239. // packed once, advance the starting index to the next field.
  2240. startingIndex += 1;
  2241. } else {
  2242. MergeRepeatedNotPackedFieldFromCodedInputStream(
  2243. self, fieldDescriptor, syntax, input, extensionRegistry);
  2244. }
  2245. merged = YES;
  2246. break;
  2247. } else {
  2248. startingIndex += 1;
  2249. }
  2250. }
  2251. }
  2252. if (!merged) {
  2253. if (tag == 0) {
  2254. // zero signals EOF / limit reached
  2255. return;
  2256. } else {
  2257. if (![self parseUnknownField:input
  2258. extensionRegistry:extensionRegistry
  2259. tag:tag]) {
  2260. // it's an endgroup tag
  2261. return;
  2262. }
  2263. }
  2264. } // if(!merged)
  2265. } // while(YES)
  2266. }
  2267. #pragma mark - MergeFrom Support
  2268. - (void)mergeFrom:(GPBMessage *)other {
  2269. Class selfClass = [self class];
  2270. Class otherClass = [other class];
  2271. if (!([selfClass isSubclassOfClass:otherClass] ||
  2272. [otherClass isSubclassOfClass:selfClass])) {
  2273. [NSException raise:NSInvalidArgumentException
  2274. format:@"Classes must match %@ != %@", selfClass, otherClass];
  2275. }
  2276. // We assume something will be done and become visible.
  2277. GPBBecomeVisibleToAutocreator(self);
  2278. GPBDescriptor *descriptor = [[self class] descriptor];
  2279. GPBFileSyntax syntax = descriptor.file.syntax;
  2280. for (GPBFieldDescriptor *field in descriptor->fields_) {
  2281. GPBFieldType fieldType = field.fieldType;
  2282. if (fieldType == GPBFieldTypeSingle) {
  2283. int32_t hasIndex = GPBFieldHasIndex(field);
  2284. uint32_t fieldNumber = GPBFieldNumber(field);
  2285. if (!GPBGetHasIvar(other, hasIndex, fieldNumber)) {
  2286. // Other doesn't have the field set, on to the next.
  2287. continue;
  2288. }
  2289. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2290. switch (fieldDataType) {
  2291. case GPBDataTypeBool:
  2292. GPBSetBoolIvarWithFieldInternal(
  2293. self, field, GPBGetMessageBoolField(other, field), syntax);
  2294. break;
  2295. case GPBDataTypeSFixed32:
  2296. case GPBDataTypeEnum:
  2297. case GPBDataTypeInt32:
  2298. case GPBDataTypeSInt32:
  2299. GPBSetInt32IvarWithFieldInternal(
  2300. self, field, GPBGetMessageInt32Field(other, field), syntax);
  2301. break;
  2302. case GPBDataTypeFixed32:
  2303. case GPBDataTypeUInt32:
  2304. GPBSetUInt32IvarWithFieldInternal(
  2305. self, field, GPBGetMessageUInt32Field(other, field), syntax);
  2306. break;
  2307. case GPBDataTypeSFixed64:
  2308. case GPBDataTypeInt64:
  2309. case GPBDataTypeSInt64:
  2310. GPBSetInt64IvarWithFieldInternal(
  2311. self, field, GPBGetMessageInt64Field(other, field), syntax);
  2312. break;
  2313. case GPBDataTypeFixed64:
  2314. case GPBDataTypeUInt64:
  2315. GPBSetUInt64IvarWithFieldInternal(
  2316. self, field, GPBGetMessageUInt64Field(other, field), syntax);
  2317. break;
  2318. case GPBDataTypeFloat:
  2319. GPBSetFloatIvarWithFieldInternal(
  2320. self, field, GPBGetMessageFloatField(other, field), syntax);
  2321. break;
  2322. case GPBDataTypeDouble:
  2323. GPBSetDoubleIvarWithFieldInternal(
  2324. self, field, GPBGetMessageDoubleField(other, field), syntax);
  2325. break;
  2326. case GPBDataTypeBytes:
  2327. case GPBDataTypeString: {
  2328. id otherVal = GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2329. GPBSetObjectIvarWithFieldInternal(self, field, otherVal, syntax);
  2330. break;
  2331. }
  2332. case GPBDataTypeMessage:
  2333. case GPBDataTypeGroup: {
  2334. id otherVal = GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2335. if (GPBGetHasIvar(self, hasIndex, fieldNumber)) {
  2336. GPBMessage *message =
  2337. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  2338. [message mergeFrom:otherVal];
  2339. } else {
  2340. GPBMessage *message = [otherVal copy];
  2341. GPBSetRetainedObjectIvarWithFieldInternal(self, field, message,
  2342. syntax);
  2343. }
  2344. break;
  2345. }
  2346. } // switch()
  2347. } else if (fieldType == GPBFieldTypeRepeated) {
  2348. // In the case of a list, they need to be appended, and there is no
  2349. // _hasIvar to worry about setting.
  2350. id otherArray =
  2351. GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2352. if (otherArray) {
  2353. GPBDataType fieldDataType = field->description_->dataType;
  2354. if (GPBDataTypeIsObject(fieldDataType)) {
  2355. NSMutableArray *resultArray =
  2356. GetOrCreateArrayIvarWithField(self, field, syntax);
  2357. [resultArray addObjectsFromArray:otherArray];
  2358. } else if (fieldDataType == GPBDataTypeEnum) {
  2359. GPBEnumArray *resultArray =
  2360. GetOrCreateArrayIvarWithField(self, field, syntax);
  2361. [resultArray addRawValuesFromArray:otherArray];
  2362. } else {
  2363. // The array type doesn't matter, that all implement
  2364. // -addValuesFromArray:.
  2365. GPBInt32Array *resultArray =
  2366. GetOrCreateArrayIvarWithField(self, field, syntax);
  2367. [resultArray addValuesFromArray:otherArray];
  2368. }
  2369. }
  2370. } else { // fieldType = GPBFieldTypeMap
  2371. // In the case of a map, they need to be merged, and there is no
  2372. // _hasIvar to worry about setting.
  2373. id otherDict = GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2374. if (otherDict) {
  2375. GPBDataType keyDataType = field.mapKeyDataType;
  2376. GPBDataType valueDataType = field->description_->dataType;
  2377. if (GPBDataTypeIsObject(keyDataType) &&
  2378. GPBDataTypeIsObject(valueDataType)) {
  2379. NSMutableDictionary *resultDict =
  2380. GetOrCreateMapIvarWithField(self, field, syntax);
  2381. [resultDict addEntriesFromDictionary:otherDict];
  2382. } else if (valueDataType == GPBDataTypeEnum) {
  2383. // The exact type doesn't matter, just need to know it is a
  2384. // GPB*EnumDictionary.
  2385. GPBInt32EnumDictionary *resultDict =
  2386. GetOrCreateMapIvarWithField(self, field, syntax);
  2387. [resultDict addRawEntriesFromDictionary:otherDict];
  2388. } else {
  2389. // The exact type doesn't matter, they all implement
  2390. // -addEntriesFromDictionary:.
  2391. GPBInt32Int32Dictionary *resultDict =
  2392. GetOrCreateMapIvarWithField(self, field, syntax);
  2393. [resultDict addEntriesFromDictionary:otherDict];
  2394. }
  2395. }
  2396. } // if (fieldType)..else if...else
  2397. } // for(fields)
  2398. // Unknown fields.
  2399. if (!unknownFields_) {
  2400. [self setUnknownFields:other.unknownFields];
  2401. } else {
  2402. [unknownFields_ mergeUnknownFields:other.unknownFields];
  2403. }
  2404. // Extensions
  2405. if (other->extensionMap_.count == 0) {
  2406. return;
  2407. }
  2408. if (extensionMap_ == nil) {
  2409. extensionMap_ =
  2410. CloneExtensionMap(other->extensionMap_, NSZoneFromPointer(self));
  2411. } else {
  2412. for (GPBExtensionDescriptor *extension in other->extensionMap_) {
  2413. id otherValue = [other->extensionMap_ objectForKey:extension];
  2414. id value = [extensionMap_ objectForKey:extension];
  2415. BOOL isMessageExtension = GPBExtensionIsMessage(extension);
  2416. if (extension.repeated) {
  2417. NSMutableArray *list = value;
  2418. if (list == nil) {
  2419. list = [[NSMutableArray alloc] init];
  2420. [extensionMap_ setObject:list forKey:extension];
  2421. [list release];
  2422. }
  2423. if (isMessageExtension) {
  2424. for (GPBMessage *otherListValue in otherValue) {
  2425. GPBMessage *copiedValue = [otherListValue copy];
  2426. [list addObject:copiedValue];
  2427. [copiedValue release];
  2428. }
  2429. } else {
  2430. [list addObjectsFromArray:otherValue];
  2431. }
  2432. } else {
  2433. if (isMessageExtension) {
  2434. if (value) {
  2435. [(GPBMessage *)value mergeFrom:(GPBMessage *)otherValue];
  2436. } else {
  2437. GPBMessage *copiedValue = [otherValue copy];
  2438. [extensionMap_ setObject:copiedValue forKey:extension];
  2439. [copiedValue release];
  2440. }
  2441. } else {
  2442. [extensionMap_ setObject:otherValue forKey:extension];
  2443. }
  2444. }
  2445. if (isMessageExtension && !extension.isRepeated) {
  2446. GPBMessage *autocreatedValue =
  2447. [[autocreatedExtensionMap_ objectForKey:extension] retain];
  2448. // Must remove from the map before calling GPBClearMessageAutocreator()
  2449. // so that GPBClearMessageAutocreator() knows its safe to clear.
  2450. [autocreatedExtensionMap_ removeObjectForKey:extension];
  2451. GPBClearMessageAutocreator(autocreatedValue);
  2452. [autocreatedValue release];
  2453. }
  2454. }
  2455. }
  2456. }
  2457. #pragma mark - isEqual: & hash Support
  2458. - (BOOL)isEqual:(id)other {
  2459. if (other == self) {
  2460. return YES;
  2461. }
  2462. if (![other isKindOfClass:[GPBMessage class]]) {
  2463. return NO;
  2464. }
  2465. GPBMessage *otherMsg = other;
  2466. GPBDescriptor *descriptor = [[self class] descriptor];
  2467. if ([[otherMsg class] descriptor] != descriptor) {
  2468. return NO;
  2469. }
  2470. uint8_t *selfStorage = (uint8_t *)messageStorage_;
  2471. uint8_t *otherStorage = (uint8_t *)otherMsg->messageStorage_;
  2472. for (GPBFieldDescriptor *field in descriptor->fields_) {
  2473. if (GPBFieldIsMapOrArray(field)) {
  2474. // In the case of a list or map, there is no _hasIvar to worry about.
  2475. // NOTE: These are NSArray/GPB*Array or NSDictionary/GPB*Dictionary, but
  2476. // the type doesn't really matter as the objects all support -count and
  2477. // -isEqual:.
  2478. NSArray *resultMapOrArray =
  2479. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  2480. NSArray *otherMapOrArray =
  2481. GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2482. // nil and empty are equal
  2483. if (resultMapOrArray.count != 0 || otherMapOrArray.count != 0) {
  2484. if (![resultMapOrArray isEqual:otherMapOrArray]) {
  2485. return NO;
  2486. }
  2487. }
  2488. } else { // Single field
  2489. int32_t hasIndex = GPBFieldHasIndex(field);
  2490. uint32_t fieldNum = GPBFieldNumber(field);
  2491. BOOL selfHas = GPBGetHasIvar(self, hasIndex, fieldNum);
  2492. BOOL otherHas = GPBGetHasIvar(other, hasIndex, fieldNum);
  2493. if (selfHas != otherHas) {
  2494. return NO; // Differing has values, not equal.
  2495. }
  2496. if (!selfHas) {
  2497. // Same has values, was no, nothing else to check for this field.
  2498. continue;
  2499. }
  2500. // Now compare the values.
  2501. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2502. size_t fieldOffset = field->description_->offset;
  2503. switch (fieldDataType) {
  2504. case GPBDataTypeBool: {
  2505. // Bools are stored in has_bits to avoid needing explicit space in
  2506. // the storage structure.
  2507. // (the field number passed to the HasIvar helper doesn't really
  2508. // matter since the offset is never negative)
  2509. BOOL selfValue = GPBGetHasIvar(self, (int32_t)(fieldOffset), 0);
  2510. BOOL otherValue = GPBGetHasIvar(other, (int32_t)(fieldOffset), 0);
  2511. if (selfValue != otherValue) {
  2512. return NO;
  2513. }
  2514. break;
  2515. }
  2516. case GPBDataTypeSFixed32:
  2517. case GPBDataTypeInt32:
  2518. case GPBDataTypeSInt32:
  2519. case GPBDataTypeEnum:
  2520. case GPBDataTypeFixed32:
  2521. case GPBDataTypeUInt32:
  2522. case GPBDataTypeFloat: {
  2523. GPBInternalCompileAssert(sizeof(float) == sizeof(uint32_t), float_not_32_bits);
  2524. // These are all 32bit, signed/unsigned doesn't matter for equality.
  2525. uint32_t *selfValPtr = (uint32_t *)&selfStorage[fieldOffset];
  2526. uint32_t *otherValPtr = (uint32_t *)&otherStorage[fieldOffset];
  2527. if (*selfValPtr != *otherValPtr) {
  2528. return NO;
  2529. }
  2530. break;
  2531. }
  2532. case GPBDataTypeSFixed64:
  2533. case GPBDataTypeInt64:
  2534. case GPBDataTypeSInt64:
  2535. case GPBDataTypeFixed64:
  2536. case GPBDataTypeUInt64:
  2537. case GPBDataTypeDouble: {
  2538. GPBInternalCompileAssert(sizeof(double) == sizeof(uint64_t), double_not_64_bits);
  2539. // These are all 64bit, signed/unsigned doesn't matter for equality.
  2540. uint64_t *selfValPtr = (uint64_t *)&selfStorage[fieldOffset];
  2541. uint64_t *otherValPtr = (uint64_t *)&otherStorage[fieldOffset];
  2542. if (*selfValPtr != *otherValPtr) {
  2543. return NO;
  2544. }
  2545. break;
  2546. }
  2547. case GPBDataTypeBytes:
  2548. case GPBDataTypeString:
  2549. case GPBDataTypeMessage:
  2550. case GPBDataTypeGroup: {
  2551. // Type doesn't matter here, they all implement -isEqual:.
  2552. id *selfValPtr = (id *)&selfStorage[fieldOffset];
  2553. id *otherValPtr = (id *)&otherStorage[fieldOffset];
  2554. if (![*selfValPtr isEqual:*otherValPtr]) {
  2555. return NO;
  2556. }
  2557. break;
  2558. }
  2559. } // switch()
  2560. } // if(mapOrArray)...else
  2561. } // for(fields)
  2562. // nil and empty are equal
  2563. if (extensionMap_.count != 0 || otherMsg->extensionMap_.count != 0) {
  2564. if (![extensionMap_ isEqual:otherMsg->extensionMap_]) {
  2565. return NO;
  2566. }
  2567. }
  2568. // nil and empty are equal
  2569. GPBUnknownFieldSet *otherUnknowns = otherMsg->unknownFields_;
  2570. if ([unknownFields_ countOfFields] != 0 ||
  2571. [otherUnknowns countOfFields] != 0) {
  2572. if (![unknownFields_ isEqual:otherUnknowns]) {
  2573. return NO;
  2574. }
  2575. }
  2576. return YES;
  2577. }
  2578. // It is very difficult to implement a generic hash for ProtoBuf messages that
  2579. // will perform well. If you need hashing on your ProtoBufs (eg you are using
  2580. // them as dictionary keys) you will probably want to implement a ProtoBuf
  2581. // message specific hash as a category on your protobuf class. Do not make it a
  2582. // category on GPBMessage as you will conflict with this hash, and will possibly
  2583. // override hash for all generated protobufs. A good implementation of hash will
  2584. // be really fast, so we would recommend only hashing protobufs that have an
  2585. // identifier field of some kind that you can easily hash. If you implement
  2586. // hash, we would strongly recommend overriding isEqual: in your category as
  2587. // well, as the default implementation of isEqual: is extremely slow, and may
  2588. // drastically affect performance in large sets.
  2589. - (NSUInteger)hash {
  2590. GPBDescriptor *descriptor = [[self class] descriptor];
  2591. const NSUInteger prime = 19;
  2592. uint8_t *storage = (uint8_t *)messageStorage_;
  2593. // Start with the descriptor and then mix it with some instance info.
  2594. // Hopefully that will give a spread based on classes and what fields are set.
  2595. NSUInteger result = (NSUInteger)descriptor;
  2596. for (GPBFieldDescriptor *field in descriptor->fields_) {
  2597. if (GPBFieldIsMapOrArray(field)) {
  2598. // Exact type doesn't matter, just check if there are any elements.
  2599. NSArray *mapOrArray = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  2600. NSUInteger count = mapOrArray.count;
  2601. if (count) {
  2602. // NSArray/NSDictionary use count, use the field number and the count.
  2603. result = prime * result + GPBFieldNumber(field);
  2604. result = prime * result + count;
  2605. }
  2606. } else if (GPBGetHasIvarField(self, field)) {
  2607. // Just using the field number seemed simple/fast, but then a small
  2608. // message class where all the same fields are always set (to different
  2609. // things would end up all with the same hash, so pull in some data).
  2610. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2611. size_t fieldOffset = field->description_->offset;
  2612. switch (fieldDataType) {
  2613. case GPBDataTypeBool: {
  2614. // Bools are stored in has_bits to avoid needing explicit space in
  2615. // the storage structure.
  2616. // (the field number passed to the HasIvar helper doesn't really
  2617. // matter since the offset is never negative)
  2618. BOOL value = GPBGetHasIvar(self, (int32_t)(fieldOffset), 0);
  2619. result = prime * result + value;
  2620. break;
  2621. }
  2622. case GPBDataTypeSFixed32:
  2623. case GPBDataTypeInt32:
  2624. case GPBDataTypeSInt32:
  2625. case GPBDataTypeEnum:
  2626. case GPBDataTypeFixed32:
  2627. case GPBDataTypeUInt32:
  2628. case GPBDataTypeFloat: {
  2629. GPBInternalCompileAssert(sizeof(float) == sizeof(uint32_t), float_not_32_bits);
  2630. // These are all 32bit, just mix it in.
  2631. uint32_t *valPtr = (uint32_t *)&storage[fieldOffset];
  2632. result = prime * result + *valPtr;
  2633. break;
  2634. }
  2635. case GPBDataTypeSFixed64:
  2636. case GPBDataTypeInt64:
  2637. case GPBDataTypeSInt64:
  2638. case GPBDataTypeFixed64:
  2639. case GPBDataTypeUInt64:
  2640. case GPBDataTypeDouble: {
  2641. GPBInternalCompileAssert(sizeof(double) == sizeof(uint64_t), double_not_64_bits);
  2642. // These are all 64bit, just mix what fits into an NSUInteger in.
  2643. uint64_t *valPtr = (uint64_t *)&storage[fieldOffset];
  2644. result = prime * result + (NSUInteger)(*valPtr);
  2645. break;
  2646. }
  2647. case GPBDataTypeBytes:
  2648. case GPBDataTypeString: {
  2649. // Type doesn't matter here, they both implement -hash:.
  2650. id *valPtr = (id *)&storage[fieldOffset];
  2651. result = prime * result + [*valPtr hash];
  2652. break;
  2653. }
  2654. case GPBDataTypeMessage:
  2655. case GPBDataTypeGroup: {
  2656. GPBMessage **valPtr = (GPBMessage **)&storage[fieldOffset];
  2657. // Could call -hash on the sub message, but that could recurse pretty
  2658. // deep; follow the lead of NSArray/NSDictionary and don't really
  2659. // recurse for hash, instead use the field number and the descriptor
  2660. // of the sub message. Yes, this could suck for a bunch of messages
  2661. // where they all only differ in the sub messages, but if you are
  2662. // using a message with sub messages for something that needs -hash,
  2663. // odds are you are also copying them as keys, and that deep copy
  2664. // will also suck.
  2665. result = prime * result + GPBFieldNumber(field);
  2666. result = prime * result + (NSUInteger)[[*valPtr class] descriptor];
  2667. break;
  2668. }
  2669. } // switch()
  2670. }
  2671. }
  2672. // Unknowns and extensions are not included.
  2673. return result;
  2674. }
  2675. #pragma mark - Description Support
  2676. - (NSString *)description {
  2677. NSString *textFormat = GPBTextFormatForMessage(self, @" ");
  2678. NSString *description = [NSString
  2679. stringWithFormat:@"<%@ %p>: {\n%@}", [self class], self, textFormat];
  2680. return description;
  2681. }
  2682. #if defined(DEBUG) && DEBUG
  2683. // Xcode 5.1 added support for custom quick look info.
  2684. // 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
  2685. - (id)debugQuickLookObject {
  2686. return GPBTextFormatForMessage(self, nil);
  2687. }
  2688. #endif // DEBUG
  2689. #pragma mark - SerializedSize
  2690. - (size_t)serializedSize {
  2691. GPBDescriptor *descriptor = [[self class] descriptor];
  2692. size_t result = 0;
  2693. // Has check is done explicitly, so GPBGetObjectIvarWithFieldNoAutocreate()
  2694. // avoids doing the has check again.
  2695. // Fields.
  2696. for (GPBFieldDescriptor *fieldDescriptor in descriptor->fields_) {
  2697. GPBFieldType fieldType = fieldDescriptor.fieldType;
  2698. GPBDataType fieldDataType = GPBGetFieldDataType(fieldDescriptor);
  2699. // Single Fields
  2700. if (fieldType == GPBFieldTypeSingle) {
  2701. BOOL selfHas = GPBGetHasIvarField(self, fieldDescriptor);
  2702. if (!selfHas) {
  2703. continue; // Nothing to do.
  2704. }
  2705. uint32_t fieldNumber = GPBFieldNumber(fieldDescriptor);
  2706. switch (fieldDataType) {
  2707. #define CASE_SINGLE_POD(NAME, TYPE, FUNC_TYPE) \
  2708. case GPBDataType##NAME: { \
  2709. TYPE fieldVal = GPBGetMessage##FUNC_TYPE##Field(self, fieldDescriptor); \
  2710. result += GPBCompute##NAME##Size(fieldNumber, fieldVal); \
  2711. break; \
  2712. }
  2713. #define CASE_SINGLE_OBJECT(NAME) \
  2714. case GPBDataType##NAME: { \
  2715. id fieldVal = GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor); \
  2716. result += GPBCompute##NAME##Size(fieldNumber, fieldVal); \
  2717. break; \
  2718. }
  2719. CASE_SINGLE_POD(Bool, BOOL, Bool)
  2720. CASE_SINGLE_POD(Fixed32, uint32_t, UInt32)
  2721. CASE_SINGLE_POD(SFixed32, int32_t, Int32)
  2722. CASE_SINGLE_POD(Float, float, Float)
  2723. CASE_SINGLE_POD(Fixed64, uint64_t, UInt64)
  2724. CASE_SINGLE_POD(SFixed64, int64_t, Int64)
  2725. CASE_SINGLE_POD(Double, double, Double)
  2726. CASE_SINGLE_POD(Int32, int32_t, Int32)
  2727. CASE_SINGLE_POD(Int64, int64_t, Int64)
  2728. CASE_SINGLE_POD(SInt32, int32_t, Int32)
  2729. CASE_SINGLE_POD(SInt64, int64_t, Int64)
  2730. CASE_SINGLE_POD(UInt32, uint32_t, UInt32)
  2731. CASE_SINGLE_POD(UInt64, uint64_t, UInt64)
  2732. CASE_SINGLE_OBJECT(Bytes)
  2733. CASE_SINGLE_OBJECT(String)
  2734. CASE_SINGLE_OBJECT(Message)
  2735. CASE_SINGLE_OBJECT(Group)
  2736. CASE_SINGLE_POD(Enum, int32_t, Int32)
  2737. #undef CASE_SINGLE_POD
  2738. #undef CASE_SINGLE_OBJECT
  2739. }
  2740. // Repeated Fields
  2741. } else if (fieldType == GPBFieldTypeRepeated) {
  2742. id genericArray =
  2743. GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor);
  2744. NSUInteger count = [genericArray count];
  2745. if (count == 0) {
  2746. continue; // Nothing to add.
  2747. }
  2748. __block size_t dataSize = 0;
  2749. switch (fieldDataType) {
  2750. #define CASE_REPEATED_POD(NAME, TYPE, ARRAY_TYPE) \
  2751. CASE_REPEATED_POD_EXTRA(NAME, TYPE, ARRAY_TYPE, )
  2752. #define CASE_REPEATED_POD_EXTRA(NAME, TYPE, ARRAY_TYPE, ARRAY_ACCESSOR_NAME) \
  2753. case GPBDataType##NAME: { \
  2754. GPB##ARRAY_TYPE##Array *array = genericArray; \
  2755. [array enumerate##ARRAY_ACCESSOR_NAME##ValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { \
  2756. _Pragma("unused(idx, stop)"); \
  2757. dataSize += GPBCompute##NAME##SizeNoTag(value); \
  2758. }]; \
  2759. break; \
  2760. }
  2761. #define CASE_REPEATED_OBJECT(NAME) \
  2762. case GPBDataType##NAME: { \
  2763. for (id value in genericArray) { \
  2764. dataSize += GPBCompute##NAME##SizeNoTag(value); \
  2765. } \
  2766. break; \
  2767. }
  2768. CASE_REPEATED_POD(Bool, BOOL, Bool)
  2769. CASE_REPEATED_POD(Fixed32, uint32_t, UInt32)
  2770. CASE_REPEATED_POD(SFixed32, int32_t, Int32)
  2771. CASE_REPEATED_POD(Float, float, Float)
  2772. CASE_REPEATED_POD(Fixed64, uint64_t, UInt64)
  2773. CASE_REPEATED_POD(SFixed64, int64_t, Int64)
  2774. CASE_REPEATED_POD(Double, double, Double)
  2775. CASE_REPEATED_POD(Int32, int32_t, Int32)
  2776. CASE_REPEATED_POD(Int64, int64_t, Int64)
  2777. CASE_REPEATED_POD(SInt32, int32_t, Int32)
  2778. CASE_REPEATED_POD(SInt64, int64_t, Int64)
  2779. CASE_REPEATED_POD(UInt32, uint32_t, UInt32)
  2780. CASE_REPEATED_POD(UInt64, uint64_t, UInt64)
  2781. CASE_REPEATED_OBJECT(Bytes)
  2782. CASE_REPEATED_OBJECT(String)
  2783. CASE_REPEATED_OBJECT(Message)
  2784. CASE_REPEATED_OBJECT(Group)
  2785. CASE_REPEATED_POD_EXTRA(Enum, int32_t, Enum, Raw)
  2786. #undef CASE_REPEATED_POD
  2787. #undef CASE_REPEATED_POD_EXTRA
  2788. #undef CASE_REPEATED_OBJECT
  2789. } // switch
  2790. result += dataSize;
  2791. size_t tagSize = GPBComputeTagSize(GPBFieldNumber(fieldDescriptor));
  2792. if (fieldDataType == GPBDataTypeGroup) {
  2793. // Groups have both a start and an end tag.
  2794. tagSize *= 2;
  2795. }
  2796. if (fieldDescriptor.isPackable) {
  2797. result += tagSize;
  2798. result += GPBComputeSizeTSizeAsInt32NoTag(dataSize);
  2799. } else {
  2800. result += count * tagSize;
  2801. }
  2802. // Map<> Fields
  2803. } else { // fieldType == GPBFieldTypeMap
  2804. if (GPBDataTypeIsObject(fieldDataType) &&
  2805. (fieldDescriptor.mapKeyDataType == GPBDataTypeString)) {
  2806. // If key type was string, then the map is an NSDictionary.
  2807. NSDictionary *map =
  2808. GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor);
  2809. if (map) {
  2810. result += GPBDictionaryComputeSizeInternalHelper(map, fieldDescriptor);
  2811. }
  2812. } else {
  2813. // Type will be GPB*GroupDictionary, exact type doesn't matter.
  2814. GPBInt32Int32Dictionary *map =
  2815. GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor);
  2816. result += [map computeSerializedSizeAsField:fieldDescriptor];
  2817. }
  2818. }
  2819. } // for(fields)
  2820. // Add any unknown fields.
  2821. if (descriptor.wireFormat) {
  2822. result += [unknownFields_ serializedSizeAsMessageSet];
  2823. } else {
  2824. result += [unknownFields_ serializedSize];
  2825. }
  2826. // Add any extensions.
  2827. for (GPBExtensionDescriptor *extension in extensionMap_) {
  2828. id value = [extensionMap_ objectForKey:extension];
  2829. result += GPBComputeExtensionSerializedSizeIncludingTag(extension, value);
  2830. }
  2831. return result;
  2832. }
  2833. #pragma mark - Resolve Methods Support
  2834. typedef struct ResolveIvarAccessorMethodResult {
  2835. IMP impToAdd;
  2836. SEL encodingSelector;
  2837. } ResolveIvarAccessorMethodResult;
  2838. // |field| can be __unsafe_unretained because they are created at startup
  2839. // and are essentially global. No need to pay for retain/release when
  2840. // they are captured in blocks.
  2841. static void ResolveIvarGet(__unsafe_unretained GPBFieldDescriptor *field,
  2842. ResolveIvarAccessorMethodResult *result) {
  2843. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2844. switch (fieldDataType) {
  2845. #define CASE_GET(NAME, TYPE, TRUE_NAME) \
  2846. case GPBDataType##NAME: { \
  2847. result->impToAdd = imp_implementationWithBlock(^(id obj) { \
  2848. return GPBGetMessage##TRUE_NAME##Field(obj, field); \
  2849. }); \
  2850. result->encodingSelector = @selector(get##NAME); \
  2851. break; \
  2852. }
  2853. #define CASE_GET_OBJECT(NAME, TYPE, TRUE_NAME) \
  2854. case GPBDataType##NAME: { \
  2855. result->impToAdd = imp_implementationWithBlock(^(id obj) { \
  2856. return GPBGetObjectIvarWithField(obj, field); \
  2857. }); \
  2858. result->encodingSelector = @selector(get##NAME); \
  2859. break; \
  2860. }
  2861. CASE_GET(Bool, BOOL, Bool)
  2862. CASE_GET(Fixed32, uint32_t, UInt32)
  2863. CASE_GET(SFixed32, int32_t, Int32)
  2864. CASE_GET(Float, float, Float)
  2865. CASE_GET(Fixed64, uint64_t, UInt64)
  2866. CASE_GET(SFixed64, int64_t, Int64)
  2867. CASE_GET(Double, double, Double)
  2868. CASE_GET(Int32, int32_t, Int32)
  2869. CASE_GET(Int64, int64_t, Int64)
  2870. CASE_GET(SInt32, int32_t, Int32)
  2871. CASE_GET(SInt64, int64_t, Int64)
  2872. CASE_GET(UInt32, uint32_t, UInt32)
  2873. CASE_GET(UInt64, uint64_t, UInt64)
  2874. CASE_GET_OBJECT(Bytes, id, Object)
  2875. CASE_GET_OBJECT(String, id, Object)
  2876. CASE_GET_OBJECT(Message, id, Object)
  2877. CASE_GET_OBJECT(Group, id, Object)
  2878. CASE_GET(Enum, int32_t, Enum)
  2879. #undef CASE_GET
  2880. }
  2881. }
  2882. // See comment about __unsafe_unretained on ResolveIvarGet.
  2883. static void ResolveIvarSet(__unsafe_unretained GPBFieldDescriptor *field,
  2884. GPBFileSyntax syntax,
  2885. ResolveIvarAccessorMethodResult *result) {
  2886. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2887. switch (fieldDataType) {
  2888. #define CASE_SET(NAME, TYPE, TRUE_NAME) \
  2889. case GPBDataType##NAME: { \
  2890. result->impToAdd = imp_implementationWithBlock(^(id obj, TYPE value) { \
  2891. return GPBSet##TRUE_NAME##IvarWithFieldInternal(obj, field, value, syntax); \
  2892. }); \
  2893. result->encodingSelector = @selector(set##NAME:); \
  2894. break; \
  2895. }
  2896. #define CASE_SET_COPY(NAME) \
  2897. case GPBDataType##NAME: { \
  2898. result->impToAdd = imp_implementationWithBlock(^(id obj, id value) { \
  2899. return GPBSetRetainedObjectIvarWithFieldInternal(obj, field, [value copy], syntax); \
  2900. }); \
  2901. result->encodingSelector = @selector(set##NAME:); \
  2902. break; \
  2903. }
  2904. CASE_SET(Bool, BOOL, Bool)
  2905. CASE_SET(Fixed32, uint32_t, UInt32)
  2906. CASE_SET(SFixed32, int32_t, Int32)
  2907. CASE_SET(Float, float, Float)
  2908. CASE_SET(Fixed64, uint64_t, UInt64)
  2909. CASE_SET(SFixed64, int64_t, Int64)
  2910. CASE_SET(Double, double, Double)
  2911. CASE_SET(Int32, int32_t, Int32)
  2912. CASE_SET(Int64, int64_t, Int64)
  2913. CASE_SET(SInt32, int32_t, Int32)
  2914. CASE_SET(SInt64, int64_t, Int64)
  2915. CASE_SET(UInt32, uint32_t, UInt32)
  2916. CASE_SET(UInt64, uint64_t, UInt64)
  2917. CASE_SET_COPY(Bytes)
  2918. CASE_SET_COPY(String)
  2919. CASE_SET(Message, id, Object)
  2920. CASE_SET(Group, id, Object)
  2921. CASE_SET(Enum, int32_t, Enum)
  2922. #undef CASE_SET
  2923. }
  2924. }
  2925. + (BOOL)resolveInstanceMethod:(SEL)sel {
  2926. const GPBDescriptor *descriptor = [self descriptor];
  2927. if (!descriptor) {
  2928. return [super resolveInstanceMethod:sel];
  2929. }
  2930. // NOTE: hasOrCountSel_/setHasSel_ will be NULL if the field for the given
  2931. // message should not have has support (done in GPBDescriptor.m), so there is
  2932. // no need for checks here to see if has*/setHas* are allowed.
  2933. ResolveIvarAccessorMethodResult result = {NULL, NULL};
  2934. // See comment about __unsafe_unretained on ResolveIvarGet.
  2935. for (__unsafe_unretained GPBFieldDescriptor *field in descriptor->fields_) {
  2936. BOOL isMapOrArray = GPBFieldIsMapOrArray(field);
  2937. if (!isMapOrArray) {
  2938. // Single fields.
  2939. if (sel == field->getSel_) {
  2940. ResolveIvarGet(field, &result);
  2941. break;
  2942. } else if (sel == field->setSel_) {
  2943. ResolveIvarSet(field, descriptor.file.syntax, &result);
  2944. break;
  2945. } else if (sel == field->hasOrCountSel_) {
  2946. int32_t index = GPBFieldHasIndex(field);
  2947. uint32_t fieldNum = GPBFieldNumber(field);
  2948. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  2949. return GPBGetHasIvar(obj, index, fieldNum);
  2950. });
  2951. result.encodingSelector = @selector(getBool);
  2952. break;
  2953. } else if (sel == field->setHasSel_) {
  2954. result.impToAdd = imp_implementationWithBlock(^(id obj, BOOL value) {
  2955. if (value) {
  2956. [NSException raise:NSInvalidArgumentException
  2957. format:@"%@: %@ can only be set to NO (to clear field).",
  2958. [obj class],
  2959. NSStringFromSelector(field->setHasSel_)];
  2960. }
  2961. GPBClearMessageField(obj, field);
  2962. });
  2963. result.encodingSelector = @selector(setBool:);
  2964. break;
  2965. } else {
  2966. GPBOneofDescriptor *oneof = field->containingOneof_;
  2967. if (oneof && (sel == oneof->caseSel_)) {
  2968. int32_t index = GPBFieldHasIndex(field);
  2969. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  2970. return GPBGetHasOneof(obj, index);
  2971. });
  2972. result.encodingSelector = @selector(getEnum);
  2973. break;
  2974. }
  2975. }
  2976. } else {
  2977. // map<>/repeated fields.
  2978. if (sel == field->getSel_) {
  2979. if (field.fieldType == GPBFieldTypeRepeated) {
  2980. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  2981. return GetArrayIvarWithField(obj, field);
  2982. });
  2983. } else {
  2984. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  2985. return GetMapIvarWithField(obj, field);
  2986. });
  2987. }
  2988. result.encodingSelector = @selector(getArray);
  2989. break;
  2990. } else if (sel == field->setSel_) {
  2991. // Local for syntax so the block can directly capture it and not the
  2992. // full lookup.
  2993. const GPBFileSyntax syntax = descriptor.file.syntax;
  2994. result.impToAdd = imp_implementationWithBlock(^(id obj, id value) {
  2995. GPBSetObjectIvarWithFieldInternal(obj, field, value, syntax);
  2996. });
  2997. result.encodingSelector = @selector(setArray:);
  2998. break;
  2999. } else if (sel == field->hasOrCountSel_) {
  3000. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  3001. // Type doesn't matter, all *Array and *Dictionary types support
  3002. // -count.
  3003. NSArray *arrayOrMap =
  3004. GPBGetObjectIvarWithFieldNoAutocreate(obj, field);
  3005. return [arrayOrMap count];
  3006. });
  3007. result.encodingSelector = @selector(getArrayCount);
  3008. break;
  3009. }
  3010. }
  3011. }
  3012. if (result.impToAdd) {
  3013. const char *encoding =
  3014. GPBMessageEncodingForSelector(result.encodingSelector, YES);
  3015. Class msgClass = descriptor.messageClass;
  3016. BOOL methodAdded = class_addMethod(msgClass, sel, result.impToAdd, encoding);
  3017. // class_addMethod() is documented as also failing if the method was already
  3018. // added; so we check if the method is already there and return success so
  3019. // the method dispatch will still happen. Why would it already be added?
  3020. // Two threads could cause the same method to be bound at the same time,
  3021. // but only one will actually bind it; the other still needs to return true
  3022. // so things will dispatch.
  3023. if (!methodAdded) {
  3024. methodAdded = GPBClassHasSel(msgClass, sel);
  3025. }
  3026. return methodAdded;
  3027. }
  3028. return [super resolveInstanceMethod:sel];
  3029. }
  3030. + (BOOL)resolveClassMethod:(SEL)sel {
  3031. // Extensions scoped to a Message and looked up via class methods.
  3032. if (GPBResolveExtensionClassMethod([self descriptor].messageClass, sel)) {
  3033. return YES;
  3034. }
  3035. return [super resolveClassMethod:sel];
  3036. }
  3037. #pragma mark - NSCoding Support
  3038. + (BOOL)supportsSecureCoding {
  3039. return YES;
  3040. }
  3041. - (instancetype)initWithCoder:(NSCoder *)aDecoder {
  3042. self = [self init];
  3043. if (self) {
  3044. NSData *data =
  3045. [aDecoder decodeObjectOfClass:[NSData class] forKey:kGPBDataCoderKey];
  3046. if (data.length) {
  3047. [self mergeFromData:data extensionRegistry:nil];
  3048. }
  3049. }
  3050. return self;
  3051. }
  3052. - (void)encodeWithCoder:(NSCoder *)aCoder {
  3053. #if defined(DEBUG) && DEBUG
  3054. if (extensionMap_.count) {
  3055. // Hint to go along with the docs on GPBMessage about this.
  3056. //
  3057. // Note: This is incomplete, in that it only checked the "root" message,
  3058. // if a sub message in a field has extensions, the issue still exists. A
  3059. // recursive check could be done here (like the work in
  3060. // GPBMessageDropUnknownFieldsRecursively()), but that has the potential to
  3061. // be expensive and could slow down serialization in DEBUG enought to cause
  3062. // developers other problems.
  3063. NSLog(@"Warning: writing out a GPBMessage (%@) via NSCoding and it"
  3064. @" has %ld extensions; when read back in, those fields will be"
  3065. @" in the unknownFields property instead.",
  3066. [self class], (long)extensionMap_.count);
  3067. }
  3068. #endif
  3069. NSData *data = [self data];
  3070. if (data.length) {
  3071. [aCoder encodeObject:data forKey:kGPBDataCoderKey];
  3072. }
  3073. }
  3074. #pragma mark - KVC Support
  3075. + (BOOL)accessInstanceVariablesDirectly {
  3076. // Make sure KVC doesn't use instance variables.
  3077. return NO;
  3078. }
  3079. @end
  3080. #pragma mark - Messages from GPBUtilities.h but defined here for access to helpers.
  3081. // Only exists for public api, no core code should use this.
  3082. id GPBGetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field) {
  3083. #if defined(DEBUG) && DEBUG
  3084. if (field.fieldType != GPBFieldTypeRepeated) {
  3085. [NSException raise:NSInvalidArgumentException
  3086. format:@"%@.%@ is not a repeated field.",
  3087. [self class], field.name];
  3088. }
  3089. #endif
  3090. GPBDescriptor *descriptor = [[self class] descriptor];
  3091. GPBFileSyntax syntax = descriptor.file.syntax;
  3092. return GetOrCreateArrayIvarWithField(self, field, syntax);
  3093. }
  3094. // Only exists for public api, no core code should use this.
  3095. id GPBGetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field) {
  3096. #if defined(DEBUG) && DEBUG
  3097. if (field.fieldType != GPBFieldTypeMap) {
  3098. [NSException raise:NSInvalidArgumentException
  3099. format:@"%@.%@ is not a map<> field.",
  3100. [self class], field.name];
  3101. }
  3102. #endif
  3103. GPBDescriptor *descriptor = [[self class] descriptor];
  3104. GPBFileSyntax syntax = descriptor.file.syntax;
  3105. return GetOrCreateMapIvarWithField(self, field, syntax);
  3106. }
  3107. id GPBGetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
  3108. NSCAssert(!GPBFieldIsMapOrArray(field), @"Shouldn't get here");
  3109. if (GPBGetHasIvarField(self, field)) {
  3110. uint8_t *storage = (uint8_t *)self->messageStorage_;
  3111. id *typePtr = (id *)&storage[field->description_->offset];
  3112. return *typePtr;
  3113. }
  3114. // Not set...
  3115. // Non messages (string/data), get their default.
  3116. if (!GPBFieldDataTypeIsMessage(field)) {
  3117. return field.defaultValue.valueMessage;
  3118. }
  3119. GPBPrepareReadOnlySemaphore(self);
  3120. dispatch_semaphore_wait(self->readOnlySemaphore_, DISPATCH_TIME_FOREVER);
  3121. GPBMessage *result = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  3122. if (!result) {
  3123. // For non repeated messages, create the object, set it and return it.
  3124. // This object will not initially be visible via GPBGetHasIvar, so
  3125. // we save its creator so it can become visible if it's mutated later.
  3126. result = GPBCreateMessageWithAutocreator(field.msgClass, self, field);
  3127. GPBSetAutocreatedRetainedObjectIvarWithField(self, field, result);
  3128. }
  3129. dispatch_semaphore_signal(self->readOnlySemaphore_);
  3130. return result;
  3131. }
  3132. #pragma clang diagnostic pop