GPBMessage.m 132 KB

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