GPBMessage.m 121 KB

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