GPBMessage.m 119 KB

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