GPBMessage.m 121 KB

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