GPBMessage.m 126 KB

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