GPBMessage.m 118 KB

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