GPBMessage.m 118 KB

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