GPBMessage.m 120 KB

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