Masterarbeit Richard Stern. Flutter App, sich mit einem Bluetooth-Gerät verbindet und Berührungen auf einem Sensor visualisiert.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GPBMessage.m 125KB

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