GPBMessage.m 119 KB

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