GPBMessage.m 119 KB

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