GPBMessage.m 123 KB

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