GPBMessage.m 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325
  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. for (NSUInteger i = 0, j = 0; i < fieldCount || j < extensionRangesCount;) {
  1203. if (i == fieldCount) {
  1204. [self writeExtensionsToCodedOutputStream:output
  1205. range:extensionRanges[j++]];
  1206. } else if (j == extensionRangesCount ||
  1207. GPBFieldNumber(fieldsArray[i]) < extensionRanges[j].start) {
  1208. [self writeField:fieldsArray[i++] toCodedOutputStream:output];
  1209. } else {
  1210. [self writeExtensionsToCodedOutputStream:output
  1211. range:extensionRanges[j++]];
  1212. }
  1213. }
  1214. if (descriptor.isWireFormat) {
  1215. [unknownFields_ writeAsMessageSetTo:output];
  1216. } else {
  1217. [unknownFields_ writeToCodedOutputStream:output];
  1218. }
  1219. }
  1220. - (void)writeDelimitedToOutputStream:(NSOutputStream *)output {
  1221. GPBCodedOutputStream *codedOutput =
  1222. [[GPBCodedOutputStream alloc] initWithOutputStream:output];
  1223. [self writeDelimitedToCodedOutputStream:codedOutput];
  1224. [codedOutput release];
  1225. }
  1226. - (void)writeDelimitedToCodedOutputStream:(GPBCodedOutputStream *)output {
  1227. [output writeRawVarintSizeTAs32:[self serializedSize]];
  1228. [self writeToCodedOutputStream:output];
  1229. }
  1230. - (void)writeField:(GPBFieldDescriptor *)field
  1231. toCodedOutputStream:(GPBCodedOutputStream *)output {
  1232. GPBFieldType fieldType = field.fieldType;
  1233. if (fieldType == GPBFieldTypeSingle) {
  1234. BOOL has = GPBGetHasIvarField(self, field);
  1235. if (!has) {
  1236. return;
  1237. }
  1238. }
  1239. uint32_t fieldNumber = GPBFieldNumber(field);
  1240. //%PDDM-DEFINE FIELD_CASE(TYPE, REAL_TYPE)
  1241. //%FIELD_CASE_FULL(TYPE, REAL_TYPE, REAL_TYPE)
  1242. //%PDDM-DEFINE FIELD_CASE_FULL(TYPE, REAL_TYPE, ARRAY_TYPE)
  1243. //% case GPBDataType##TYPE:
  1244. //% if (fieldType == GPBFieldTypeRepeated) {
  1245. //% uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1246. //% GPB##ARRAY_TYPE##Array *array =
  1247. //% GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1248. //% [output write##TYPE##Array:fieldNumber values:array tag:tag];
  1249. //% } else if (fieldType == GPBFieldTypeSingle) {
  1250. //% [output write##TYPE:fieldNumber
  1251. //% TYPE$S value:GPBGetMessage##REAL_TYPE##Field(self, field)];
  1252. //% } else { // fieldType == GPBFieldTypeMap
  1253. //% // Exact type here doesn't matter.
  1254. //% GPBInt32##ARRAY_TYPE##Dictionary *dict =
  1255. //% GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1256. //% [dict writeToCodedOutputStream:output asField:field];
  1257. //% }
  1258. //% break;
  1259. //%
  1260. //%PDDM-DEFINE FIELD_CASE2(TYPE)
  1261. //% case GPBDataType##TYPE:
  1262. //% if (fieldType == GPBFieldTypeRepeated) {
  1263. //% NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1264. //% [output write##TYPE##Array:fieldNumber values:array];
  1265. //% } else if (fieldType == GPBFieldTypeSingle) {
  1266. //% // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1267. //% // again.
  1268. //% [output write##TYPE:fieldNumber
  1269. //% TYPE$S value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1270. //% } else { // fieldType == GPBFieldTypeMap
  1271. //% // Exact type here doesn't matter.
  1272. //% id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1273. //% GPBDataType mapKeyDataType = field.mapKeyDataType;
  1274. //% if (mapKeyDataType == GPBDataTypeString) {
  1275. //% GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1276. //% } else {
  1277. //% [dict writeToCodedOutputStream:output asField:field];
  1278. //% }
  1279. //% }
  1280. //% break;
  1281. //%
  1282. switch (GPBGetFieldDataType(field)) {
  1283. //%PDDM-EXPAND FIELD_CASE(Bool, Bool)
  1284. // This block of code is generated, do not edit it directly.
  1285. case GPBDataTypeBool:
  1286. if (fieldType == GPBFieldTypeRepeated) {
  1287. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1288. GPBBoolArray *array =
  1289. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1290. [output writeBoolArray:fieldNumber values:array tag:tag];
  1291. } else if (fieldType == GPBFieldTypeSingle) {
  1292. [output writeBool:fieldNumber
  1293. value:GPBGetMessageBoolField(self, field)];
  1294. } else { // fieldType == GPBFieldTypeMap
  1295. // Exact type here doesn't matter.
  1296. GPBInt32BoolDictionary *dict =
  1297. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1298. [dict writeToCodedOutputStream:output asField:field];
  1299. }
  1300. break;
  1301. //%PDDM-EXPAND FIELD_CASE(Fixed32, UInt32)
  1302. // This block of code is generated, do not edit it directly.
  1303. case GPBDataTypeFixed32:
  1304. if (fieldType == GPBFieldTypeRepeated) {
  1305. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1306. GPBUInt32Array *array =
  1307. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1308. [output writeFixed32Array:fieldNumber values:array tag:tag];
  1309. } else if (fieldType == GPBFieldTypeSingle) {
  1310. [output writeFixed32:fieldNumber
  1311. value:GPBGetMessageUInt32Field(self, field)];
  1312. } else { // fieldType == GPBFieldTypeMap
  1313. // Exact type here doesn't matter.
  1314. GPBInt32UInt32Dictionary *dict =
  1315. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1316. [dict writeToCodedOutputStream:output asField:field];
  1317. }
  1318. break;
  1319. //%PDDM-EXPAND FIELD_CASE(SFixed32, Int32)
  1320. // This block of code is generated, do not edit it directly.
  1321. case GPBDataTypeSFixed32:
  1322. if (fieldType == GPBFieldTypeRepeated) {
  1323. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1324. GPBInt32Array *array =
  1325. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1326. [output writeSFixed32Array:fieldNumber values:array tag:tag];
  1327. } else if (fieldType == GPBFieldTypeSingle) {
  1328. [output writeSFixed32:fieldNumber
  1329. value:GPBGetMessageInt32Field(self, field)];
  1330. } else { // fieldType == GPBFieldTypeMap
  1331. // Exact type here doesn't matter.
  1332. GPBInt32Int32Dictionary *dict =
  1333. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1334. [dict writeToCodedOutputStream:output asField:field];
  1335. }
  1336. break;
  1337. //%PDDM-EXPAND FIELD_CASE(Float, Float)
  1338. // This block of code is generated, do not edit it directly.
  1339. case GPBDataTypeFloat:
  1340. if (fieldType == GPBFieldTypeRepeated) {
  1341. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1342. GPBFloatArray *array =
  1343. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1344. [output writeFloatArray:fieldNumber values:array tag:tag];
  1345. } else if (fieldType == GPBFieldTypeSingle) {
  1346. [output writeFloat:fieldNumber
  1347. value:GPBGetMessageFloatField(self, field)];
  1348. } else { // fieldType == GPBFieldTypeMap
  1349. // Exact type here doesn't matter.
  1350. GPBInt32FloatDictionary *dict =
  1351. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1352. [dict writeToCodedOutputStream:output asField:field];
  1353. }
  1354. break;
  1355. //%PDDM-EXPAND FIELD_CASE(Fixed64, UInt64)
  1356. // This block of code is generated, do not edit it directly.
  1357. case GPBDataTypeFixed64:
  1358. if (fieldType == GPBFieldTypeRepeated) {
  1359. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1360. GPBUInt64Array *array =
  1361. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1362. [output writeFixed64Array:fieldNumber values:array tag:tag];
  1363. } else if (fieldType == GPBFieldTypeSingle) {
  1364. [output writeFixed64:fieldNumber
  1365. value:GPBGetMessageUInt64Field(self, field)];
  1366. } else { // fieldType == GPBFieldTypeMap
  1367. // Exact type here doesn't matter.
  1368. GPBInt32UInt64Dictionary *dict =
  1369. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1370. [dict writeToCodedOutputStream:output asField:field];
  1371. }
  1372. break;
  1373. //%PDDM-EXPAND FIELD_CASE(SFixed64, Int64)
  1374. // This block of code is generated, do not edit it directly.
  1375. case GPBDataTypeSFixed64:
  1376. if (fieldType == GPBFieldTypeRepeated) {
  1377. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1378. GPBInt64Array *array =
  1379. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1380. [output writeSFixed64Array:fieldNumber values:array tag:tag];
  1381. } else if (fieldType == GPBFieldTypeSingle) {
  1382. [output writeSFixed64:fieldNumber
  1383. value:GPBGetMessageInt64Field(self, field)];
  1384. } else { // fieldType == GPBFieldTypeMap
  1385. // Exact type here doesn't matter.
  1386. GPBInt32Int64Dictionary *dict =
  1387. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1388. [dict writeToCodedOutputStream:output asField:field];
  1389. }
  1390. break;
  1391. //%PDDM-EXPAND FIELD_CASE(Double, Double)
  1392. // This block of code is generated, do not edit it directly.
  1393. case GPBDataTypeDouble:
  1394. if (fieldType == GPBFieldTypeRepeated) {
  1395. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1396. GPBDoubleArray *array =
  1397. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1398. [output writeDoubleArray:fieldNumber values:array tag:tag];
  1399. } else if (fieldType == GPBFieldTypeSingle) {
  1400. [output writeDouble:fieldNumber
  1401. value:GPBGetMessageDoubleField(self, field)];
  1402. } else { // fieldType == GPBFieldTypeMap
  1403. // Exact type here doesn't matter.
  1404. GPBInt32DoubleDictionary *dict =
  1405. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1406. [dict writeToCodedOutputStream:output asField:field];
  1407. }
  1408. break;
  1409. //%PDDM-EXPAND FIELD_CASE(Int32, Int32)
  1410. // This block of code is generated, do not edit it directly.
  1411. case GPBDataTypeInt32:
  1412. if (fieldType == GPBFieldTypeRepeated) {
  1413. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1414. GPBInt32Array *array =
  1415. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1416. [output writeInt32Array:fieldNumber values:array tag:tag];
  1417. } else if (fieldType == GPBFieldTypeSingle) {
  1418. [output writeInt32:fieldNumber
  1419. value:GPBGetMessageInt32Field(self, field)];
  1420. } else { // fieldType == GPBFieldTypeMap
  1421. // Exact type here doesn't matter.
  1422. GPBInt32Int32Dictionary *dict =
  1423. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1424. [dict writeToCodedOutputStream:output asField:field];
  1425. }
  1426. break;
  1427. //%PDDM-EXPAND FIELD_CASE(Int64, Int64)
  1428. // This block of code is generated, do not edit it directly.
  1429. case GPBDataTypeInt64:
  1430. if (fieldType == GPBFieldTypeRepeated) {
  1431. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1432. GPBInt64Array *array =
  1433. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1434. [output writeInt64Array:fieldNumber values:array tag:tag];
  1435. } else if (fieldType == GPBFieldTypeSingle) {
  1436. [output writeInt64:fieldNumber
  1437. value:GPBGetMessageInt64Field(self, field)];
  1438. } else { // fieldType == GPBFieldTypeMap
  1439. // Exact type here doesn't matter.
  1440. GPBInt32Int64Dictionary *dict =
  1441. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1442. [dict writeToCodedOutputStream:output asField:field];
  1443. }
  1444. break;
  1445. //%PDDM-EXPAND FIELD_CASE(SInt32, Int32)
  1446. // This block of code is generated, do not edit it directly.
  1447. case GPBDataTypeSInt32:
  1448. if (fieldType == GPBFieldTypeRepeated) {
  1449. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1450. GPBInt32Array *array =
  1451. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1452. [output writeSInt32Array:fieldNumber values:array tag:tag];
  1453. } else if (fieldType == GPBFieldTypeSingle) {
  1454. [output writeSInt32:fieldNumber
  1455. value:GPBGetMessageInt32Field(self, field)];
  1456. } else { // fieldType == GPBFieldTypeMap
  1457. // Exact type here doesn't matter.
  1458. GPBInt32Int32Dictionary *dict =
  1459. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1460. [dict writeToCodedOutputStream:output asField:field];
  1461. }
  1462. break;
  1463. //%PDDM-EXPAND FIELD_CASE(SInt64, Int64)
  1464. // This block of code is generated, do not edit it directly.
  1465. case GPBDataTypeSInt64:
  1466. if (fieldType == GPBFieldTypeRepeated) {
  1467. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1468. GPBInt64Array *array =
  1469. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1470. [output writeSInt64Array:fieldNumber values:array tag:tag];
  1471. } else if (fieldType == GPBFieldTypeSingle) {
  1472. [output writeSInt64:fieldNumber
  1473. value:GPBGetMessageInt64Field(self, field)];
  1474. } else { // fieldType == GPBFieldTypeMap
  1475. // Exact type here doesn't matter.
  1476. GPBInt32Int64Dictionary *dict =
  1477. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1478. [dict writeToCodedOutputStream:output asField:field];
  1479. }
  1480. break;
  1481. //%PDDM-EXPAND FIELD_CASE(UInt32, UInt32)
  1482. // This block of code is generated, do not edit it directly.
  1483. case GPBDataTypeUInt32:
  1484. if (fieldType == GPBFieldTypeRepeated) {
  1485. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1486. GPBUInt32Array *array =
  1487. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1488. [output writeUInt32Array:fieldNumber values:array tag:tag];
  1489. } else if (fieldType == GPBFieldTypeSingle) {
  1490. [output writeUInt32:fieldNumber
  1491. value:GPBGetMessageUInt32Field(self, field)];
  1492. } else { // fieldType == GPBFieldTypeMap
  1493. // Exact type here doesn't matter.
  1494. GPBInt32UInt32Dictionary *dict =
  1495. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1496. [dict writeToCodedOutputStream:output asField:field];
  1497. }
  1498. break;
  1499. //%PDDM-EXPAND FIELD_CASE(UInt64, UInt64)
  1500. // This block of code is generated, do not edit it directly.
  1501. case GPBDataTypeUInt64:
  1502. if (fieldType == GPBFieldTypeRepeated) {
  1503. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1504. GPBUInt64Array *array =
  1505. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1506. [output writeUInt64Array:fieldNumber values:array tag:tag];
  1507. } else if (fieldType == GPBFieldTypeSingle) {
  1508. [output writeUInt64:fieldNumber
  1509. value:GPBGetMessageUInt64Field(self, field)];
  1510. } else { // fieldType == GPBFieldTypeMap
  1511. // Exact type here doesn't matter.
  1512. GPBInt32UInt64Dictionary *dict =
  1513. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1514. [dict writeToCodedOutputStream:output asField:field];
  1515. }
  1516. break;
  1517. //%PDDM-EXPAND FIELD_CASE_FULL(Enum, Int32, Enum)
  1518. // This block of code is generated, do not edit it directly.
  1519. case GPBDataTypeEnum:
  1520. if (fieldType == GPBFieldTypeRepeated) {
  1521. uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0;
  1522. GPBEnumArray *array =
  1523. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1524. [output writeEnumArray:fieldNumber values:array tag:tag];
  1525. } else if (fieldType == GPBFieldTypeSingle) {
  1526. [output writeEnum:fieldNumber
  1527. value:GPBGetMessageInt32Field(self, field)];
  1528. } else { // fieldType == GPBFieldTypeMap
  1529. // Exact type here doesn't matter.
  1530. GPBInt32EnumDictionary *dict =
  1531. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1532. [dict writeToCodedOutputStream:output asField:field];
  1533. }
  1534. break;
  1535. //%PDDM-EXPAND FIELD_CASE2(Bytes)
  1536. // This block of code is generated, do not edit it directly.
  1537. case GPBDataTypeBytes:
  1538. if (fieldType == GPBFieldTypeRepeated) {
  1539. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1540. [output writeBytesArray:fieldNumber values:array];
  1541. } else if (fieldType == GPBFieldTypeSingle) {
  1542. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1543. // again.
  1544. [output writeBytes:fieldNumber
  1545. value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1546. } else { // fieldType == GPBFieldTypeMap
  1547. // Exact type here doesn't matter.
  1548. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1549. GPBDataType mapKeyDataType = field.mapKeyDataType;
  1550. if (mapKeyDataType == GPBDataTypeString) {
  1551. GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1552. } else {
  1553. [dict writeToCodedOutputStream:output asField:field];
  1554. }
  1555. }
  1556. break;
  1557. //%PDDM-EXPAND FIELD_CASE2(String)
  1558. // This block of code is generated, do not edit it directly.
  1559. case GPBDataTypeString:
  1560. if (fieldType == GPBFieldTypeRepeated) {
  1561. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1562. [output writeStringArray:fieldNumber values:array];
  1563. } else if (fieldType == GPBFieldTypeSingle) {
  1564. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1565. // again.
  1566. [output writeString:fieldNumber
  1567. value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1568. } else { // fieldType == GPBFieldTypeMap
  1569. // Exact type here doesn't matter.
  1570. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1571. GPBDataType mapKeyDataType = field.mapKeyDataType;
  1572. if (mapKeyDataType == GPBDataTypeString) {
  1573. GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1574. } else {
  1575. [dict writeToCodedOutputStream:output asField:field];
  1576. }
  1577. }
  1578. break;
  1579. //%PDDM-EXPAND FIELD_CASE2(Message)
  1580. // This block of code is generated, do not edit it directly.
  1581. case GPBDataTypeMessage:
  1582. if (fieldType == GPBFieldTypeRepeated) {
  1583. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1584. [output writeMessageArray:fieldNumber values:array];
  1585. } else if (fieldType == GPBFieldTypeSingle) {
  1586. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1587. // again.
  1588. [output writeMessage:fieldNumber
  1589. value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1590. } else { // fieldType == GPBFieldTypeMap
  1591. // Exact type here doesn't matter.
  1592. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1593. GPBDataType mapKeyDataType = field.mapKeyDataType;
  1594. if (mapKeyDataType == GPBDataTypeString) {
  1595. GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1596. } else {
  1597. [dict writeToCodedOutputStream:output asField:field];
  1598. }
  1599. }
  1600. break;
  1601. //%PDDM-EXPAND FIELD_CASE2(Group)
  1602. // This block of code is generated, do not edit it directly.
  1603. case GPBDataTypeGroup:
  1604. if (fieldType == GPBFieldTypeRepeated) {
  1605. NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1606. [output writeGroupArray:fieldNumber values:array];
  1607. } else if (fieldType == GPBFieldTypeSingle) {
  1608. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check
  1609. // again.
  1610. [output writeGroup:fieldNumber
  1611. value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)];
  1612. } else { // fieldType == GPBFieldTypeMap
  1613. // Exact type here doesn't matter.
  1614. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1615. GPBDataType mapKeyDataType = field.mapKeyDataType;
  1616. if (mapKeyDataType == GPBDataTypeString) {
  1617. GPBDictionaryWriteToStreamInternalHelper(output, dict, field);
  1618. } else {
  1619. [dict writeToCodedOutputStream:output asField:field];
  1620. }
  1621. }
  1622. break;
  1623. //%PDDM-EXPAND-END (18 expansions)
  1624. }
  1625. }
  1626. #pragma mark - Extensions
  1627. - (id)getExtension:(GPBExtensionDescriptor *)extension {
  1628. CheckExtension(self, extension);
  1629. id value = [extensionMap_ objectForKey:extension];
  1630. if (value != nil) {
  1631. return value;
  1632. }
  1633. // No default for repeated.
  1634. if (extension.isRepeated) {
  1635. return nil;
  1636. }
  1637. // Non messages get their default.
  1638. if (!GPBExtensionIsMessage(extension)) {
  1639. return extension.defaultValue;
  1640. }
  1641. // Check for an autocreated value.
  1642. GPBPrepareReadOnlySemaphore(self);
  1643. dispatch_semaphore_wait(readOnlySemaphore_, DISPATCH_TIME_FOREVER);
  1644. value = [autocreatedExtensionMap_ objectForKey:extension];
  1645. if (!value) {
  1646. // Auto create the message extensions to match normal fields.
  1647. value = CreateMessageWithAutocreatorForExtension(extension.msgClass, self,
  1648. extension);
  1649. if (autocreatedExtensionMap_ == nil) {
  1650. autocreatedExtensionMap_ = [[NSMutableDictionary alloc] init];
  1651. }
  1652. // We can't simply call setExtension here because that would clear the new
  1653. // value's autocreator.
  1654. [autocreatedExtensionMap_ setObject:value forKey:extension];
  1655. [value release];
  1656. }
  1657. dispatch_semaphore_signal(readOnlySemaphore_);
  1658. return value;
  1659. }
  1660. - (id)getExistingExtension:(GPBExtensionDescriptor *)extension {
  1661. // This is an internal method so we don't need to call CheckExtension().
  1662. return [extensionMap_ objectForKey:extension];
  1663. }
  1664. - (BOOL)hasExtension:(GPBExtensionDescriptor *)extension {
  1665. #if defined(DEBUG) && DEBUG
  1666. CheckExtension(self, extension);
  1667. #endif // DEBUG
  1668. return nil != [extensionMap_ objectForKey:extension];
  1669. }
  1670. - (NSArray *)extensionsCurrentlySet {
  1671. return [extensionMap_ allKeys];
  1672. }
  1673. - (void)writeExtensionsToCodedOutputStream:(GPBCodedOutputStream *)output
  1674. range:(GPBExtensionRange)range {
  1675. NSArray *sortedExtensions = [[extensionMap_ allKeys]
  1676. sortedArrayUsingSelector:@selector(compareByFieldNumber:)];
  1677. uint32_t start = range.start;
  1678. uint32_t end = range.end;
  1679. for (GPBExtensionDescriptor *extension in sortedExtensions) {
  1680. uint32_t fieldNumber = extension.fieldNumber;
  1681. if (fieldNumber >= start && fieldNumber < end) {
  1682. id value = [extensionMap_ objectForKey:extension];
  1683. GPBWriteExtensionValueToOutputStream(extension, value, output);
  1684. }
  1685. }
  1686. }
  1687. - (void)setExtension:(GPBExtensionDescriptor *)extension value:(id)value {
  1688. if (!value) {
  1689. [self clearExtension:extension];
  1690. return;
  1691. }
  1692. CheckExtension(self, extension);
  1693. if (extension.repeated) {
  1694. [NSException raise:NSInvalidArgumentException
  1695. format:@"Must call addExtension() for repeated types."];
  1696. }
  1697. if (extensionMap_ == nil) {
  1698. extensionMap_ = [[NSMutableDictionary alloc] init];
  1699. }
  1700. // This pointless cast is for CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION.
  1701. // Without it, the compiler complains we're passing an id nullable when
  1702. // setObject:forKey: requires a id nonnull for the value. The check for
  1703. // !value at the start of the method ensures it isn't nil, but the check
  1704. // isn't smart enough to realize that.
  1705. [extensionMap_ setObject:(id)value forKey:extension];
  1706. GPBExtensionDescriptor *descriptor = extension;
  1707. if (GPBExtensionIsMessage(descriptor) && !descriptor.isRepeated) {
  1708. GPBMessage *autocreatedValue =
  1709. [[autocreatedExtensionMap_ objectForKey:extension] retain];
  1710. // Must remove from the map before calling GPBClearMessageAutocreator() so
  1711. // that GPBClearMessageAutocreator() knows its safe to clear.
  1712. [autocreatedExtensionMap_ removeObjectForKey:extension];
  1713. GPBClearMessageAutocreator(autocreatedValue);
  1714. [autocreatedValue release];
  1715. }
  1716. GPBBecomeVisibleToAutocreator(self);
  1717. }
  1718. - (void)addExtension:(GPBExtensionDescriptor *)extension value:(id)value {
  1719. CheckExtension(self, extension);
  1720. if (!extension.repeated) {
  1721. [NSException raise:NSInvalidArgumentException
  1722. format:@"Must call setExtension() for singular types."];
  1723. }
  1724. if (extensionMap_ == nil) {
  1725. extensionMap_ = [[NSMutableDictionary alloc] init];
  1726. }
  1727. NSMutableArray *list = [extensionMap_ objectForKey:extension];
  1728. if (list == nil) {
  1729. list = [NSMutableArray array];
  1730. [extensionMap_ setObject:list forKey:extension];
  1731. }
  1732. [list addObject:value];
  1733. GPBBecomeVisibleToAutocreator(self);
  1734. }
  1735. - (void)setExtension:(GPBExtensionDescriptor *)extension
  1736. index:(NSUInteger)idx
  1737. value:(id)value {
  1738. CheckExtension(self, extension);
  1739. if (!extension.repeated) {
  1740. [NSException raise:NSInvalidArgumentException
  1741. format:@"Must call setExtension() for singular types."];
  1742. }
  1743. if (extensionMap_ == nil) {
  1744. extensionMap_ = [[NSMutableDictionary alloc] init];
  1745. }
  1746. NSMutableArray *list = [extensionMap_ objectForKey:extension];
  1747. [list replaceObjectAtIndex:idx withObject:value];
  1748. GPBBecomeVisibleToAutocreator(self);
  1749. }
  1750. - (void)clearExtension:(GPBExtensionDescriptor *)extension {
  1751. CheckExtension(self, extension);
  1752. // Only become visible if there was actually a value to clear.
  1753. if ([extensionMap_ objectForKey:extension]) {
  1754. [extensionMap_ removeObjectForKey:extension];
  1755. GPBBecomeVisibleToAutocreator(self);
  1756. }
  1757. }
  1758. #pragma mark - mergeFrom
  1759. - (void)mergeFromData:(NSData *)data
  1760. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
  1761. GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data];
  1762. [self mergeFromCodedInputStream:input extensionRegistry:extensionRegistry];
  1763. [input checkLastTagWas:0];
  1764. [input release];
  1765. }
  1766. #pragma mark - mergeDelimitedFrom
  1767. - (void)mergeDelimitedFromCodedInputStream:(GPBCodedInputStream *)input
  1768. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
  1769. GPBCodedInputStreamState *state = &input->state_;
  1770. if (GPBCodedInputStreamIsAtEnd(state)) {
  1771. return;
  1772. }
  1773. NSData *data = GPBCodedInputStreamReadRetainedBytesNoCopy(state);
  1774. if (data == nil) {
  1775. return;
  1776. }
  1777. [self mergeFromData:data extensionRegistry:extensionRegistry];
  1778. [data release];
  1779. }
  1780. #pragma mark - Parse From Data Support
  1781. + (instancetype)parseFromData:(NSData *)data error:(NSError **)errorPtr {
  1782. return [self parseFromData:data extensionRegistry:nil error:errorPtr];
  1783. }
  1784. + (instancetype)parseFromData:(NSData *)data
  1785. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry
  1786. error:(NSError **)errorPtr {
  1787. return [[[self alloc] initWithData:data
  1788. extensionRegistry:extensionRegistry
  1789. error:errorPtr] autorelease];
  1790. }
  1791. + (instancetype)parseFromCodedInputStream:(GPBCodedInputStream *)input
  1792. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry
  1793. error:(NSError **)errorPtr {
  1794. return
  1795. [[[self alloc] initWithCodedInputStream:input
  1796. extensionRegistry:extensionRegistry
  1797. error:errorPtr] autorelease];
  1798. }
  1799. #pragma mark - Parse Delimited From Data Support
  1800. + (instancetype)parseDelimitedFromCodedInputStream:(GPBCodedInputStream *)input
  1801. extensionRegistry:
  1802. (GPBExtensionRegistry *)extensionRegistry
  1803. error:(NSError **)errorPtr {
  1804. GPBMessage *message = [[[self alloc] init] autorelease];
  1805. @try {
  1806. [message mergeDelimitedFromCodedInputStream:input
  1807. extensionRegistry:extensionRegistry];
  1808. if (errorPtr) {
  1809. *errorPtr = nil;
  1810. }
  1811. }
  1812. @catch (NSException *exception) {
  1813. message = nil;
  1814. if (errorPtr) {
  1815. *errorPtr = ErrorFromException(exception);
  1816. }
  1817. }
  1818. #ifdef DEBUG
  1819. if (message && !message.initialized) {
  1820. message = nil;
  1821. if (errorPtr) {
  1822. *errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil);
  1823. }
  1824. }
  1825. #endif
  1826. return message;
  1827. }
  1828. #pragma mark - Unknown Field Support
  1829. - (GPBUnknownFieldSet *)unknownFields {
  1830. return unknownFields_;
  1831. }
  1832. - (void)setUnknownFields:(GPBUnknownFieldSet *)unknownFields {
  1833. if (unknownFields != unknownFields_) {
  1834. [unknownFields_ release];
  1835. unknownFields_ = [unknownFields copy];
  1836. GPBBecomeVisibleToAutocreator(self);
  1837. }
  1838. }
  1839. - (void)parseMessageSet:(GPBCodedInputStream *)input
  1840. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
  1841. uint32_t typeId = 0;
  1842. NSData *rawBytes = nil;
  1843. GPBExtensionDescriptor *extension = nil;
  1844. GPBCodedInputStreamState *state = &input->state_;
  1845. while (true) {
  1846. uint32_t tag = GPBCodedInputStreamReadTag(state);
  1847. if (tag == 0) {
  1848. break;
  1849. }
  1850. if (tag == GPBWireFormatMessageSetTypeIdTag) {
  1851. typeId = GPBCodedInputStreamReadUInt32(state);
  1852. if (typeId != 0) {
  1853. extension = [extensionRegistry extensionForDescriptor:[self descriptor]
  1854. fieldNumber:typeId];
  1855. }
  1856. } else if (tag == GPBWireFormatMessageSetMessageTag) {
  1857. rawBytes =
  1858. [GPBCodedInputStreamReadRetainedBytesNoCopy(state) autorelease];
  1859. } else {
  1860. if (![input skipField:tag]) {
  1861. break;
  1862. }
  1863. }
  1864. }
  1865. [input checkLastTagWas:GPBWireFormatMessageSetItemEndTag];
  1866. if (rawBytes != nil && typeId != 0) {
  1867. if (extension != nil) {
  1868. GPBCodedInputStream *newInput =
  1869. [[GPBCodedInputStream alloc] initWithData:rawBytes];
  1870. GPBExtensionMergeFromInputStream(extension,
  1871. extension.packable,
  1872. newInput,
  1873. extensionRegistry,
  1874. self);
  1875. [newInput release];
  1876. } else {
  1877. GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
  1878. // rawBytes was created via a NoCopy, so it can be reusing a
  1879. // subrange of another NSData that might go out of scope as things
  1880. // unwind, so a copy is needed to ensure what is saved in the
  1881. // unknown fields stays valid.
  1882. NSData *cloned = [NSData dataWithData:rawBytes];
  1883. [unknownFields mergeMessageSetMessage:typeId data:cloned];
  1884. }
  1885. }
  1886. }
  1887. - (BOOL)parseUnknownField:(GPBCodedInputStream *)input
  1888. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry
  1889. tag:(uint32_t)tag {
  1890. GPBWireFormat wireType = GPBWireFormatGetTagWireType(tag);
  1891. int32_t fieldNumber = GPBWireFormatGetTagFieldNumber(tag);
  1892. GPBDescriptor *descriptor = [self descriptor];
  1893. GPBExtensionDescriptor *extension =
  1894. [extensionRegistry extensionForDescriptor:descriptor
  1895. fieldNumber:fieldNumber];
  1896. if (extension == nil) {
  1897. if (descriptor.wireFormat && GPBWireFormatMessageSetItemTag == tag) {
  1898. [self parseMessageSet:input extensionRegistry:extensionRegistry];
  1899. return YES;
  1900. }
  1901. } else {
  1902. if (extension.wireType == wireType) {
  1903. GPBExtensionMergeFromInputStream(extension,
  1904. extension.packable,
  1905. input,
  1906. extensionRegistry,
  1907. self);
  1908. return YES;
  1909. }
  1910. // Primitive, repeated types can be packed on unpacked on the wire, and are
  1911. // parsed either way.
  1912. if ([extension isRepeated] &&
  1913. !GPBDataTypeIsObject(extension->description_->dataType) &&
  1914. (extension.alternateWireType == wireType)) {
  1915. GPBExtensionMergeFromInputStream(extension,
  1916. !extension.packable,
  1917. input,
  1918. extensionRegistry,
  1919. self);
  1920. return YES;
  1921. }
  1922. }
  1923. if ([GPBUnknownFieldSet isFieldTag:tag]) {
  1924. GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
  1925. return [unknownFields mergeFieldFrom:tag input:input];
  1926. } else {
  1927. return NO;
  1928. }
  1929. }
  1930. - (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data {
  1931. GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
  1932. [unknownFields addUnknownMapEntry:fieldNum value:data];
  1933. }
  1934. #pragma mark - MergeFromCodedInputStream Support
  1935. static void MergeSingleFieldFromCodedInputStream(
  1936. GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax,
  1937. GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry) {
  1938. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  1939. switch (fieldDataType) {
  1940. #define CASE_SINGLE_POD(NAME, TYPE, FUNC_TYPE) \
  1941. case GPBDataType##NAME: { \
  1942. TYPE val = GPBCodedInputStreamRead##NAME(&input->state_); \
  1943. GPBSet##FUNC_TYPE##IvarWithFieldInternal(self, field, val, syntax); \
  1944. break; \
  1945. }
  1946. #define CASE_SINGLE_OBJECT(NAME) \
  1947. case GPBDataType##NAME: { \
  1948. id val = GPBCodedInputStreamReadRetained##NAME(&input->state_); \
  1949. GPBSetRetainedObjectIvarWithFieldInternal(self, field, val, syntax); \
  1950. break; \
  1951. }
  1952. CASE_SINGLE_POD(Bool, BOOL, Bool)
  1953. CASE_SINGLE_POD(Fixed32, uint32_t, UInt32)
  1954. CASE_SINGLE_POD(SFixed32, int32_t, Int32)
  1955. CASE_SINGLE_POD(Float, float, Float)
  1956. CASE_SINGLE_POD(Fixed64, uint64_t, UInt64)
  1957. CASE_SINGLE_POD(SFixed64, int64_t, Int64)
  1958. CASE_SINGLE_POD(Double, double, Double)
  1959. CASE_SINGLE_POD(Int32, int32_t, Int32)
  1960. CASE_SINGLE_POD(Int64, int64_t, Int64)
  1961. CASE_SINGLE_POD(SInt32, int32_t, Int32)
  1962. CASE_SINGLE_POD(SInt64, int64_t, Int64)
  1963. CASE_SINGLE_POD(UInt32, uint32_t, UInt32)
  1964. CASE_SINGLE_POD(UInt64, uint64_t, UInt64)
  1965. CASE_SINGLE_OBJECT(Bytes)
  1966. CASE_SINGLE_OBJECT(String)
  1967. #undef CASE_SINGLE_POD
  1968. #undef CASE_SINGLE_OBJECT
  1969. case GPBDataTypeMessage: {
  1970. if (GPBGetHasIvarField(self, field)) {
  1971. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has
  1972. // check again.
  1973. GPBMessage *message =
  1974. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1975. [input readMessage:message extensionRegistry:extensionRegistry];
  1976. } else {
  1977. GPBMessage *message = [[field.msgClass alloc] init];
  1978. [input readMessage:message extensionRegistry:extensionRegistry];
  1979. GPBSetRetainedObjectIvarWithFieldInternal(self, field, message, syntax);
  1980. }
  1981. break;
  1982. }
  1983. case GPBDataTypeGroup: {
  1984. if (GPBGetHasIvarField(self, field)) {
  1985. // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has
  1986. // check again.
  1987. GPBMessage *message =
  1988. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  1989. [input readGroup:GPBFieldNumber(field)
  1990. message:message
  1991. extensionRegistry:extensionRegistry];
  1992. } else {
  1993. GPBMessage *message = [[field.msgClass alloc] init];
  1994. [input readGroup:GPBFieldNumber(field)
  1995. message:message
  1996. extensionRegistry:extensionRegistry];
  1997. GPBSetRetainedObjectIvarWithFieldInternal(self, field, message, syntax);
  1998. }
  1999. break;
  2000. }
  2001. case GPBDataTypeEnum: {
  2002. int32_t val = GPBCodedInputStreamReadEnum(&input->state_);
  2003. if (GPBHasPreservingUnknownEnumSemantics(syntax) ||
  2004. [field isValidEnumValue:val]) {
  2005. GPBSetInt32IvarWithFieldInternal(self, field, val, syntax);
  2006. } else {
  2007. GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
  2008. [unknownFields mergeVarintField:GPBFieldNumber(field) value:val];
  2009. }
  2010. }
  2011. } // switch
  2012. }
  2013. static void MergeRepeatedPackedFieldFromCodedInputStream(
  2014. GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax,
  2015. GPBCodedInputStream *input) {
  2016. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2017. GPBCodedInputStreamState *state = &input->state_;
  2018. id genericArray = GetOrCreateArrayIvarWithField(self, field, syntax);
  2019. int32_t length = GPBCodedInputStreamReadInt32(state);
  2020. size_t limit = GPBCodedInputStreamPushLimit(state, length);
  2021. while (GPBCodedInputStreamBytesUntilLimit(state) > 0) {
  2022. switch (fieldDataType) {
  2023. #define CASE_REPEATED_PACKED_POD(NAME, TYPE, ARRAY_TYPE) \
  2024. case GPBDataType##NAME: { \
  2025. TYPE val = GPBCodedInputStreamRead##NAME(state); \
  2026. [(GPB##ARRAY_TYPE##Array *)genericArray addValue:val]; \
  2027. break; \
  2028. }
  2029. CASE_REPEATED_PACKED_POD(Bool, BOOL, Bool)
  2030. CASE_REPEATED_PACKED_POD(Fixed32, uint32_t, UInt32)
  2031. CASE_REPEATED_PACKED_POD(SFixed32, int32_t, Int32)
  2032. CASE_REPEATED_PACKED_POD(Float, float, Float)
  2033. CASE_REPEATED_PACKED_POD(Fixed64, uint64_t, UInt64)
  2034. CASE_REPEATED_PACKED_POD(SFixed64, int64_t, Int64)
  2035. CASE_REPEATED_PACKED_POD(Double, double, Double)
  2036. CASE_REPEATED_PACKED_POD(Int32, int32_t, Int32)
  2037. CASE_REPEATED_PACKED_POD(Int64, int64_t, Int64)
  2038. CASE_REPEATED_PACKED_POD(SInt32, int32_t, Int32)
  2039. CASE_REPEATED_PACKED_POD(SInt64, int64_t, Int64)
  2040. CASE_REPEATED_PACKED_POD(UInt32, uint32_t, UInt32)
  2041. CASE_REPEATED_PACKED_POD(UInt64, uint64_t, UInt64)
  2042. #undef CASE_REPEATED_PACKED_POD
  2043. case GPBDataTypeBytes:
  2044. case GPBDataTypeString:
  2045. case GPBDataTypeMessage:
  2046. case GPBDataTypeGroup:
  2047. NSCAssert(NO, @"Non primitive types can't be packed");
  2048. break;
  2049. case GPBDataTypeEnum: {
  2050. int32_t val = GPBCodedInputStreamReadEnum(state);
  2051. if (GPBHasPreservingUnknownEnumSemantics(syntax) ||
  2052. [field isValidEnumValue:val]) {
  2053. [(GPBEnumArray*)genericArray addRawValue:val];
  2054. } else {
  2055. GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
  2056. [unknownFields mergeVarintField:GPBFieldNumber(field) value:val];
  2057. }
  2058. break;
  2059. }
  2060. } // switch
  2061. } // while(BytesUntilLimit() > 0)
  2062. GPBCodedInputStreamPopLimit(state, limit);
  2063. }
  2064. static void MergeRepeatedNotPackedFieldFromCodedInputStream(
  2065. GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax,
  2066. GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry) {
  2067. GPBCodedInputStreamState *state = &input->state_;
  2068. id genericArray = GetOrCreateArrayIvarWithField(self, field, syntax);
  2069. switch (GPBGetFieldDataType(field)) {
  2070. #define CASE_REPEATED_NOT_PACKED_POD(NAME, TYPE, ARRAY_TYPE) \
  2071. case GPBDataType##NAME: { \
  2072. TYPE val = GPBCodedInputStreamRead##NAME(state); \
  2073. [(GPB##ARRAY_TYPE##Array *)genericArray addValue:val]; \
  2074. break; \
  2075. }
  2076. #define CASE_REPEATED_NOT_PACKED_OBJECT(NAME) \
  2077. case GPBDataType##NAME: { \
  2078. id val = GPBCodedInputStreamReadRetained##NAME(state); \
  2079. [(NSMutableArray*)genericArray addObject:val]; \
  2080. [val release]; \
  2081. break; \
  2082. }
  2083. CASE_REPEATED_NOT_PACKED_POD(Bool, BOOL, Bool)
  2084. CASE_REPEATED_NOT_PACKED_POD(Fixed32, uint32_t, UInt32)
  2085. CASE_REPEATED_NOT_PACKED_POD(SFixed32, int32_t, Int32)
  2086. CASE_REPEATED_NOT_PACKED_POD(Float, float, Float)
  2087. CASE_REPEATED_NOT_PACKED_POD(Fixed64, uint64_t, UInt64)
  2088. CASE_REPEATED_NOT_PACKED_POD(SFixed64, int64_t, Int64)
  2089. CASE_REPEATED_NOT_PACKED_POD(Double, double, Double)
  2090. CASE_REPEATED_NOT_PACKED_POD(Int32, int32_t, Int32)
  2091. CASE_REPEATED_NOT_PACKED_POD(Int64, int64_t, Int64)
  2092. CASE_REPEATED_NOT_PACKED_POD(SInt32, int32_t, Int32)
  2093. CASE_REPEATED_NOT_PACKED_POD(SInt64, int64_t, Int64)
  2094. CASE_REPEATED_NOT_PACKED_POD(UInt32, uint32_t, UInt32)
  2095. CASE_REPEATED_NOT_PACKED_POD(UInt64, uint64_t, UInt64)
  2096. CASE_REPEATED_NOT_PACKED_OBJECT(Bytes)
  2097. CASE_REPEATED_NOT_PACKED_OBJECT(String)
  2098. #undef CASE_REPEATED_NOT_PACKED_POD
  2099. #undef CASE_NOT_PACKED_OBJECT
  2100. case GPBDataTypeMessage: {
  2101. GPBMessage *message = [[field.msgClass alloc] init];
  2102. [input readMessage:message extensionRegistry:extensionRegistry];
  2103. [(NSMutableArray*)genericArray addObject:message];
  2104. [message release];
  2105. break;
  2106. }
  2107. case GPBDataTypeGroup: {
  2108. GPBMessage *message = [[field.msgClass alloc] init];
  2109. [input readGroup:GPBFieldNumber(field)
  2110. message:message
  2111. extensionRegistry:extensionRegistry];
  2112. [(NSMutableArray*)genericArray addObject:message];
  2113. [message release];
  2114. break;
  2115. }
  2116. case GPBDataTypeEnum: {
  2117. int32_t val = GPBCodedInputStreamReadEnum(state);
  2118. if (GPBHasPreservingUnknownEnumSemantics(syntax) ||
  2119. [field isValidEnumValue:val]) {
  2120. [(GPBEnumArray*)genericArray addRawValue:val];
  2121. } else {
  2122. GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
  2123. [unknownFields mergeVarintField:GPBFieldNumber(field) value:val];
  2124. }
  2125. break;
  2126. }
  2127. } // switch
  2128. }
  2129. - (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input
  2130. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
  2131. GPBDescriptor *descriptor = [self descriptor];
  2132. GPBFileSyntax syntax = descriptor.file.syntax;
  2133. GPBCodedInputStreamState *state = &input->state_;
  2134. uint32_t tag = 0;
  2135. NSUInteger startingIndex = 0;
  2136. NSArray *fields = descriptor->fields_;
  2137. NSUInteger numFields = fields.count;
  2138. while (YES) {
  2139. BOOL merged = NO;
  2140. tag = GPBCodedInputStreamReadTag(state);
  2141. if (tag == 0) {
  2142. break; // Reached end.
  2143. }
  2144. for (NSUInteger i = 0; i < numFields; ++i) {
  2145. if (startingIndex >= numFields) startingIndex = 0;
  2146. GPBFieldDescriptor *fieldDescriptor = fields[startingIndex];
  2147. if (GPBFieldTag(fieldDescriptor) == tag) {
  2148. GPBFieldType fieldType = fieldDescriptor.fieldType;
  2149. if (fieldType == GPBFieldTypeSingle) {
  2150. MergeSingleFieldFromCodedInputStream(self, fieldDescriptor, syntax,
  2151. input, extensionRegistry);
  2152. // Well formed protos will only have a single field once, advance
  2153. // the starting index to the next field.
  2154. startingIndex += 1;
  2155. } else if (fieldType == GPBFieldTypeRepeated) {
  2156. if (fieldDescriptor.isPackable) {
  2157. MergeRepeatedPackedFieldFromCodedInputStream(
  2158. self, fieldDescriptor, syntax, input);
  2159. // Well formed protos will only have a repeated field that is
  2160. // packed once, advance the starting index to the next field.
  2161. startingIndex += 1;
  2162. } else {
  2163. MergeRepeatedNotPackedFieldFromCodedInputStream(
  2164. self, fieldDescriptor, syntax, input, extensionRegistry);
  2165. }
  2166. } else { // fieldType == GPBFieldTypeMap
  2167. // GPB*Dictionary or NSDictionary, exact type doesn't matter at this
  2168. // point.
  2169. id map = GetOrCreateMapIvarWithField(self, fieldDescriptor, syntax);
  2170. [input readMapEntry:map
  2171. extensionRegistry:extensionRegistry
  2172. field:fieldDescriptor
  2173. parentMessage:self];
  2174. }
  2175. merged = YES;
  2176. break;
  2177. } else {
  2178. startingIndex += 1;
  2179. }
  2180. } // for(i < numFields)
  2181. if (!merged && (tag != 0)) {
  2182. // Primitive, repeated types can be packed on unpacked on the wire, and
  2183. // are parsed either way. The above loop covered tag in the preferred
  2184. // for, so this need to check the alternate form.
  2185. for (NSUInteger i = 0; i < numFields; ++i) {
  2186. if (startingIndex >= numFields) startingIndex = 0;
  2187. GPBFieldDescriptor *fieldDescriptor = fields[startingIndex];
  2188. if ((fieldDescriptor.fieldType == GPBFieldTypeRepeated) &&
  2189. !GPBFieldDataTypeIsObject(fieldDescriptor) &&
  2190. (GPBFieldAlternateTag(fieldDescriptor) == tag)) {
  2191. BOOL alternateIsPacked = !fieldDescriptor.isPackable;
  2192. if (alternateIsPacked) {
  2193. MergeRepeatedPackedFieldFromCodedInputStream(
  2194. self, fieldDescriptor, syntax, input);
  2195. // Well formed protos will only have a repeated field that is
  2196. // packed once, advance the starting index to the next field.
  2197. startingIndex += 1;
  2198. } else {
  2199. MergeRepeatedNotPackedFieldFromCodedInputStream(
  2200. self, fieldDescriptor, syntax, input, extensionRegistry);
  2201. }
  2202. merged = YES;
  2203. break;
  2204. } else {
  2205. startingIndex += 1;
  2206. }
  2207. }
  2208. }
  2209. if (!merged) {
  2210. if (tag == 0) {
  2211. // zero signals EOF / limit reached
  2212. return;
  2213. } else {
  2214. if (![self parseUnknownField:input
  2215. extensionRegistry:extensionRegistry
  2216. tag:tag]) {
  2217. // it's an endgroup tag
  2218. return;
  2219. }
  2220. }
  2221. } // if(!merged)
  2222. } // while(YES)
  2223. }
  2224. #pragma mark - MergeFrom Support
  2225. - (void)mergeFrom:(GPBMessage *)other {
  2226. Class selfClass = [self class];
  2227. Class otherClass = [other class];
  2228. if (!([selfClass isSubclassOfClass:otherClass] ||
  2229. [otherClass isSubclassOfClass:selfClass])) {
  2230. [NSException raise:NSInvalidArgumentException
  2231. format:@"Classes must match %@ != %@", selfClass, otherClass];
  2232. }
  2233. // We assume something will be done and become visible.
  2234. GPBBecomeVisibleToAutocreator(self);
  2235. GPBDescriptor *descriptor = [[self class] descriptor];
  2236. GPBFileSyntax syntax = descriptor.file.syntax;
  2237. for (GPBFieldDescriptor *field in descriptor->fields_) {
  2238. GPBFieldType fieldType = field.fieldType;
  2239. if (fieldType == GPBFieldTypeSingle) {
  2240. int32_t hasIndex = GPBFieldHasIndex(field);
  2241. uint32_t fieldNumber = GPBFieldNumber(field);
  2242. if (!GPBGetHasIvar(other, hasIndex, fieldNumber)) {
  2243. // Other doesn't have the field set, on to the next.
  2244. continue;
  2245. }
  2246. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2247. switch (fieldDataType) {
  2248. case GPBDataTypeBool:
  2249. GPBSetBoolIvarWithFieldInternal(
  2250. self, field, GPBGetMessageBoolField(other, field), syntax);
  2251. break;
  2252. case GPBDataTypeSFixed32:
  2253. case GPBDataTypeEnum:
  2254. case GPBDataTypeInt32:
  2255. case GPBDataTypeSInt32:
  2256. GPBSetInt32IvarWithFieldInternal(
  2257. self, field, GPBGetMessageInt32Field(other, field), syntax);
  2258. break;
  2259. case GPBDataTypeFixed32:
  2260. case GPBDataTypeUInt32:
  2261. GPBSetUInt32IvarWithFieldInternal(
  2262. self, field, GPBGetMessageUInt32Field(other, field), syntax);
  2263. break;
  2264. case GPBDataTypeSFixed64:
  2265. case GPBDataTypeInt64:
  2266. case GPBDataTypeSInt64:
  2267. GPBSetInt64IvarWithFieldInternal(
  2268. self, field, GPBGetMessageInt64Field(other, field), syntax);
  2269. break;
  2270. case GPBDataTypeFixed64:
  2271. case GPBDataTypeUInt64:
  2272. GPBSetUInt64IvarWithFieldInternal(
  2273. self, field, GPBGetMessageUInt64Field(other, field), syntax);
  2274. break;
  2275. case GPBDataTypeFloat:
  2276. GPBSetFloatIvarWithFieldInternal(
  2277. self, field, GPBGetMessageFloatField(other, field), syntax);
  2278. break;
  2279. case GPBDataTypeDouble:
  2280. GPBSetDoubleIvarWithFieldInternal(
  2281. self, field, GPBGetMessageDoubleField(other, field), syntax);
  2282. break;
  2283. case GPBDataTypeBytes:
  2284. case GPBDataTypeString: {
  2285. id otherVal = GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2286. GPBSetObjectIvarWithFieldInternal(self, field, otherVal, syntax);
  2287. break;
  2288. }
  2289. case GPBDataTypeMessage:
  2290. case GPBDataTypeGroup: {
  2291. id otherVal = GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2292. if (GPBGetHasIvar(self, hasIndex, fieldNumber)) {
  2293. GPBMessage *message =
  2294. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  2295. [message mergeFrom:otherVal];
  2296. } else {
  2297. GPBMessage *message = [otherVal copy];
  2298. GPBSetRetainedObjectIvarWithFieldInternal(self, field, message,
  2299. syntax);
  2300. }
  2301. break;
  2302. }
  2303. } // switch()
  2304. } else if (fieldType == GPBFieldTypeRepeated) {
  2305. // In the case of a list, they need to be appended, and there is no
  2306. // _hasIvar to worry about setting.
  2307. id otherArray =
  2308. GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2309. if (otherArray) {
  2310. GPBDataType fieldDataType = field->description_->dataType;
  2311. if (GPBDataTypeIsObject(fieldDataType)) {
  2312. NSMutableArray *resultArray =
  2313. GetOrCreateArrayIvarWithField(self, field, syntax);
  2314. [resultArray addObjectsFromArray:otherArray];
  2315. } else if (fieldDataType == GPBDataTypeEnum) {
  2316. GPBEnumArray *resultArray =
  2317. GetOrCreateArrayIvarWithField(self, field, syntax);
  2318. [resultArray addRawValuesFromArray:otherArray];
  2319. } else {
  2320. // The array type doesn't matter, that all implment
  2321. // -addValuesFromArray:.
  2322. GPBInt32Array *resultArray =
  2323. GetOrCreateArrayIvarWithField(self, field, syntax);
  2324. [resultArray addValuesFromArray:otherArray];
  2325. }
  2326. }
  2327. } else { // fieldType = GPBFieldTypeMap
  2328. // In the case of a map, they need to be merged, and there is no
  2329. // _hasIvar to worry about setting.
  2330. id otherDict = GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2331. if (otherDict) {
  2332. GPBDataType keyDataType = field.mapKeyDataType;
  2333. GPBDataType valueDataType = field->description_->dataType;
  2334. if (GPBDataTypeIsObject(keyDataType) &&
  2335. GPBDataTypeIsObject(valueDataType)) {
  2336. NSMutableDictionary *resultDict =
  2337. GetOrCreateMapIvarWithField(self, field, syntax);
  2338. [resultDict addEntriesFromDictionary:otherDict];
  2339. } else if (valueDataType == GPBDataTypeEnum) {
  2340. // The exact type doesn't matter, just need to know it is a
  2341. // GPB*EnumDictionary.
  2342. GPBInt32EnumDictionary *resultDict =
  2343. GetOrCreateMapIvarWithField(self, field, syntax);
  2344. [resultDict addRawEntriesFromDictionary:otherDict];
  2345. } else {
  2346. // The exact type doesn't matter, they all implement
  2347. // -addEntriesFromDictionary:.
  2348. GPBInt32Int32Dictionary *resultDict =
  2349. GetOrCreateMapIvarWithField(self, field, syntax);
  2350. [resultDict addEntriesFromDictionary:otherDict];
  2351. }
  2352. }
  2353. } // if (fieldType)..else if...else
  2354. } // for(fields)
  2355. // Unknown fields.
  2356. if (!unknownFields_) {
  2357. [self setUnknownFields:other.unknownFields];
  2358. } else {
  2359. [unknownFields_ mergeUnknownFields:other.unknownFields];
  2360. }
  2361. // Extensions
  2362. if (other->extensionMap_.count == 0) {
  2363. return;
  2364. }
  2365. if (extensionMap_ == nil) {
  2366. extensionMap_ =
  2367. CloneExtensionMap(other->extensionMap_, NSZoneFromPointer(self));
  2368. } else {
  2369. for (GPBExtensionDescriptor *extension in other->extensionMap_) {
  2370. id otherValue = [other->extensionMap_ objectForKey:extension];
  2371. id value = [extensionMap_ objectForKey:extension];
  2372. BOOL isMessageExtension = GPBExtensionIsMessage(extension);
  2373. if (extension.repeated) {
  2374. NSMutableArray *list = value;
  2375. if (list == nil) {
  2376. list = [[NSMutableArray alloc] init];
  2377. [extensionMap_ setObject:list forKey:extension];
  2378. [list release];
  2379. }
  2380. if (isMessageExtension) {
  2381. for (GPBMessage *otherListValue in otherValue) {
  2382. GPBMessage *copiedValue = [otherListValue copy];
  2383. [list addObject:copiedValue];
  2384. [copiedValue release];
  2385. }
  2386. } else {
  2387. [list addObjectsFromArray:otherValue];
  2388. }
  2389. } else {
  2390. if (isMessageExtension) {
  2391. if (value) {
  2392. [(GPBMessage *)value mergeFrom:(GPBMessage *)otherValue];
  2393. } else {
  2394. GPBMessage *copiedValue = [otherValue copy];
  2395. [extensionMap_ setObject:copiedValue forKey:extension];
  2396. [copiedValue release];
  2397. }
  2398. } else {
  2399. [extensionMap_ setObject:otherValue forKey:extension];
  2400. }
  2401. }
  2402. if (isMessageExtension && !extension.isRepeated) {
  2403. GPBMessage *autocreatedValue =
  2404. [[autocreatedExtensionMap_ objectForKey:extension] retain];
  2405. // Must remove from the map before calling GPBClearMessageAutocreator()
  2406. // so that GPBClearMessageAutocreator() knows its safe to clear.
  2407. [autocreatedExtensionMap_ removeObjectForKey:extension];
  2408. GPBClearMessageAutocreator(autocreatedValue);
  2409. [autocreatedValue release];
  2410. }
  2411. }
  2412. }
  2413. }
  2414. #pragma mark - isEqual: & hash Support
  2415. - (BOOL)isEqual:(id)other {
  2416. if (other == self) {
  2417. return YES;
  2418. }
  2419. if (![other isKindOfClass:[GPBMessage class]]) {
  2420. return NO;
  2421. }
  2422. GPBMessage *otherMsg = other;
  2423. GPBDescriptor *descriptor = [[self class] descriptor];
  2424. if ([[otherMsg class] descriptor] != descriptor) {
  2425. return NO;
  2426. }
  2427. uint8_t *selfStorage = (uint8_t *)messageStorage_;
  2428. uint8_t *otherStorage = (uint8_t *)otherMsg->messageStorage_;
  2429. for (GPBFieldDescriptor *field in descriptor->fields_) {
  2430. if (GPBFieldIsMapOrArray(field)) {
  2431. // In the case of a list or map, there is no _hasIvar to worry about.
  2432. // NOTE: These are NSArray/GPB*Array or NSDictionary/GPB*Dictionary, but
  2433. // the type doesn't really matter as the objects all support -count and
  2434. // -isEqual:.
  2435. NSArray *resultMapOrArray =
  2436. GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  2437. NSArray *otherMapOrArray =
  2438. GPBGetObjectIvarWithFieldNoAutocreate(other, field);
  2439. // nil and empty are equal
  2440. if (resultMapOrArray.count != 0 || otherMapOrArray.count != 0) {
  2441. if (![resultMapOrArray isEqual:otherMapOrArray]) {
  2442. return NO;
  2443. }
  2444. }
  2445. } else { // Single field
  2446. int32_t hasIndex = GPBFieldHasIndex(field);
  2447. uint32_t fieldNum = GPBFieldNumber(field);
  2448. BOOL selfHas = GPBGetHasIvar(self, hasIndex, fieldNum);
  2449. BOOL otherHas = GPBGetHasIvar(other, hasIndex, fieldNum);
  2450. if (selfHas != otherHas) {
  2451. return NO; // Differing has values, not equal.
  2452. }
  2453. if (!selfHas) {
  2454. // Same has values, was no, nothing else to check for this field.
  2455. continue;
  2456. }
  2457. // Now compare the values.
  2458. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2459. size_t fieldOffset = field->description_->offset;
  2460. switch (fieldDataType) {
  2461. case GPBDataTypeBool: {
  2462. // Bools are stored in has_bits to avoid needing explicit space in
  2463. // the storage structure.
  2464. // (the field number passed to the HasIvar helper doesn't really
  2465. // matter since the offset is never negative)
  2466. BOOL selfValue = GPBGetHasIvar(self, (int32_t)(fieldOffset), 0);
  2467. BOOL otherValue = GPBGetHasIvar(other, (int32_t)(fieldOffset), 0);
  2468. if (selfValue != otherValue) {
  2469. return NO;
  2470. }
  2471. break;
  2472. }
  2473. case GPBDataTypeSFixed32:
  2474. case GPBDataTypeInt32:
  2475. case GPBDataTypeSInt32:
  2476. case GPBDataTypeEnum:
  2477. case GPBDataTypeFixed32:
  2478. case GPBDataTypeUInt32:
  2479. case GPBDataTypeFloat: {
  2480. GPBInternalCompileAssert(sizeof(float) == sizeof(uint32_t), float_not_32_bits);
  2481. // These are all 32bit, signed/unsigned doesn't matter for equality.
  2482. uint32_t *selfValPtr = (uint32_t *)&selfStorage[fieldOffset];
  2483. uint32_t *otherValPtr = (uint32_t *)&otherStorage[fieldOffset];
  2484. if (*selfValPtr != *otherValPtr) {
  2485. return NO;
  2486. }
  2487. break;
  2488. }
  2489. case GPBDataTypeSFixed64:
  2490. case GPBDataTypeInt64:
  2491. case GPBDataTypeSInt64:
  2492. case GPBDataTypeFixed64:
  2493. case GPBDataTypeUInt64:
  2494. case GPBDataTypeDouble: {
  2495. GPBInternalCompileAssert(sizeof(double) == sizeof(uint64_t), double_not_64_bits);
  2496. // These are all 64bit, signed/unsigned doesn't matter for equality.
  2497. uint64_t *selfValPtr = (uint64_t *)&selfStorage[fieldOffset];
  2498. uint64_t *otherValPtr = (uint64_t *)&otherStorage[fieldOffset];
  2499. if (*selfValPtr != *otherValPtr) {
  2500. return NO;
  2501. }
  2502. break;
  2503. }
  2504. case GPBDataTypeBytes:
  2505. case GPBDataTypeString:
  2506. case GPBDataTypeMessage:
  2507. case GPBDataTypeGroup: {
  2508. // Type doesn't matter here, they all implement -isEqual:.
  2509. id *selfValPtr = (id *)&selfStorage[fieldOffset];
  2510. id *otherValPtr = (id *)&otherStorage[fieldOffset];
  2511. if (![*selfValPtr isEqual:*otherValPtr]) {
  2512. return NO;
  2513. }
  2514. break;
  2515. }
  2516. } // switch()
  2517. } // if(mapOrArray)...else
  2518. } // for(fields)
  2519. // nil and empty are equal
  2520. if (extensionMap_.count != 0 || otherMsg->extensionMap_.count != 0) {
  2521. if (![extensionMap_ isEqual:otherMsg->extensionMap_]) {
  2522. return NO;
  2523. }
  2524. }
  2525. // nil and empty are equal
  2526. GPBUnknownFieldSet *otherUnknowns = otherMsg->unknownFields_;
  2527. if ([unknownFields_ countOfFields] != 0 ||
  2528. [otherUnknowns countOfFields] != 0) {
  2529. if (![unknownFields_ isEqual:otherUnknowns]) {
  2530. return NO;
  2531. }
  2532. }
  2533. return YES;
  2534. }
  2535. // It is very difficult to implement a generic hash for ProtoBuf messages that
  2536. // will perform well. If you need hashing on your ProtoBufs (eg you are using
  2537. // them as dictionary keys) you will probably want to implement a ProtoBuf
  2538. // message specific hash as a category on your protobuf class. Do not make it a
  2539. // category on GPBMessage as you will conflict with this hash, and will possibly
  2540. // override hash for all generated protobufs. A good implementation of hash will
  2541. // be really fast, so we would recommend only hashing protobufs that have an
  2542. // identifier field of some kind that you can easily hash. If you implement
  2543. // hash, we would strongly recommend overriding isEqual: in your category as
  2544. // well, as the default implementation of isEqual: is extremely slow, and may
  2545. // drastically affect performance in large sets.
  2546. - (NSUInteger)hash {
  2547. GPBDescriptor *descriptor = [[self class] descriptor];
  2548. const NSUInteger prime = 19;
  2549. uint8_t *storage = (uint8_t *)messageStorage_;
  2550. // Start with the descriptor and then mix it with some instance info.
  2551. // Hopefully that will give a spread based on classes and what fields are set.
  2552. NSUInteger result = (NSUInteger)descriptor;
  2553. for (GPBFieldDescriptor *field in descriptor->fields_) {
  2554. if (GPBFieldIsMapOrArray(field)) {
  2555. // Exact type doesn't matter, just check if there are any elements.
  2556. NSArray *mapOrArray = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  2557. NSUInteger count = mapOrArray.count;
  2558. if (count) {
  2559. // NSArray/NSDictionary use count, use the field number and the count.
  2560. result = prime * result + GPBFieldNumber(field);
  2561. result = prime * result + count;
  2562. }
  2563. } else if (GPBGetHasIvarField(self, field)) {
  2564. // Just using the field number seemed simple/fast, but then a small
  2565. // message class where all the same fields are always set (to different
  2566. // things would end up all with the same hash, so pull in some data).
  2567. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2568. size_t fieldOffset = field->description_->offset;
  2569. switch (fieldDataType) {
  2570. case GPBDataTypeBool: {
  2571. // Bools are stored in has_bits to avoid needing explicit space in
  2572. // the storage structure.
  2573. // (the field number passed to the HasIvar helper doesn't really
  2574. // matter since the offset is never negative)
  2575. BOOL value = GPBGetHasIvar(self, (int32_t)(fieldOffset), 0);
  2576. result = prime * result + value;
  2577. break;
  2578. }
  2579. case GPBDataTypeSFixed32:
  2580. case GPBDataTypeInt32:
  2581. case GPBDataTypeSInt32:
  2582. case GPBDataTypeEnum:
  2583. case GPBDataTypeFixed32:
  2584. case GPBDataTypeUInt32:
  2585. case GPBDataTypeFloat: {
  2586. GPBInternalCompileAssert(sizeof(float) == sizeof(uint32_t), float_not_32_bits);
  2587. // These are all 32bit, just mix it in.
  2588. uint32_t *valPtr = (uint32_t *)&storage[fieldOffset];
  2589. result = prime * result + *valPtr;
  2590. break;
  2591. }
  2592. case GPBDataTypeSFixed64:
  2593. case GPBDataTypeInt64:
  2594. case GPBDataTypeSInt64:
  2595. case GPBDataTypeFixed64:
  2596. case GPBDataTypeUInt64:
  2597. case GPBDataTypeDouble: {
  2598. GPBInternalCompileAssert(sizeof(double) == sizeof(uint64_t), double_not_64_bits);
  2599. // These are all 64bit, just mix what fits into an NSUInteger in.
  2600. uint64_t *valPtr = (uint64_t *)&storage[fieldOffset];
  2601. result = prime * result + (NSUInteger)(*valPtr);
  2602. break;
  2603. }
  2604. case GPBDataTypeBytes:
  2605. case GPBDataTypeString: {
  2606. // Type doesn't matter here, they both implement -hash:.
  2607. id *valPtr = (id *)&storage[fieldOffset];
  2608. result = prime * result + [*valPtr hash];
  2609. break;
  2610. }
  2611. case GPBDataTypeMessage:
  2612. case GPBDataTypeGroup: {
  2613. GPBMessage **valPtr = (GPBMessage **)&storage[fieldOffset];
  2614. // Could call -hash on the sub message, but that could recurse pretty
  2615. // deep; follow the lead of NSArray/NSDictionary and don't really
  2616. // recurse for hash, instead use the field number and the descriptor
  2617. // of the sub message. Yes, this could suck for a bunch of messages
  2618. // where they all only differ in the sub messages, but if you are
  2619. // using a message with sub messages for something that needs -hash,
  2620. // odds are you are also copying them as keys, and that deep copy
  2621. // will also suck.
  2622. result = prime * result + GPBFieldNumber(field);
  2623. result = prime * result + (NSUInteger)[[*valPtr class] descriptor];
  2624. break;
  2625. }
  2626. } // switch()
  2627. }
  2628. }
  2629. // Unknowns and extensions are not included.
  2630. return result;
  2631. }
  2632. #pragma mark - Description Support
  2633. - (NSString *)description {
  2634. NSString *textFormat = GPBTextFormatForMessage(self, @" ");
  2635. NSString *description = [NSString
  2636. stringWithFormat:@"<%@ %p>: {\n%@}", [self class], self, textFormat];
  2637. return description;
  2638. }
  2639. #if defined(DEBUG) && DEBUG
  2640. // Xcode 5.1 added support for custom quick look info.
  2641. // 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
  2642. - (id)debugQuickLookObject {
  2643. return GPBTextFormatForMessage(self, nil);
  2644. }
  2645. #endif // DEBUG
  2646. #pragma mark - SerializedSize
  2647. - (size_t)serializedSize {
  2648. GPBDescriptor *descriptor = [[self class] descriptor];
  2649. size_t result = 0;
  2650. // Has check is done explicitly, so GPBGetObjectIvarWithFieldNoAutocreate()
  2651. // avoids doing the has check again.
  2652. // Fields.
  2653. for (GPBFieldDescriptor *fieldDescriptor in descriptor->fields_) {
  2654. GPBFieldType fieldType = fieldDescriptor.fieldType;
  2655. GPBDataType fieldDataType = GPBGetFieldDataType(fieldDescriptor);
  2656. // Single Fields
  2657. if (fieldType == GPBFieldTypeSingle) {
  2658. BOOL selfHas = GPBGetHasIvarField(self, fieldDescriptor);
  2659. if (!selfHas) {
  2660. continue; // Nothing to do.
  2661. }
  2662. uint32_t fieldNumber = GPBFieldNumber(fieldDescriptor);
  2663. switch (fieldDataType) {
  2664. #define CASE_SINGLE_POD(NAME, TYPE, FUNC_TYPE) \
  2665. case GPBDataType##NAME: { \
  2666. TYPE fieldVal = GPBGetMessage##FUNC_TYPE##Field(self, fieldDescriptor); \
  2667. result += GPBCompute##NAME##Size(fieldNumber, fieldVal); \
  2668. break; \
  2669. }
  2670. #define CASE_SINGLE_OBJECT(NAME) \
  2671. case GPBDataType##NAME: { \
  2672. id fieldVal = GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor); \
  2673. result += GPBCompute##NAME##Size(fieldNumber, fieldVal); \
  2674. break; \
  2675. }
  2676. CASE_SINGLE_POD(Bool, BOOL, Bool)
  2677. CASE_SINGLE_POD(Fixed32, uint32_t, UInt32)
  2678. CASE_SINGLE_POD(SFixed32, int32_t, Int32)
  2679. CASE_SINGLE_POD(Float, float, Float)
  2680. CASE_SINGLE_POD(Fixed64, uint64_t, UInt64)
  2681. CASE_SINGLE_POD(SFixed64, int64_t, Int64)
  2682. CASE_SINGLE_POD(Double, double, Double)
  2683. CASE_SINGLE_POD(Int32, int32_t, Int32)
  2684. CASE_SINGLE_POD(Int64, int64_t, Int64)
  2685. CASE_SINGLE_POD(SInt32, int32_t, Int32)
  2686. CASE_SINGLE_POD(SInt64, int64_t, Int64)
  2687. CASE_SINGLE_POD(UInt32, uint32_t, UInt32)
  2688. CASE_SINGLE_POD(UInt64, uint64_t, UInt64)
  2689. CASE_SINGLE_OBJECT(Bytes)
  2690. CASE_SINGLE_OBJECT(String)
  2691. CASE_SINGLE_OBJECT(Message)
  2692. CASE_SINGLE_OBJECT(Group)
  2693. CASE_SINGLE_POD(Enum, int32_t, Int32)
  2694. #undef CASE_SINGLE_POD
  2695. #undef CASE_SINGLE_OBJECT
  2696. }
  2697. // Repeated Fields
  2698. } else if (fieldType == GPBFieldTypeRepeated) {
  2699. id genericArray =
  2700. GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor);
  2701. NSUInteger count = [genericArray count];
  2702. if (count == 0) {
  2703. continue; // Nothing to add.
  2704. }
  2705. __block size_t dataSize = 0;
  2706. switch (fieldDataType) {
  2707. #define CASE_REPEATED_POD(NAME, TYPE, ARRAY_TYPE) \
  2708. CASE_REPEATED_POD_EXTRA(NAME, TYPE, ARRAY_TYPE, )
  2709. #define CASE_REPEATED_POD_EXTRA(NAME, TYPE, ARRAY_TYPE, ARRAY_ACCESSOR_NAME) \
  2710. case GPBDataType##NAME: { \
  2711. GPB##ARRAY_TYPE##Array *array = genericArray; \
  2712. [array enumerate##ARRAY_ACCESSOR_NAME##ValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { \
  2713. _Pragma("unused(idx, stop)"); \
  2714. dataSize += GPBCompute##NAME##SizeNoTag(value); \
  2715. }]; \
  2716. break; \
  2717. }
  2718. #define CASE_REPEATED_OBJECT(NAME) \
  2719. case GPBDataType##NAME: { \
  2720. for (id value in genericArray) { \
  2721. dataSize += GPBCompute##NAME##SizeNoTag(value); \
  2722. } \
  2723. break; \
  2724. }
  2725. CASE_REPEATED_POD(Bool, BOOL, Bool)
  2726. CASE_REPEATED_POD(Fixed32, uint32_t, UInt32)
  2727. CASE_REPEATED_POD(SFixed32, int32_t, Int32)
  2728. CASE_REPEATED_POD(Float, float, Float)
  2729. CASE_REPEATED_POD(Fixed64, uint64_t, UInt64)
  2730. CASE_REPEATED_POD(SFixed64, int64_t, Int64)
  2731. CASE_REPEATED_POD(Double, double, Double)
  2732. CASE_REPEATED_POD(Int32, int32_t, Int32)
  2733. CASE_REPEATED_POD(Int64, int64_t, Int64)
  2734. CASE_REPEATED_POD(SInt32, int32_t, Int32)
  2735. CASE_REPEATED_POD(SInt64, int64_t, Int64)
  2736. CASE_REPEATED_POD(UInt32, uint32_t, UInt32)
  2737. CASE_REPEATED_POD(UInt64, uint64_t, UInt64)
  2738. CASE_REPEATED_OBJECT(Bytes)
  2739. CASE_REPEATED_OBJECT(String)
  2740. CASE_REPEATED_OBJECT(Message)
  2741. CASE_REPEATED_OBJECT(Group)
  2742. CASE_REPEATED_POD_EXTRA(Enum, int32_t, Enum, Raw)
  2743. #undef CASE_REPEATED_POD
  2744. #undef CASE_REPEATED_POD_EXTRA
  2745. #undef CASE_REPEATED_OBJECT
  2746. } // switch
  2747. result += dataSize;
  2748. size_t tagSize = GPBComputeTagSize(GPBFieldNumber(fieldDescriptor));
  2749. if (fieldDataType == GPBDataTypeGroup) {
  2750. // Groups have both a start and an end tag.
  2751. tagSize *= 2;
  2752. }
  2753. if (fieldDescriptor.isPackable) {
  2754. result += tagSize;
  2755. result += GPBComputeSizeTSizeAsInt32NoTag(dataSize);
  2756. } else {
  2757. result += count * tagSize;
  2758. }
  2759. // Map<> Fields
  2760. } else { // fieldType == GPBFieldTypeMap
  2761. if (GPBDataTypeIsObject(fieldDataType) &&
  2762. (fieldDescriptor.mapKeyDataType == GPBDataTypeString)) {
  2763. // If key type was string, then the map is an NSDictionary.
  2764. NSDictionary *map =
  2765. GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor);
  2766. if (map) {
  2767. result += GPBDictionaryComputeSizeInternalHelper(map, fieldDescriptor);
  2768. }
  2769. } else {
  2770. // Type will be GPB*GroupDictionary, exact type doesn't matter.
  2771. GPBInt32Int32Dictionary *map =
  2772. GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor);
  2773. result += [map computeSerializedSizeAsField:fieldDescriptor];
  2774. }
  2775. }
  2776. } // for(fields)
  2777. // Add any unknown fields.
  2778. if (descriptor.wireFormat) {
  2779. result += [unknownFields_ serializedSizeAsMessageSet];
  2780. } else {
  2781. result += [unknownFields_ serializedSize];
  2782. }
  2783. // Add any extensions.
  2784. for (GPBExtensionDescriptor *extension in extensionMap_) {
  2785. id value = [extensionMap_ objectForKey:extension];
  2786. result += GPBComputeExtensionSerializedSizeIncludingTag(extension, value);
  2787. }
  2788. return result;
  2789. }
  2790. #pragma mark - Resolve Methods Support
  2791. typedef struct ResolveIvarAccessorMethodResult {
  2792. IMP impToAdd;
  2793. SEL encodingSelector;
  2794. } ResolveIvarAccessorMethodResult;
  2795. // |field| can be __unsafe_unretained because they are created at startup
  2796. // and are essentially global. No need to pay for retain/release when
  2797. // they are captured in blocks.
  2798. static void ResolveIvarGet(__unsafe_unretained GPBFieldDescriptor *field,
  2799. ResolveIvarAccessorMethodResult *result) {
  2800. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2801. switch (fieldDataType) {
  2802. #define CASE_GET(NAME, TYPE, TRUE_NAME) \
  2803. case GPBDataType##NAME: { \
  2804. result->impToAdd = imp_implementationWithBlock(^(id obj) { \
  2805. return GPBGetMessage##TRUE_NAME##Field(obj, field); \
  2806. }); \
  2807. result->encodingSelector = @selector(get##NAME); \
  2808. break; \
  2809. }
  2810. #define CASE_GET_OBJECT(NAME, TYPE, TRUE_NAME) \
  2811. case GPBDataType##NAME: { \
  2812. result->impToAdd = imp_implementationWithBlock(^(id obj) { \
  2813. return GPBGetObjectIvarWithField(obj, field); \
  2814. }); \
  2815. result->encodingSelector = @selector(get##NAME); \
  2816. break; \
  2817. }
  2818. CASE_GET(Bool, BOOL, Bool)
  2819. CASE_GET(Fixed32, uint32_t, UInt32)
  2820. CASE_GET(SFixed32, int32_t, Int32)
  2821. CASE_GET(Float, float, Float)
  2822. CASE_GET(Fixed64, uint64_t, UInt64)
  2823. CASE_GET(SFixed64, int64_t, Int64)
  2824. CASE_GET(Double, double, Double)
  2825. CASE_GET(Int32, int32_t, Int32)
  2826. CASE_GET(Int64, int64_t, Int64)
  2827. CASE_GET(SInt32, int32_t, Int32)
  2828. CASE_GET(SInt64, int64_t, Int64)
  2829. CASE_GET(UInt32, uint32_t, UInt32)
  2830. CASE_GET(UInt64, uint64_t, UInt64)
  2831. CASE_GET_OBJECT(Bytes, id, Object)
  2832. CASE_GET_OBJECT(String, id, Object)
  2833. CASE_GET_OBJECT(Message, id, Object)
  2834. CASE_GET_OBJECT(Group, id, Object)
  2835. CASE_GET(Enum, int32_t, Enum)
  2836. #undef CASE_GET
  2837. }
  2838. }
  2839. // See comment about __unsafe_unretained on ResolveIvarGet.
  2840. static void ResolveIvarSet(__unsafe_unretained GPBFieldDescriptor *field,
  2841. GPBFileSyntax syntax,
  2842. ResolveIvarAccessorMethodResult *result) {
  2843. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  2844. switch (fieldDataType) {
  2845. #define CASE_SET(NAME, TYPE, TRUE_NAME) \
  2846. case GPBDataType##NAME: { \
  2847. result->impToAdd = imp_implementationWithBlock(^(id obj, TYPE value) { \
  2848. return GPBSet##TRUE_NAME##IvarWithFieldInternal(obj, field, value, syntax); \
  2849. }); \
  2850. result->encodingSelector = @selector(set##NAME:); \
  2851. break; \
  2852. }
  2853. #define CASE_SET_COPY(NAME) \
  2854. case GPBDataType##NAME: { \
  2855. result->impToAdd = imp_implementationWithBlock(^(id obj, id value) { \
  2856. return GPBSetRetainedObjectIvarWithFieldInternal(obj, field, [value copy], syntax); \
  2857. }); \
  2858. result->encodingSelector = @selector(set##NAME:); \
  2859. break; \
  2860. }
  2861. CASE_SET(Bool, BOOL, Bool)
  2862. CASE_SET(Fixed32, uint32_t, UInt32)
  2863. CASE_SET(SFixed32, int32_t, Int32)
  2864. CASE_SET(Float, float, Float)
  2865. CASE_SET(Fixed64, uint64_t, UInt64)
  2866. CASE_SET(SFixed64, int64_t, Int64)
  2867. CASE_SET(Double, double, Double)
  2868. CASE_SET(Int32, int32_t, Int32)
  2869. CASE_SET(Int64, int64_t, Int64)
  2870. CASE_SET(SInt32, int32_t, Int32)
  2871. CASE_SET(SInt64, int64_t, Int64)
  2872. CASE_SET(UInt32, uint32_t, UInt32)
  2873. CASE_SET(UInt64, uint64_t, UInt64)
  2874. CASE_SET_COPY(Bytes)
  2875. CASE_SET_COPY(String)
  2876. CASE_SET(Message, id, Object)
  2877. CASE_SET(Group, id, Object)
  2878. CASE_SET(Enum, int32_t, Enum)
  2879. #undef CASE_SET
  2880. }
  2881. }
  2882. + (BOOL)resolveInstanceMethod:(SEL)sel {
  2883. const GPBDescriptor *descriptor = [self descriptor];
  2884. if (!descriptor) {
  2885. return [super resolveInstanceMethod:sel];
  2886. }
  2887. // NOTE: hasOrCountSel_/setHasSel_ will be NULL if the field for the given
  2888. // message should not have has support (done in GPBDescriptor.m), so there is
  2889. // no need for checks here to see if has*/setHas* are allowed.
  2890. ResolveIvarAccessorMethodResult result = {NULL, NULL};
  2891. // See comment about __unsafe_unretained on ResolveIvarGet.
  2892. for (__unsafe_unretained GPBFieldDescriptor *field in descriptor->fields_) {
  2893. BOOL isMapOrArray = GPBFieldIsMapOrArray(field);
  2894. if (!isMapOrArray) {
  2895. // Single fields.
  2896. if (sel == field->getSel_) {
  2897. ResolveIvarGet(field, &result);
  2898. break;
  2899. } else if (sel == field->setSel_) {
  2900. ResolveIvarSet(field, descriptor.file.syntax, &result);
  2901. break;
  2902. } else if (sel == field->hasOrCountSel_) {
  2903. int32_t index = GPBFieldHasIndex(field);
  2904. uint32_t fieldNum = GPBFieldNumber(field);
  2905. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  2906. return GPBGetHasIvar(obj, index, fieldNum);
  2907. });
  2908. result.encodingSelector = @selector(getBool);
  2909. break;
  2910. } else if (sel == field->setHasSel_) {
  2911. result.impToAdd = imp_implementationWithBlock(^(id obj, BOOL value) {
  2912. if (value) {
  2913. [NSException raise:NSInvalidArgumentException
  2914. format:@"%@: %@ can only be set to NO (to clear field).",
  2915. [obj class],
  2916. NSStringFromSelector(field->setHasSel_)];
  2917. }
  2918. GPBClearMessageField(obj, field);
  2919. });
  2920. result.encodingSelector = @selector(setBool:);
  2921. break;
  2922. } else {
  2923. GPBOneofDescriptor *oneof = field->containingOneof_;
  2924. if (oneof && (sel == oneof->caseSel_)) {
  2925. int32_t index = GPBFieldHasIndex(field);
  2926. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  2927. return GPBGetHasOneof(obj, index);
  2928. });
  2929. result.encodingSelector = @selector(getEnum);
  2930. break;
  2931. }
  2932. }
  2933. } else {
  2934. // map<>/repeated fields.
  2935. if (sel == field->getSel_) {
  2936. if (field.fieldType == GPBFieldTypeRepeated) {
  2937. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  2938. return GetArrayIvarWithField(obj, field);
  2939. });
  2940. } else {
  2941. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  2942. return GetMapIvarWithField(obj, field);
  2943. });
  2944. }
  2945. result.encodingSelector = @selector(getArray);
  2946. break;
  2947. } else if (sel == field->setSel_) {
  2948. // Local for syntax so the block can directly capture it and not the
  2949. // full lookup.
  2950. const GPBFileSyntax syntax = descriptor.file.syntax;
  2951. result.impToAdd = imp_implementationWithBlock(^(id obj, id value) {
  2952. GPBSetObjectIvarWithFieldInternal(obj, field, value, syntax);
  2953. });
  2954. result.encodingSelector = @selector(setArray:);
  2955. break;
  2956. } else if (sel == field->hasOrCountSel_) {
  2957. result.impToAdd = imp_implementationWithBlock(^(id obj) {
  2958. // Type doesn't matter, all *Array and *Dictionary types support
  2959. // -count.
  2960. NSArray *arrayOrMap =
  2961. GPBGetObjectIvarWithFieldNoAutocreate(obj, field);
  2962. return [arrayOrMap count];
  2963. });
  2964. result.encodingSelector = @selector(getArrayCount);
  2965. break;
  2966. }
  2967. }
  2968. }
  2969. if (result.impToAdd) {
  2970. const char *encoding =
  2971. GPBMessageEncodingForSelector(result.encodingSelector, YES);
  2972. Class msgClass = descriptor.messageClass;
  2973. BOOL methodAdded = class_addMethod(msgClass, sel, result.impToAdd, encoding);
  2974. // class_addMethod() is documented as also failing if the method was already
  2975. // added; so we check if the method is already there and return success so
  2976. // the method dispatch will still happen. Why would it already be added?
  2977. // Two threads could cause the same method to be bound at the same time,
  2978. // but only one will actually bind it; the other still needs to return true
  2979. // so things will dispatch.
  2980. if (!methodAdded) {
  2981. methodAdded = GPBClassHasSel(msgClass, sel);
  2982. }
  2983. return methodAdded;
  2984. }
  2985. return [super resolveInstanceMethod:sel];
  2986. }
  2987. + (BOOL)resolveClassMethod:(SEL)sel {
  2988. // Extensions scoped to a Message and looked up via class methods.
  2989. if (GPBResolveExtensionClassMethod([self descriptor].messageClass, sel)) {
  2990. return YES;
  2991. }
  2992. return [super resolveClassMethod:sel];
  2993. }
  2994. #pragma mark - NSCoding Support
  2995. + (BOOL)supportsSecureCoding {
  2996. return YES;
  2997. }
  2998. - (instancetype)initWithCoder:(NSCoder *)aDecoder {
  2999. self = [self init];
  3000. if (self) {
  3001. NSData *data =
  3002. [aDecoder decodeObjectOfClass:[NSData class] forKey:kGPBDataCoderKey];
  3003. if (data.length) {
  3004. [self mergeFromData:data extensionRegistry:nil];
  3005. }
  3006. }
  3007. return self;
  3008. }
  3009. - (void)encodeWithCoder:(NSCoder *)aCoder {
  3010. NSData *data = [self data];
  3011. if (data.length) {
  3012. [aCoder encodeObject:data forKey:kGPBDataCoderKey];
  3013. }
  3014. }
  3015. #pragma mark - KVC Support
  3016. + (BOOL)accessInstanceVariablesDirectly {
  3017. // Make sure KVC doesn't use instance variables.
  3018. return NO;
  3019. }
  3020. @end
  3021. #pragma mark - Messages from GPBUtilities.h but defined here for access to helpers.
  3022. // Only exists for public api, no core code should use this.
  3023. id GPBGetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field) {
  3024. #if defined(DEBUG) && DEBUG
  3025. if (field.fieldType != GPBFieldTypeRepeated) {
  3026. [NSException raise:NSInvalidArgumentException
  3027. format:@"%@.%@ is not a repeated field.",
  3028. [self class], field.name];
  3029. }
  3030. #endif
  3031. GPBDescriptor *descriptor = [[self class] descriptor];
  3032. GPBFileSyntax syntax = descriptor.file.syntax;
  3033. return GetOrCreateArrayIvarWithField(self, field, syntax);
  3034. }
  3035. // Only exists for public api, no core code should use this.
  3036. id GPBGetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field) {
  3037. #if defined(DEBUG) && DEBUG
  3038. if (field.fieldType != GPBFieldTypeMap) {
  3039. [NSException raise:NSInvalidArgumentException
  3040. format:@"%@.%@ is not a map<> field.",
  3041. [self class], field.name];
  3042. }
  3043. #endif
  3044. GPBDescriptor *descriptor = [[self class] descriptor];
  3045. GPBFileSyntax syntax = descriptor.file.syntax;
  3046. return GetOrCreateMapIvarWithField(self, field, syntax);
  3047. }
  3048. id GPBGetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
  3049. NSCAssert(!GPBFieldIsMapOrArray(field), @"Shouldn't get here");
  3050. if (GPBGetHasIvarField(self, field)) {
  3051. uint8_t *storage = (uint8_t *)self->messageStorage_;
  3052. id *typePtr = (id *)&storage[field->description_->offset];
  3053. return *typePtr;
  3054. }
  3055. // Not set...
  3056. // Non messages (string/data), get their default.
  3057. if (!GPBFieldDataTypeIsMessage(field)) {
  3058. return field.defaultValue.valueMessage;
  3059. }
  3060. GPBPrepareReadOnlySemaphore(self);
  3061. dispatch_semaphore_wait(self->readOnlySemaphore_, DISPATCH_TIME_FOREVER);
  3062. GPBMessage *result = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  3063. if (!result) {
  3064. // For non repeated messages, create the object, set it and return it.
  3065. // This object will not initially be visible via GPBGetHasIvar, so
  3066. // we save its creator so it can become visible if it's mutated later.
  3067. result = GPBCreateMessageWithAutocreator(field.msgClass, self, field);
  3068. GPBSetAutocreatedRetainedObjectIvarWithField(self, field, result);
  3069. }
  3070. dispatch_semaphore_signal(self->readOnlySemaphore_);
  3071. return result;
  3072. }
  3073. #pragma clang diagnostic pop