GPBMessage.m 126 KB

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