GPBMessage.m 122 KB

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