GPBMessage.m 118 KB

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