GPBUtilities.m 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234
  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 "GPBUtilities_PackagePrivate.h"
  31. #import <objc/runtime.h>
  32. #import "GPBArray_PackagePrivate.h"
  33. #import "GPBDescriptor_PackagePrivate.h"
  34. #import "GPBDictionary_PackagePrivate.h"
  35. #import "GPBMessage_PackagePrivate.h"
  36. #import "GPBUnknownField.h"
  37. #import "GPBUnknownFieldSet.h"
  38. // Direct access is use for speed, to avoid even internally declaring things
  39. // read/write, etc. The warning is enabled in the project to ensure code calling
  40. // protos can turn on -Wdirect-ivar-access without issues.
  41. #pragma clang diagnostic push
  42. #pragma clang diagnostic ignored "-Wdirect-ivar-access"
  43. static void AppendTextFormatForMessage(GPBMessage *message,
  44. NSMutableString *toStr,
  45. NSString *lineIndent);
  46. // Are two datatypes the same basic type representation (ex Int32 and SInt32).
  47. // Marked unused because currently only called from asserts/debug.
  48. static BOOL DataTypesEquivalent(GPBDataType type1,
  49. GPBDataType type2) __attribute__ ((unused));
  50. // Basic type representation for a type (ex: for SInt32 it is Int32).
  51. // Marked unused because currently only called from asserts/debug.
  52. static GPBDataType BaseDataType(GPBDataType type) __attribute__ ((unused));
  53. // String name for a data type.
  54. // Marked unused because currently only called from asserts/debug.
  55. static NSString *TypeToString(GPBDataType dataType) __attribute__ ((unused));
  56. NSData *GPBEmptyNSData(void) {
  57. static dispatch_once_t onceToken;
  58. static NSData *defaultNSData = nil;
  59. dispatch_once(&onceToken, ^{
  60. defaultNSData = [[NSData alloc] init];
  61. });
  62. return defaultNSData;
  63. }
  64. void GPBMessageDropUnknownFieldsRecursively(GPBMessage *initialMessage) {
  65. if (!initialMessage) {
  66. return;
  67. }
  68. // Use an array as a list to process to avoid recursion.
  69. NSMutableArray *todo = [NSMutableArray arrayWithObject:initialMessage];
  70. while (todo.count) {
  71. GPBMessage *msg = todo.lastObject;
  72. [todo removeLastObject];
  73. // Clear unknowns.
  74. msg.unknownFields = nil;
  75. // Handle the message fields.
  76. GPBDescriptor *descriptor = [[msg class] descriptor];
  77. for (GPBFieldDescriptor *field in descriptor->fields_) {
  78. if (!GPBFieldDataTypeIsMessage(field)) {
  79. continue;
  80. }
  81. switch (field.fieldType) {
  82. case GPBFieldTypeSingle:
  83. if (GPBGetHasIvarField(msg, field)) {
  84. GPBMessage *fieldMessage = GPBGetObjectIvarWithFieldNoAutocreate(msg, field);
  85. [todo addObject:fieldMessage];
  86. }
  87. break;
  88. case GPBFieldTypeRepeated: {
  89. NSArray *fieldMessages = GPBGetObjectIvarWithFieldNoAutocreate(msg, field);
  90. if (fieldMessages.count) {
  91. [todo addObjectsFromArray:fieldMessages];
  92. }
  93. break;
  94. }
  95. case GPBFieldTypeMap: {
  96. id rawFieldMap = GPBGetObjectIvarWithFieldNoAutocreate(msg, field);
  97. switch (field.mapKeyDataType) {
  98. case GPBDataTypeBool:
  99. [(GPBBoolObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^(
  100. BOOL key, id _Nonnull object, BOOL * _Nonnull stop) {
  101. #pragma unused(key, stop)
  102. [todo addObject:object];
  103. }];
  104. break;
  105. case GPBDataTypeFixed32:
  106. case GPBDataTypeUInt32:
  107. [(GPBUInt32ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^(
  108. uint32_t key, id _Nonnull object, BOOL * _Nonnull stop) {
  109. #pragma unused(key, stop)
  110. [todo addObject:object];
  111. }];
  112. break;
  113. case GPBDataTypeInt32:
  114. case GPBDataTypeSFixed32:
  115. case GPBDataTypeSInt32:
  116. [(GPBInt32ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^(
  117. int32_t key, id _Nonnull object, BOOL * _Nonnull stop) {
  118. #pragma unused(key, stop)
  119. [todo addObject:object];
  120. }];
  121. break;
  122. case GPBDataTypeFixed64:
  123. case GPBDataTypeUInt64:
  124. [(GPBUInt64ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^(
  125. uint64_t key, id _Nonnull object, BOOL * _Nonnull stop) {
  126. #pragma unused(key, stop)
  127. [todo addObject:object];
  128. }];
  129. break;
  130. case GPBDataTypeInt64:
  131. case GPBDataTypeSFixed64:
  132. case GPBDataTypeSInt64:
  133. [(GPBInt64ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^(
  134. int64_t key, id _Nonnull object, BOOL * _Nonnull stop) {
  135. #pragma unused(key, stop)
  136. [todo addObject:object];
  137. }];
  138. break;
  139. case GPBDataTypeString:
  140. [(NSDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^(
  141. NSString * _Nonnull key, GPBMessage * _Nonnull obj, BOOL * _Nonnull stop) {
  142. #pragma unused(key, stop)
  143. [todo addObject:obj];
  144. }];
  145. break;
  146. case GPBDataTypeFloat:
  147. case GPBDataTypeDouble:
  148. case GPBDataTypeEnum:
  149. case GPBDataTypeBytes:
  150. case GPBDataTypeGroup:
  151. case GPBDataTypeMessage:
  152. NSCAssert(NO, @"Aren't valid key types.");
  153. }
  154. break;
  155. } // switch(field.mapKeyDataType)
  156. } // switch(field.fieldType)
  157. } // for(fields)
  158. // Handle any extensions holding messages.
  159. for (GPBExtensionDescriptor *extension in [msg extensionsCurrentlySet]) {
  160. if (!GPBDataTypeIsMessage(extension.dataType)) {
  161. continue;
  162. }
  163. if (extension.isRepeated) {
  164. NSArray *extMessages = [msg getExtension:extension];
  165. [todo addObjectsFromArray:extMessages];
  166. } else {
  167. GPBMessage *extMessage = [msg getExtension:extension];
  168. [todo addObject:extMessage];
  169. }
  170. } // for(extensionsCurrentlySet)
  171. } // while(todo.count)
  172. }
  173. // -- About Version Checks --
  174. // There's actually 3 places these checks all come into play:
  175. // 1. When the generated source is compile into .o files, the header check
  176. // happens. This is checking the protoc used matches the library being used
  177. // when making the .o.
  178. // 2. Every place a generated proto header is included in a developer's code,
  179. // the header check comes into play again. But this time it is checking that
  180. // the current library headers being used still support/match the ones for
  181. // the generated code.
  182. // 3. At runtime the final check here (GPBCheckRuntimeVersionsInternal), is
  183. // called from the generated code passing in values captured when the
  184. // generated code's .o was made. This checks that at runtime the generated
  185. // code and runtime library match.
  186. void GPBCheckRuntimeVersionSupport(int32_t objcRuntimeVersion) {
  187. // NOTE: This is passing the value captured in the compiled code to check
  188. // against the values captured when the runtime support was compiled. This
  189. // ensures the library code isn't in a different framework/library that
  190. // was generated with a non matching version.
  191. if (GOOGLE_PROTOBUF_OBJC_VERSION < objcRuntimeVersion) {
  192. // Library is too old for headers.
  193. [NSException raise:NSInternalInconsistencyException
  194. format:@"Linked to ProtocolBuffer runtime version %d,"
  195. @" but code compiled needing atleast %d!",
  196. GOOGLE_PROTOBUF_OBJC_VERSION, objcRuntimeVersion];
  197. }
  198. if (objcRuntimeVersion < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION) {
  199. // Headers are too old for library.
  200. [NSException raise:NSInternalInconsistencyException
  201. format:@"Proto generation source compiled against runtime"
  202. @" version %d, but this version of the runtime only"
  203. @" supports back to %d!",
  204. objcRuntimeVersion,
  205. GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION];
  206. }
  207. }
  208. // This api is no longer used for version checks. 30001 is the last version
  209. // using this old versioning model. When that support is removed, this function
  210. // can be removed (along with the declaration in GPBUtilities_PackagePrivate.h).
  211. void GPBCheckRuntimeVersionInternal(int32_t version) {
  212. GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION == 30001,
  213. time_to_remove_this_old_version_shim);
  214. if (version != GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION) {
  215. [NSException raise:NSInternalInconsistencyException
  216. format:@"Linked to ProtocolBuffer runtime version %d,"
  217. @" but code compiled with version %d!",
  218. GOOGLE_PROTOBUF_OBJC_GEN_VERSION, version];
  219. }
  220. }
  221. BOOL GPBMessageHasFieldNumberSet(GPBMessage *self, uint32_t fieldNumber) {
  222. GPBDescriptor *descriptor = [self descriptor];
  223. GPBFieldDescriptor *field = [descriptor fieldWithNumber:fieldNumber];
  224. return GPBMessageHasFieldSet(self, field);
  225. }
  226. BOOL GPBMessageHasFieldSet(GPBMessage *self, GPBFieldDescriptor *field) {
  227. if (self == nil || field == nil) return NO;
  228. // Repeated/Map don't use the bit, they check the count.
  229. if (GPBFieldIsMapOrArray(field)) {
  230. // Array/map type doesn't matter, since GPB*Array/NSArray and
  231. // GPB*Dictionary/NSDictionary all support -count;
  232. NSArray *arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  233. return (arrayOrMap.count > 0);
  234. } else {
  235. return GPBGetHasIvarField(self, field);
  236. }
  237. }
  238. void GPBClearMessageField(GPBMessage *self, GPBFieldDescriptor *field) {
  239. // If not set, nothing to do.
  240. if (!GPBGetHasIvarField(self, field)) {
  241. return;
  242. }
  243. if (GPBFieldStoresObject(field)) {
  244. // Object types are handled slightly differently, they need to be released.
  245. uint8_t *storage = (uint8_t *)self->messageStorage_;
  246. id *typePtr = (id *)&storage[field->description_->offset];
  247. [*typePtr release];
  248. *typePtr = nil;
  249. } else {
  250. // POD types just need to clear the has bit as the Get* method will
  251. // fetch the default when needed.
  252. }
  253. GPBSetHasIvarField(self, field, NO);
  254. }
  255. BOOL GPBGetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber) {
  256. NSCAssert(self->messageStorage_ != NULL,
  257. @"%@: All messages should have storage (from init)",
  258. [self class]);
  259. if (idx < 0) {
  260. NSCAssert(fieldNumber != 0, @"Invalid field number.");
  261. BOOL hasIvar = (self->messageStorage_->_has_storage_[-idx] == fieldNumber);
  262. return hasIvar;
  263. } else {
  264. NSCAssert(idx != GPBNoHasBit, @"Invalid has bit.");
  265. uint32_t byteIndex = idx / 32;
  266. uint32_t bitMask = (1U << (idx % 32));
  267. BOOL hasIvar =
  268. (self->messageStorage_->_has_storage_[byteIndex] & bitMask) ? YES : NO;
  269. return hasIvar;
  270. }
  271. }
  272. uint32_t GPBGetHasOneof(GPBMessage *self, int32_t idx) {
  273. NSCAssert(idx < 0, @"%@: invalid index (%d) for oneof.",
  274. [self class], idx);
  275. uint32_t result = self->messageStorage_->_has_storage_[-idx];
  276. return result;
  277. }
  278. void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber,
  279. BOOL value) {
  280. if (idx < 0) {
  281. NSCAssert(fieldNumber != 0, @"Invalid field number.");
  282. uint32_t *has_storage = self->messageStorage_->_has_storage_;
  283. has_storage[-idx] = (value ? fieldNumber : 0);
  284. } else {
  285. NSCAssert(idx != GPBNoHasBit, @"Invalid has bit.");
  286. uint32_t *has_storage = self->messageStorage_->_has_storage_;
  287. uint32_t byte = idx / 32;
  288. uint32_t bitMask = (1U << (idx % 32));
  289. if (value) {
  290. has_storage[byte] |= bitMask;
  291. } else {
  292. has_storage[byte] &= ~bitMask;
  293. }
  294. }
  295. }
  296. void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
  297. int32_t oneofHasIndex, uint32_t fieldNumberNotToClear) {
  298. uint32_t fieldNumberSet = GPBGetHasOneof(self, oneofHasIndex);
  299. if ((fieldNumberSet == fieldNumberNotToClear) || (fieldNumberSet == 0)) {
  300. // Do nothing/nothing set in the oneof.
  301. return;
  302. }
  303. // Like GPBClearMessageField(), free the memory if an objecttype is set,
  304. // pod types don't need to do anything.
  305. GPBFieldDescriptor *fieldSet = [oneof fieldWithNumber:fieldNumberSet];
  306. NSCAssert(fieldSet,
  307. @"%@: oneof set to something (%u) not in the oneof?",
  308. [self class], fieldNumberSet);
  309. if (fieldSet && GPBFieldStoresObject(fieldSet)) {
  310. uint8_t *storage = (uint8_t *)self->messageStorage_;
  311. id *typePtr = (id *)&storage[fieldSet->description_->offset];
  312. [*typePtr release];
  313. *typePtr = nil;
  314. }
  315. // Set to nothing stored in the oneof.
  316. // (field number doesn't matter since setting to nothing).
  317. GPBSetHasIvar(self, oneofHasIndex, 1, NO);
  318. }
  319. #pragma mark - IVar accessors
  320. //%PDDM-DEFINE IVAR_POD_ACCESSORS_DEFN(NAME, TYPE)
  321. //%TYPE GPBGetMessage##NAME##Field(GPBMessage *self,
  322. //% TYPE$S NAME$S GPBFieldDescriptor *field) {
  323. //%#if defined(DEBUG) && DEBUG
  324. //% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  325. //% GPBDataType##NAME),
  326. //% @"Attempting to get value of TYPE from field %@ "
  327. //% @"of %@ which is of type %@.",
  328. //% [self class], field.name,
  329. //% TypeToString(GPBGetFieldDataType(field)));
  330. //%#endif
  331. //% if (GPBGetHasIvarField(self, field)) {
  332. //% uint8_t *storage = (uint8_t *)self->messageStorage_;
  333. //% TYPE *typePtr = (TYPE *)&storage[field->description_->offset];
  334. //% return *typePtr;
  335. //% } else {
  336. //% return field.defaultValue.value##NAME;
  337. //% }
  338. //%}
  339. //%
  340. //%// Only exists for public api, no core code should use this.
  341. //%void GPBSetMessage##NAME##Field(GPBMessage *self,
  342. //% NAME$S GPBFieldDescriptor *field,
  343. //% NAME$S TYPE value) {
  344. //% if (self == nil || field == nil) return;
  345. //% GPBFileSyntax syntax = [self descriptor].file.syntax;
  346. //% GPBSet##NAME##IvarWithFieldInternal(self, field, value, syntax);
  347. //%}
  348. //%
  349. //%void GPBSet##NAME##IvarWithFieldInternal(GPBMessage *self,
  350. //% NAME$S GPBFieldDescriptor *field,
  351. //% NAME$S TYPE value,
  352. //% NAME$S GPBFileSyntax syntax) {
  353. //%#if defined(DEBUG) && DEBUG
  354. //% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  355. //% GPBDataType##NAME),
  356. //% @"Attempting to set field %@ of %@ which is of type %@ with "
  357. //% @"value of type TYPE.",
  358. //% [self class], field.name,
  359. //% TypeToString(GPBGetFieldDataType(field)));
  360. //%#endif
  361. //% GPBOneofDescriptor *oneof = field->containingOneof_;
  362. //% if (oneof) {
  363. //% GPBMessageFieldDescription *fieldDesc = field->description_;
  364. //% GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  365. //% }
  366. //%#if defined(DEBUG) && DEBUG
  367. //% NSCAssert(self->messageStorage_ != NULL,
  368. //% @"%@: All messages should have storage (from init)",
  369. //% [self class]);
  370. //%#endif
  371. //%#if defined(__clang_analyzer__)
  372. //% if (self->messageStorage_ == NULL) return;
  373. //%#endif
  374. //% uint8_t *storage = (uint8_t *)self->messageStorage_;
  375. //% TYPE *typePtr = (TYPE *)&storage[field->description_->offset];
  376. //% *typePtr = value;
  377. //% // proto2: any value counts as having been set; proto3, it
  378. //% // has to be a non zero value or be in a oneof.
  379. //% BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
  380. //% || (value != (TYPE)0)
  381. //% || (field->containingOneof_ != NULL));
  382. //% GPBSetHasIvarField(self, field, hasValue);
  383. //% GPBBecomeVisibleToAutocreator(self);
  384. //%}
  385. //%
  386. //%PDDM-DEFINE IVAR_ALIAS_DEFN_OBJECT(NAME, TYPE)
  387. //%// Only exists for public api, no core code should use this.
  388. //%TYPE *GPBGetMessage##NAME##Field(GPBMessage *self,
  389. //% TYPE$S NAME$S GPBFieldDescriptor *field) {
  390. //%#if defined(DEBUG) && DEBUG
  391. //% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  392. //% GPBDataType##NAME),
  393. //% @"Attempting to get value of TYPE from field %@ "
  394. //% @"of %@ which is of type %@.",
  395. //% [self class], field.name,
  396. //% TypeToString(GPBGetFieldDataType(field)));
  397. //%#endif
  398. //% return (TYPE *)GPBGetObjectIvarWithField(self, field);
  399. //%}
  400. //%
  401. //%// Only exists for public api, no core code should use this.
  402. //%void GPBSetMessage##NAME##Field(GPBMessage *self,
  403. //% NAME$S GPBFieldDescriptor *field,
  404. //% NAME$S TYPE *value) {
  405. //%#if defined(DEBUG) && DEBUG
  406. //% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  407. //% GPBDataType##NAME),
  408. //% @"Attempting to set field %@ of %@ which is of type %@ with "
  409. //% @"value of type TYPE.",
  410. //% [self class], field.name,
  411. //% TypeToString(GPBGetFieldDataType(field)));
  412. //%#endif
  413. //% GPBSetObjectIvarWithField(self, field, (id)value);
  414. //%}
  415. //%
  416. //%PDDM-DEFINE IVAR_ALIAS_DEFN_COPY_OBJECT(NAME, TYPE)
  417. //%// Only exists for public api, no core code should use this.
  418. //%TYPE *GPBGetMessage##NAME##Field(GPBMessage *self,
  419. //% TYPE$S NAME$S GPBFieldDescriptor *field) {
  420. //%#if defined(DEBUG) && DEBUG
  421. //% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  422. //% GPBDataType##NAME),
  423. //% @"Attempting to get value of TYPE from field %@ "
  424. //% @"of %@ which is of type %@.",
  425. //% [self class], field.name,
  426. //% TypeToString(GPBGetFieldDataType(field)));
  427. //%#endif
  428. //% return (TYPE *)GPBGetObjectIvarWithField(self, field);
  429. //%}
  430. //%
  431. //%// Only exists for public api, no core code should use this.
  432. //%void GPBSetMessage##NAME##Field(GPBMessage *self,
  433. //% NAME$S GPBFieldDescriptor *field,
  434. //% NAME$S TYPE *value) {
  435. //%#if defined(DEBUG) && DEBUG
  436. //% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  437. //% GPBDataType##NAME),
  438. //% @"Attempting to set field %@ of %@ which is of type %@ with "
  439. //% @"value of type TYPE.",
  440. //% [self class], field.name,
  441. //% TypeToString(GPBGetFieldDataType(field)));
  442. //%#endif
  443. //% GPBSetCopyObjectIvarWithField(self, field, (id)value);
  444. //%}
  445. //%
  446. // Object types are handled slightly differently, they need to be released
  447. // and retained.
  448. void GPBSetAutocreatedRetainedObjectIvarWithField(
  449. GPBMessage *self, GPBFieldDescriptor *field,
  450. id __attribute__((ns_consumed)) value) {
  451. uint8_t *storage = (uint8_t *)self->messageStorage_;
  452. id *typePtr = (id *)&storage[field->description_->offset];
  453. NSCAssert(*typePtr == NULL, @"Can't set autocreated object more than once.");
  454. *typePtr = value;
  455. }
  456. void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self,
  457. GPBFieldDescriptor *field) {
  458. if (GPBGetHasIvarField(self, field)) {
  459. return;
  460. }
  461. uint8_t *storage = (uint8_t *)self->messageStorage_;
  462. id *typePtr = (id *)&storage[field->description_->offset];
  463. GPBMessage *oldValue = *typePtr;
  464. *typePtr = NULL;
  465. GPBClearMessageAutocreator(oldValue);
  466. [oldValue release];
  467. }
  468. // This exists only for bridging some aliased types, nothing else should use it.
  469. static void GPBSetObjectIvarWithField(GPBMessage *self,
  470. GPBFieldDescriptor *field, id value) {
  471. if (self == nil || field == nil) return;
  472. GPBFileSyntax syntax = [self descriptor].file.syntax;
  473. GPBSetRetainedObjectIvarWithFieldInternal(self, field, [value retain],
  474. syntax);
  475. }
  476. static void GPBSetCopyObjectIvarWithField(GPBMessage *self,
  477. GPBFieldDescriptor *field, id value);
  478. // GPBSetCopyObjectIvarWithField is blocked from the analyzer because it flags
  479. // a leak for the -copy even though GPBSetRetainedObjectIvarWithFieldInternal
  480. // is marked as consuming the value. Note: For some reason this doesn't happen
  481. // with the -retain in GPBSetObjectIvarWithField.
  482. #if !defined(__clang_analyzer__)
  483. // This exists only for bridging some aliased types, nothing else should use it.
  484. static void GPBSetCopyObjectIvarWithField(GPBMessage *self,
  485. GPBFieldDescriptor *field, id value) {
  486. if (self == nil || field == nil) return;
  487. GPBFileSyntax syntax = [self descriptor].file.syntax;
  488. GPBSetRetainedObjectIvarWithFieldInternal(self, field, [value copy],
  489. syntax);
  490. }
  491. #endif // !defined(__clang_analyzer__)
  492. void GPBSetObjectIvarWithFieldInternal(GPBMessage *self,
  493. GPBFieldDescriptor *field, id value,
  494. GPBFileSyntax syntax) {
  495. GPBSetRetainedObjectIvarWithFieldInternal(self, field, [value retain],
  496. syntax);
  497. }
  498. void GPBSetRetainedObjectIvarWithFieldInternal(GPBMessage *self,
  499. GPBFieldDescriptor *field,
  500. id value, GPBFileSyntax syntax) {
  501. NSCAssert(self->messageStorage_ != NULL,
  502. @"%@: All messages should have storage (from init)",
  503. [self class]);
  504. #if defined(__clang_analyzer__)
  505. if (self->messageStorage_ == NULL) return;
  506. #endif
  507. GPBDataType fieldType = GPBGetFieldDataType(field);
  508. BOOL isMapOrArray = GPBFieldIsMapOrArray(field);
  509. BOOL fieldIsMessage = GPBDataTypeIsMessage(fieldType);
  510. #if defined(DEBUG) && DEBUG
  511. if (value == nil && !isMapOrArray && !fieldIsMessage &&
  512. field.hasDefaultValue) {
  513. // Setting a message to nil is an obvious way to "clear" the value
  514. // as there is no way to set a non-empty default value for messages.
  515. //
  516. // For Strings and Bytes that have default values set it is not clear what
  517. // should be done when their value is set to nil. Is the intention just to
  518. // clear the set value and reset to default, or is the intention to set the
  519. // value to the empty string/data? Arguments can be made for both cases.
  520. // 'nil' has been abused as a replacement for an empty string/data in ObjC.
  521. // We decided to be consistent with all "object" types and clear the has
  522. // field, and fall back on the default value. The warning below will only
  523. // appear in debug, but the could should be changed so the intention is
  524. // clear.
  525. NSString *hasSel = NSStringFromSelector(field->hasOrCountSel_);
  526. NSString *propName = field.name;
  527. NSString *className = self.descriptor.name;
  528. NSLog(@"warning: '%@.%@ = nil;' is not clearly defined for fields with "
  529. @"default values. Please use '%@.%@ = %@' if you want to set it to "
  530. @"empty, or call '%@.%@ = NO' to reset it to it's default value of "
  531. @"'%@'. Defaulting to resetting default value.",
  532. className, propName, className, propName,
  533. (fieldType == GPBDataTypeString) ? @"@\"\"" : @"GPBEmptyNSData()",
  534. className, hasSel, field.defaultValue.valueString);
  535. // Note: valueString, depending on the type, it could easily be
  536. // valueData/valueMessage.
  537. }
  538. #endif // DEBUG
  539. if (!isMapOrArray) {
  540. // Non repeated/map can be in an oneof, clear any existing value from the
  541. // oneof.
  542. GPBOneofDescriptor *oneof = field->containingOneof_;
  543. if (oneof) {
  544. GPBMessageFieldDescription *fieldDesc = field->description_;
  545. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  546. }
  547. // Clear "has" if they are being set to nil.
  548. BOOL setHasValue = (value != nil);
  549. // Under proto3, Bytes & String fields get cleared by resetting them to
  550. // their default (empty) values, so if they are set to something of length
  551. // zero, they are being cleared.
  552. if ((syntax == GPBFileSyntaxProto3) && !fieldIsMessage &&
  553. ([value length] == 0)) {
  554. // Except, if the field was in a oneof, then it still gets recorded as
  555. // having been set so the state of the oneof can be serialized back out.
  556. if (!oneof) {
  557. setHasValue = NO;
  558. }
  559. if (setHasValue) {
  560. NSCAssert(value != nil, @"Should never be setting has for nil");
  561. } else {
  562. // The value passed in was retained, it must be released since we
  563. // aren't saving anything in the field.
  564. [value release];
  565. value = nil;
  566. }
  567. }
  568. GPBSetHasIvarField(self, field, setHasValue);
  569. }
  570. uint8_t *storage = (uint8_t *)self->messageStorage_;
  571. id *typePtr = (id *)&storage[field->description_->offset];
  572. id oldValue = *typePtr;
  573. *typePtr = value;
  574. if (oldValue) {
  575. if (isMapOrArray) {
  576. if (field.fieldType == GPBFieldTypeRepeated) {
  577. // If the old array was autocreated by us, then clear it.
  578. if (GPBDataTypeIsObject(fieldType)) {
  579. if ([oldValue isKindOfClass:[GPBAutocreatedArray class]]) {
  580. GPBAutocreatedArray *autoArray = oldValue;
  581. if (autoArray->_autocreator == self) {
  582. autoArray->_autocreator = nil;
  583. }
  584. }
  585. } else {
  586. // Type doesn't matter, it is a GPB*Array.
  587. GPBInt32Array *gpbArray = oldValue;
  588. if (gpbArray->_autocreator == self) {
  589. gpbArray->_autocreator = nil;
  590. }
  591. }
  592. } else { // GPBFieldTypeMap
  593. // If the old map was autocreated by us, then clear it.
  594. if ((field.mapKeyDataType == GPBDataTypeString) &&
  595. GPBDataTypeIsObject(fieldType)) {
  596. if ([oldValue isKindOfClass:[GPBAutocreatedDictionary class]]) {
  597. GPBAutocreatedDictionary *autoDict = oldValue;
  598. if (autoDict->_autocreator == self) {
  599. autoDict->_autocreator = nil;
  600. }
  601. }
  602. } else {
  603. // Type doesn't matter, it is a GPB*Dictionary.
  604. GPBInt32Int32Dictionary *gpbDict = oldValue;
  605. if (gpbDict->_autocreator == self) {
  606. gpbDict->_autocreator = nil;
  607. }
  608. }
  609. }
  610. } else if (fieldIsMessage) {
  611. // If the old message value was autocreated by us, then clear it.
  612. GPBMessage *oldMessageValue = oldValue;
  613. if (GPBWasMessageAutocreatedBy(oldMessageValue, self)) {
  614. GPBClearMessageAutocreator(oldMessageValue);
  615. }
  616. }
  617. [oldValue release];
  618. }
  619. GPBBecomeVisibleToAutocreator(self);
  620. }
  621. id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self,
  622. GPBFieldDescriptor *field) {
  623. if (self->messageStorage_ == nil) {
  624. return nil;
  625. }
  626. uint8_t *storage = (uint8_t *)self->messageStorage_;
  627. id *typePtr = (id *)&storage[field->description_->offset];
  628. return *typePtr;
  629. }
  630. // Only exists for public api, no core code should use this.
  631. int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field) {
  632. GPBFileSyntax syntax = [self descriptor].file.syntax;
  633. return GPBGetEnumIvarWithFieldInternal(self, field, syntax);
  634. }
  635. int32_t GPBGetEnumIvarWithFieldInternal(GPBMessage *self,
  636. GPBFieldDescriptor *field,
  637. GPBFileSyntax syntax) {
  638. #if defined(DEBUG) && DEBUG
  639. NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum,
  640. @"Attempting to get value of type Enum from field %@ "
  641. @"of %@ which is of type %@.",
  642. [self class], field.name,
  643. TypeToString(GPBGetFieldDataType(field)));
  644. #endif
  645. int32_t result = GPBGetMessageInt32Field(self, field);
  646. // If this is presevering unknown enums, make sure the value is valid before
  647. // returning it.
  648. if (GPBHasPreservingUnknownEnumSemantics(syntax) &&
  649. ![field isValidEnumValue:result]) {
  650. result = kGPBUnrecognizedEnumeratorValue;
  651. }
  652. return result;
  653. }
  654. // Only exists for public api, no core code should use this.
  655. void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field,
  656. int32_t value) {
  657. GPBFileSyntax syntax = [self descriptor].file.syntax;
  658. GPBSetInt32IvarWithFieldInternal(self, field, value, syntax);
  659. }
  660. void GPBSetEnumIvarWithFieldInternal(GPBMessage *self,
  661. GPBFieldDescriptor *field, int32_t value,
  662. GPBFileSyntax syntax) {
  663. #if defined(DEBUG) && DEBUG
  664. NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum,
  665. @"Attempting to set field %@ of %@ which is of type %@ with "
  666. @"value of type Enum.",
  667. [self class], field.name,
  668. TypeToString(GPBGetFieldDataType(field)));
  669. #endif
  670. // Don't allow in unknown values. Proto3 can use the Raw method.
  671. if (![field isValidEnumValue:value]) {
  672. [NSException raise:NSInvalidArgumentException
  673. format:@"%@.%@: Attempt to set an unknown enum value (%d)",
  674. [self class], field.name, value];
  675. }
  676. GPBSetInt32IvarWithFieldInternal(self, field, value, syntax);
  677. }
  678. // Only exists for public api, no core code should use this.
  679. int32_t GPBGetMessageRawEnumField(GPBMessage *self,
  680. GPBFieldDescriptor *field) {
  681. int32_t result = GPBGetMessageInt32Field(self, field);
  682. return result;
  683. }
  684. // Only exists for public api, no core code should use this.
  685. void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field,
  686. int32_t value) {
  687. GPBFileSyntax syntax = [self descriptor].file.syntax;
  688. GPBSetInt32IvarWithFieldInternal(self, field, value, syntax);
  689. }
  690. BOOL GPBGetMessageBoolField(GPBMessage *self,
  691. GPBFieldDescriptor *field) {
  692. #if defined(DEBUG) && DEBUG
  693. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool),
  694. @"Attempting to get value of type bool from field %@ "
  695. @"of %@ which is of type %@.",
  696. [self class], field.name,
  697. TypeToString(GPBGetFieldDataType(field)));
  698. #endif
  699. if (GPBGetHasIvarField(self, field)) {
  700. // Bools are stored in the has bits to avoid needing explicit space in the
  701. // storage structure.
  702. // (the field number passed to the HasIvar helper doesn't really matter
  703. // since the offset is never negative)
  704. GPBMessageFieldDescription *fieldDesc = field->description_;
  705. return GPBGetHasIvar(self, (int32_t)(fieldDesc->offset), fieldDesc->number);
  706. } else {
  707. return field.defaultValue.valueBool;
  708. }
  709. }
  710. // Only exists for public api, no core code should use this.
  711. void GPBSetMessageBoolField(GPBMessage *self,
  712. GPBFieldDescriptor *field,
  713. BOOL value) {
  714. if (self == nil || field == nil) return;
  715. GPBFileSyntax syntax = [self descriptor].file.syntax;
  716. GPBSetBoolIvarWithFieldInternal(self, field, value, syntax);
  717. }
  718. void GPBSetBoolIvarWithFieldInternal(GPBMessage *self,
  719. GPBFieldDescriptor *field,
  720. BOOL value,
  721. GPBFileSyntax syntax) {
  722. #if defined(DEBUG) && DEBUG
  723. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool),
  724. @"Attempting to set field %@ of %@ which is of type %@ with "
  725. @"value of type bool.",
  726. [self class], field.name,
  727. TypeToString(GPBGetFieldDataType(field)));
  728. #endif
  729. GPBMessageFieldDescription *fieldDesc = field->description_;
  730. GPBOneofDescriptor *oneof = field->containingOneof_;
  731. if (oneof) {
  732. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  733. }
  734. // Bools are stored in the has bits to avoid needing explicit space in the
  735. // storage structure.
  736. // (the field number passed to the HasIvar helper doesn't really matter since
  737. // the offset is never negative)
  738. GPBSetHasIvar(self, (int32_t)(fieldDesc->offset), fieldDesc->number, value);
  739. // proto2: any value counts as having been set; proto3, it
  740. // has to be a non zero value or be in a oneof.
  741. BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
  742. || (value != (BOOL)0)
  743. || (field->containingOneof_ != NULL));
  744. GPBSetHasIvarField(self, field, hasValue);
  745. GPBBecomeVisibleToAutocreator(self);
  746. }
  747. //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Int32, int32_t)
  748. // This block of code is generated, do not edit it directly.
  749. // clang-format off
  750. int32_t GPBGetMessageInt32Field(GPBMessage *self,
  751. GPBFieldDescriptor *field) {
  752. #if defined(DEBUG) && DEBUG
  753. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  754. GPBDataTypeInt32),
  755. @"Attempting to get value of int32_t from field %@ "
  756. @"of %@ which is of type %@.",
  757. [self class], field.name,
  758. TypeToString(GPBGetFieldDataType(field)));
  759. #endif
  760. if (GPBGetHasIvarField(self, field)) {
  761. uint8_t *storage = (uint8_t *)self->messageStorage_;
  762. int32_t *typePtr = (int32_t *)&storage[field->description_->offset];
  763. return *typePtr;
  764. } else {
  765. return field.defaultValue.valueInt32;
  766. }
  767. }
  768. // Only exists for public api, no core code should use this.
  769. void GPBSetMessageInt32Field(GPBMessage *self,
  770. GPBFieldDescriptor *field,
  771. int32_t value) {
  772. if (self == nil || field == nil) return;
  773. GPBFileSyntax syntax = [self descriptor].file.syntax;
  774. GPBSetInt32IvarWithFieldInternal(self, field, value, syntax);
  775. }
  776. void GPBSetInt32IvarWithFieldInternal(GPBMessage *self,
  777. GPBFieldDescriptor *field,
  778. int32_t value,
  779. GPBFileSyntax syntax) {
  780. #if defined(DEBUG) && DEBUG
  781. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  782. GPBDataTypeInt32),
  783. @"Attempting to set field %@ of %@ which is of type %@ with "
  784. @"value of type int32_t.",
  785. [self class], field.name,
  786. TypeToString(GPBGetFieldDataType(field)));
  787. #endif
  788. GPBOneofDescriptor *oneof = field->containingOneof_;
  789. if (oneof) {
  790. GPBMessageFieldDescription *fieldDesc = field->description_;
  791. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  792. }
  793. #if defined(DEBUG) && DEBUG
  794. NSCAssert(self->messageStorage_ != NULL,
  795. @"%@: All messages should have storage (from init)",
  796. [self class]);
  797. #endif
  798. #if defined(__clang_analyzer__)
  799. if (self->messageStorage_ == NULL) return;
  800. #endif
  801. uint8_t *storage = (uint8_t *)self->messageStorage_;
  802. int32_t *typePtr = (int32_t *)&storage[field->description_->offset];
  803. *typePtr = value;
  804. // proto2: any value counts as having been set; proto3, it
  805. // has to be a non zero value or be in a oneof.
  806. BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
  807. || (value != (int32_t)0)
  808. || (field->containingOneof_ != NULL));
  809. GPBSetHasIvarField(self, field, hasValue);
  810. GPBBecomeVisibleToAutocreator(self);
  811. }
  812. // clang-format on
  813. //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(UInt32, uint32_t)
  814. // This block of code is generated, do not edit it directly.
  815. // clang-format off
  816. uint32_t GPBGetMessageUInt32Field(GPBMessage *self,
  817. GPBFieldDescriptor *field) {
  818. #if defined(DEBUG) && DEBUG
  819. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  820. GPBDataTypeUInt32),
  821. @"Attempting to get value of uint32_t from field %@ "
  822. @"of %@ which is of type %@.",
  823. [self class], field.name,
  824. TypeToString(GPBGetFieldDataType(field)));
  825. #endif
  826. if (GPBGetHasIvarField(self, field)) {
  827. uint8_t *storage = (uint8_t *)self->messageStorage_;
  828. uint32_t *typePtr = (uint32_t *)&storage[field->description_->offset];
  829. return *typePtr;
  830. } else {
  831. return field.defaultValue.valueUInt32;
  832. }
  833. }
  834. // Only exists for public api, no core code should use this.
  835. void GPBSetMessageUInt32Field(GPBMessage *self,
  836. GPBFieldDescriptor *field,
  837. uint32_t value) {
  838. if (self == nil || field == nil) return;
  839. GPBFileSyntax syntax = [self descriptor].file.syntax;
  840. GPBSetUInt32IvarWithFieldInternal(self, field, value, syntax);
  841. }
  842. void GPBSetUInt32IvarWithFieldInternal(GPBMessage *self,
  843. GPBFieldDescriptor *field,
  844. uint32_t value,
  845. GPBFileSyntax syntax) {
  846. #if defined(DEBUG) && DEBUG
  847. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  848. GPBDataTypeUInt32),
  849. @"Attempting to set field %@ of %@ which is of type %@ with "
  850. @"value of type uint32_t.",
  851. [self class], field.name,
  852. TypeToString(GPBGetFieldDataType(field)));
  853. #endif
  854. GPBOneofDescriptor *oneof = field->containingOneof_;
  855. if (oneof) {
  856. GPBMessageFieldDescription *fieldDesc = field->description_;
  857. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  858. }
  859. #if defined(DEBUG) && DEBUG
  860. NSCAssert(self->messageStorage_ != NULL,
  861. @"%@: All messages should have storage (from init)",
  862. [self class]);
  863. #endif
  864. #if defined(__clang_analyzer__)
  865. if (self->messageStorage_ == NULL) return;
  866. #endif
  867. uint8_t *storage = (uint8_t *)self->messageStorage_;
  868. uint32_t *typePtr = (uint32_t *)&storage[field->description_->offset];
  869. *typePtr = value;
  870. // proto2: any value counts as having been set; proto3, it
  871. // has to be a non zero value or be in a oneof.
  872. BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
  873. || (value != (uint32_t)0)
  874. || (field->containingOneof_ != NULL));
  875. GPBSetHasIvarField(self, field, hasValue);
  876. GPBBecomeVisibleToAutocreator(self);
  877. }
  878. // clang-format on
  879. //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Int64, int64_t)
  880. // This block of code is generated, do not edit it directly.
  881. // clang-format off
  882. int64_t GPBGetMessageInt64Field(GPBMessage *self,
  883. GPBFieldDescriptor *field) {
  884. #if defined(DEBUG) && DEBUG
  885. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  886. GPBDataTypeInt64),
  887. @"Attempting to get value of int64_t from field %@ "
  888. @"of %@ which is of type %@.",
  889. [self class], field.name,
  890. TypeToString(GPBGetFieldDataType(field)));
  891. #endif
  892. if (GPBGetHasIvarField(self, field)) {
  893. uint8_t *storage = (uint8_t *)self->messageStorage_;
  894. int64_t *typePtr = (int64_t *)&storage[field->description_->offset];
  895. return *typePtr;
  896. } else {
  897. return field.defaultValue.valueInt64;
  898. }
  899. }
  900. // Only exists for public api, no core code should use this.
  901. void GPBSetMessageInt64Field(GPBMessage *self,
  902. GPBFieldDescriptor *field,
  903. int64_t value) {
  904. if (self == nil || field == nil) return;
  905. GPBFileSyntax syntax = [self descriptor].file.syntax;
  906. GPBSetInt64IvarWithFieldInternal(self, field, value, syntax);
  907. }
  908. void GPBSetInt64IvarWithFieldInternal(GPBMessage *self,
  909. GPBFieldDescriptor *field,
  910. int64_t value,
  911. GPBFileSyntax syntax) {
  912. #if defined(DEBUG) && DEBUG
  913. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  914. GPBDataTypeInt64),
  915. @"Attempting to set field %@ of %@ which is of type %@ with "
  916. @"value of type int64_t.",
  917. [self class], field.name,
  918. TypeToString(GPBGetFieldDataType(field)));
  919. #endif
  920. GPBOneofDescriptor *oneof = field->containingOneof_;
  921. if (oneof) {
  922. GPBMessageFieldDescription *fieldDesc = field->description_;
  923. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  924. }
  925. #if defined(DEBUG) && DEBUG
  926. NSCAssert(self->messageStorage_ != NULL,
  927. @"%@: All messages should have storage (from init)",
  928. [self class]);
  929. #endif
  930. #if defined(__clang_analyzer__)
  931. if (self->messageStorage_ == NULL) return;
  932. #endif
  933. uint8_t *storage = (uint8_t *)self->messageStorage_;
  934. int64_t *typePtr = (int64_t *)&storage[field->description_->offset];
  935. *typePtr = value;
  936. // proto2: any value counts as having been set; proto3, it
  937. // has to be a non zero value or be in a oneof.
  938. BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
  939. || (value != (int64_t)0)
  940. || (field->containingOneof_ != NULL));
  941. GPBSetHasIvarField(self, field, hasValue);
  942. GPBBecomeVisibleToAutocreator(self);
  943. }
  944. // clang-format on
  945. //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(UInt64, uint64_t)
  946. // This block of code is generated, do not edit it directly.
  947. // clang-format off
  948. uint64_t GPBGetMessageUInt64Field(GPBMessage *self,
  949. GPBFieldDescriptor *field) {
  950. #if defined(DEBUG) && DEBUG
  951. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  952. GPBDataTypeUInt64),
  953. @"Attempting to get value of uint64_t from field %@ "
  954. @"of %@ which is of type %@.",
  955. [self class], field.name,
  956. TypeToString(GPBGetFieldDataType(field)));
  957. #endif
  958. if (GPBGetHasIvarField(self, field)) {
  959. uint8_t *storage = (uint8_t *)self->messageStorage_;
  960. uint64_t *typePtr = (uint64_t *)&storage[field->description_->offset];
  961. return *typePtr;
  962. } else {
  963. return field.defaultValue.valueUInt64;
  964. }
  965. }
  966. // Only exists for public api, no core code should use this.
  967. void GPBSetMessageUInt64Field(GPBMessage *self,
  968. GPBFieldDescriptor *field,
  969. uint64_t value) {
  970. if (self == nil || field == nil) return;
  971. GPBFileSyntax syntax = [self descriptor].file.syntax;
  972. GPBSetUInt64IvarWithFieldInternal(self, field, value, syntax);
  973. }
  974. void GPBSetUInt64IvarWithFieldInternal(GPBMessage *self,
  975. GPBFieldDescriptor *field,
  976. uint64_t value,
  977. GPBFileSyntax syntax) {
  978. #if defined(DEBUG) && DEBUG
  979. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  980. GPBDataTypeUInt64),
  981. @"Attempting to set field %@ of %@ which is of type %@ with "
  982. @"value of type uint64_t.",
  983. [self class], field.name,
  984. TypeToString(GPBGetFieldDataType(field)));
  985. #endif
  986. GPBOneofDescriptor *oneof = field->containingOneof_;
  987. if (oneof) {
  988. GPBMessageFieldDescription *fieldDesc = field->description_;
  989. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  990. }
  991. #if defined(DEBUG) && DEBUG
  992. NSCAssert(self->messageStorage_ != NULL,
  993. @"%@: All messages should have storage (from init)",
  994. [self class]);
  995. #endif
  996. #if defined(__clang_analyzer__)
  997. if (self->messageStorage_ == NULL) return;
  998. #endif
  999. uint8_t *storage = (uint8_t *)self->messageStorage_;
  1000. uint64_t *typePtr = (uint64_t *)&storage[field->description_->offset];
  1001. *typePtr = value;
  1002. // proto2: any value counts as having been set; proto3, it
  1003. // has to be a non zero value or be in a oneof.
  1004. BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
  1005. || (value != (uint64_t)0)
  1006. || (field->containingOneof_ != NULL));
  1007. GPBSetHasIvarField(self, field, hasValue);
  1008. GPBBecomeVisibleToAutocreator(self);
  1009. }
  1010. // clang-format on
  1011. //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Float, float)
  1012. // This block of code is generated, do not edit it directly.
  1013. // clang-format off
  1014. float GPBGetMessageFloatField(GPBMessage *self,
  1015. GPBFieldDescriptor *field) {
  1016. #if defined(DEBUG) && DEBUG
  1017. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  1018. GPBDataTypeFloat),
  1019. @"Attempting to get value of float from field %@ "
  1020. @"of %@ which is of type %@.",
  1021. [self class], field.name,
  1022. TypeToString(GPBGetFieldDataType(field)));
  1023. #endif
  1024. if (GPBGetHasIvarField(self, field)) {
  1025. uint8_t *storage = (uint8_t *)self->messageStorage_;
  1026. float *typePtr = (float *)&storage[field->description_->offset];
  1027. return *typePtr;
  1028. } else {
  1029. return field.defaultValue.valueFloat;
  1030. }
  1031. }
  1032. // Only exists for public api, no core code should use this.
  1033. void GPBSetMessageFloatField(GPBMessage *self,
  1034. GPBFieldDescriptor *field,
  1035. float value) {
  1036. if (self == nil || field == nil) return;
  1037. GPBFileSyntax syntax = [self descriptor].file.syntax;
  1038. GPBSetFloatIvarWithFieldInternal(self, field, value, syntax);
  1039. }
  1040. void GPBSetFloatIvarWithFieldInternal(GPBMessage *self,
  1041. GPBFieldDescriptor *field,
  1042. float value,
  1043. GPBFileSyntax syntax) {
  1044. #if defined(DEBUG) && DEBUG
  1045. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  1046. GPBDataTypeFloat),
  1047. @"Attempting to set field %@ of %@ which is of type %@ with "
  1048. @"value of type float.",
  1049. [self class], field.name,
  1050. TypeToString(GPBGetFieldDataType(field)));
  1051. #endif
  1052. GPBOneofDescriptor *oneof = field->containingOneof_;
  1053. if (oneof) {
  1054. GPBMessageFieldDescription *fieldDesc = field->description_;
  1055. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  1056. }
  1057. #if defined(DEBUG) && DEBUG
  1058. NSCAssert(self->messageStorage_ != NULL,
  1059. @"%@: All messages should have storage (from init)",
  1060. [self class]);
  1061. #endif
  1062. #if defined(__clang_analyzer__)
  1063. if (self->messageStorage_ == NULL) return;
  1064. #endif
  1065. uint8_t *storage = (uint8_t *)self->messageStorage_;
  1066. float *typePtr = (float *)&storage[field->description_->offset];
  1067. *typePtr = value;
  1068. // proto2: any value counts as having been set; proto3, it
  1069. // has to be a non zero value or be in a oneof.
  1070. BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
  1071. || (value != (float)0)
  1072. || (field->containingOneof_ != NULL));
  1073. GPBSetHasIvarField(self, field, hasValue);
  1074. GPBBecomeVisibleToAutocreator(self);
  1075. }
  1076. // clang-format on
  1077. //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Double, double)
  1078. // This block of code is generated, do not edit it directly.
  1079. // clang-format off
  1080. double GPBGetMessageDoubleField(GPBMessage *self,
  1081. GPBFieldDescriptor *field) {
  1082. #if defined(DEBUG) && DEBUG
  1083. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  1084. GPBDataTypeDouble),
  1085. @"Attempting to get value of double from field %@ "
  1086. @"of %@ which is of type %@.",
  1087. [self class], field.name,
  1088. TypeToString(GPBGetFieldDataType(field)));
  1089. #endif
  1090. if (GPBGetHasIvarField(self, field)) {
  1091. uint8_t *storage = (uint8_t *)self->messageStorage_;
  1092. double *typePtr = (double *)&storage[field->description_->offset];
  1093. return *typePtr;
  1094. } else {
  1095. return field.defaultValue.valueDouble;
  1096. }
  1097. }
  1098. // Only exists for public api, no core code should use this.
  1099. void GPBSetMessageDoubleField(GPBMessage *self,
  1100. GPBFieldDescriptor *field,
  1101. double value) {
  1102. if (self == nil || field == nil) return;
  1103. GPBFileSyntax syntax = [self descriptor].file.syntax;
  1104. GPBSetDoubleIvarWithFieldInternal(self, field, value, syntax);
  1105. }
  1106. void GPBSetDoubleIvarWithFieldInternal(GPBMessage *self,
  1107. GPBFieldDescriptor *field,
  1108. double value,
  1109. GPBFileSyntax syntax) {
  1110. #if defined(DEBUG) && DEBUG
  1111. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  1112. GPBDataTypeDouble),
  1113. @"Attempting to set field %@ of %@ which is of type %@ with "
  1114. @"value of type double.",
  1115. [self class], field.name,
  1116. TypeToString(GPBGetFieldDataType(field)));
  1117. #endif
  1118. GPBOneofDescriptor *oneof = field->containingOneof_;
  1119. if (oneof) {
  1120. GPBMessageFieldDescription *fieldDesc = field->description_;
  1121. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  1122. }
  1123. #if defined(DEBUG) && DEBUG
  1124. NSCAssert(self->messageStorage_ != NULL,
  1125. @"%@: All messages should have storage (from init)",
  1126. [self class]);
  1127. #endif
  1128. #if defined(__clang_analyzer__)
  1129. if (self->messageStorage_ == NULL) return;
  1130. #endif
  1131. uint8_t *storage = (uint8_t *)self->messageStorage_;
  1132. double *typePtr = (double *)&storage[field->description_->offset];
  1133. *typePtr = value;
  1134. // proto2: any value counts as having been set; proto3, it
  1135. // has to be a non zero value or be in a oneof.
  1136. BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
  1137. || (value != (double)0)
  1138. || (field->containingOneof_ != NULL));
  1139. GPBSetHasIvarField(self, field, hasValue);
  1140. GPBBecomeVisibleToAutocreator(self);
  1141. }
  1142. // clang-format on
  1143. //%PDDM-EXPAND-END (6 expansions)
  1144. // Aliases are function calls that are virtually the same.
  1145. //%PDDM-EXPAND IVAR_ALIAS_DEFN_COPY_OBJECT(String, NSString)
  1146. // This block of code is generated, do not edit it directly.
  1147. // clang-format off
  1148. // Only exists for public api, no core code should use this.
  1149. NSString *GPBGetMessageStringField(GPBMessage *self,
  1150. GPBFieldDescriptor *field) {
  1151. #if defined(DEBUG) && DEBUG
  1152. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  1153. GPBDataTypeString),
  1154. @"Attempting to get value of NSString from field %@ "
  1155. @"of %@ which is of type %@.",
  1156. [self class], field.name,
  1157. TypeToString(GPBGetFieldDataType(field)));
  1158. #endif
  1159. return (NSString *)GPBGetObjectIvarWithField(self, field);
  1160. }
  1161. // Only exists for public api, no core code should use this.
  1162. void GPBSetMessageStringField(GPBMessage *self,
  1163. GPBFieldDescriptor *field,
  1164. NSString *value) {
  1165. #if defined(DEBUG) && DEBUG
  1166. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  1167. GPBDataTypeString),
  1168. @"Attempting to set field %@ of %@ which is of type %@ with "
  1169. @"value of type NSString.",
  1170. [self class], field.name,
  1171. TypeToString(GPBGetFieldDataType(field)));
  1172. #endif
  1173. GPBSetCopyObjectIvarWithField(self, field, (id)value);
  1174. }
  1175. // clang-format on
  1176. //%PDDM-EXPAND IVAR_ALIAS_DEFN_COPY_OBJECT(Bytes, NSData)
  1177. // This block of code is generated, do not edit it directly.
  1178. // clang-format off
  1179. // Only exists for public api, no core code should use this.
  1180. NSData *GPBGetMessageBytesField(GPBMessage *self,
  1181. GPBFieldDescriptor *field) {
  1182. #if defined(DEBUG) && DEBUG
  1183. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  1184. GPBDataTypeBytes),
  1185. @"Attempting to get value of NSData from field %@ "
  1186. @"of %@ which is of type %@.",
  1187. [self class], field.name,
  1188. TypeToString(GPBGetFieldDataType(field)));
  1189. #endif
  1190. return (NSData *)GPBGetObjectIvarWithField(self, field);
  1191. }
  1192. // Only exists for public api, no core code should use this.
  1193. void GPBSetMessageBytesField(GPBMessage *self,
  1194. GPBFieldDescriptor *field,
  1195. NSData *value) {
  1196. #if defined(DEBUG) && DEBUG
  1197. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  1198. GPBDataTypeBytes),
  1199. @"Attempting to set field %@ of %@ which is of type %@ with "
  1200. @"value of type NSData.",
  1201. [self class], field.name,
  1202. TypeToString(GPBGetFieldDataType(field)));
  1203. #endif
  1204. GPBSetCopyObjectIvarWithField(self, field, (id)value);
  1205. }
  1206. // clang-format on
  1207. //%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Message, GPBMessage)
  1208. // This block of code is generated, do not edit it directly.
  1209. // clang-format off
  1210. // Only exists for public api, no core code should use this.
  1211. GPBMessage *GPBGetMessageMessageField(GPBMessage *self,
  1212. GPBFieldDescriptor *field) {
  1213. #if defined(DEBUG) && DEBUG
  1214. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  1215. GPBDataTypeMessage),
  1216. @"Attempting to get value of GPBMessage from field %@ "
  1217. @"of %@ which is of type %@.",
  1218. [self class], field.name,
  1219. TypeToString(GPBGetFieldDataType(field)));
  1220. #endif
  1221. return (GPBMessage *)GPBGetObjectIvarWithField(self, field);
  1222. }
  1223. // Only exists for public api, no core code should use this.
  1224. void GPBSetMessageMessageField(GPBMessage *self,
  1225. GPBFieldDescriptor *field,
  1226. GPBMessage *value) {
  1227. #if defined(DEBUG) && DEBUG
  1228. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  1229. GPBDataTypeMessage),
  1230. @"Attempting to set field %@ of %@ which is of type %@ with "
  1231. @"value of type GPBMessage.",
  1232. [self class], field.name,
  1233. TypeToString(GPBGetFieldDataType(field)));
  1234. #endif
  1235. GPBSetObjectIvarWithField(self, field, (id)value);
  1236. }
  1237. // clang-format on
  1238. //%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Group, GPBMessage)
  1239. // This block of code is generated, do not edit it directly.
  1240. // clang-format off
  1241. // Only exists for public api, no core code should use this.
  1242. GPBMessage *GPBGetMessageGroupField(GPBMessage *self,
  1243. GPBFieldDescriptor *field) {
  1244. #if defined(DEBUG) && DEBUG
  1245. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  1246. GPBDataTypeGroup),
  1247. @"Attempting to get value of GPBMessage from field %@ "
  1248. @"of %@ which is of type %@.",
  1249. [self class], field.name,
  1250. TypeToString(GPBGetFieldDataType(field)));
  1251. #endif
  1252. return (GPBMessage *)GPBGetObjectIvarWithField(self, field);
  1253. }
  1254. // Only exists for public api, no core code should use this.
  1255. void GPBSetMessageGroupField(GPBMessage *self,
  1256. GPBFieldDescriptor *field,
  1257. GPBMessage *value) {
  1258. #if defined(DEBUG) && DEBUG
  1259. NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
  1260. GPBDataTypeGroup),
  1261. @"Attempting to set field %@ of %@ which is of type %@ with "
  1262. @"value of type GPBMessage.",
  1263. [self class], field.name,
  1264. TypeToString(GPBGetFieldDataType(field)));
  1265. #endif
  1266. GPBSetObjectIvarWithField(self, field, (id)value);
  1267. }
  1268. // clang-format on
  1269. //%PDDM-EXPAND-END (4 expansions)
  1270. // GPBGetMessageRepeatedField is defined in GPBMessage.m
  1271. // Only exists for public api, no core code should use this.
  1272. void GPBSetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field, id array) {
  1273. #if defined(DEBUG) && DEBUG
  1274. if (field.fieldType != GPBFieldTypeRepeated) {
  1275. [NSException raise:NSInvalidArgumentException
  1276. format:@"%@.%@ is not a repeated field.",
  1277. [self class], field.name];
  1278. }
  1279. Class expectedClass = Nil;
  1280. switch (GPBGetFieldDataType(field)) {
  1281. case GPBDataTypeBool:
  1282. expectedClass = [GPBBoolArray class];
  1283. break;
  1284. case GPBDataTypeSFixed32:
  1285. case GPBDataTypeInt32:
  1286. case GPBDataTypeSInt32:
  1287. expectedClass = [GPBInt32Array class];
  1288. break;
  1289. case GPBDataTypeFixed32:
  1290. case GPBDataTypeUInt32:
  1291. expectedClass = [GPBUInt32Array class];
  1292. break;
  1293. case GPBDataTypeSFixed64:
  1294. case GPBDataTypeInt64:
  1295. case GPBDataTypeSInt64:
  1296. expectedClass = [GPBInt64Array class];
  1297. break;
  1298. case GPBDataTypeFixed64:
  1299. case GPBDataTypeUInt64:
  1300. expectedClass = [GPBUInt64Array class];
  1301. break;
  1302. case GPBDataTypeFloat:
  1303. expectedClass = [GPBFloatArray class];
  1304. break;
  1305. case GPBDataTypeDouble:
  1306. expectedClass = [GPBDoubleArray class];
  1307. break;
  1308. case GPBDataTypeBytes:
  1309. case GPBDataTypeString:
  1310. case GPBDataTypeMessage:
  1311. case GPBDataTypeGroup:
  1312. expectedClass = [NSMutableArray class];
  1313. break;
  1314. case GPBDataTypeEnum:
  1315. expectedClass = [GPBEnumArray class];
  1316. break;
  1317. }
  1318. if (array && ![array isKindOfClass:expectedClass]) {
  1319. [NSException raise:NSInvalidArgumentException
  1320. format:@"%@.%@: Expected %@ object, got %@.",
  1321. [self class], field.name, expectedClass, [array class]];
  1322. }
  1323. #endif
  1324. GPBSetObjectIvarWithField(self, field, array);
  1325. }
  1326. static GPBDataType BaseDataType(GPBDataType type) {
  1327. switch (type) {
  1328. case GPBDataTypeSFixed32:
  1329. case GPBDataTypeInt32:
  1330. case GPBDataTypeSInt32:
  1331. case GPBDataTypeEnum:
  1332. return GPBDataTypeInt32;
  1333. case GPBDataTypeFixed32:
  1334. case GPBDataTypeUInt32:
  1335. return GPBDataTypeUInt32;
  1336. case GPBDataTypeSFixed64:
  1337. case GPBDataTypeInt64:
  1338. case GPBDataTypeSInt64:
  1339. return GPBDataTypeInt64;
  1340. case GPBDataTypeFixed64:
  1341. case GPBDataTypeUInt64:
  1342. return GPBDataTypeUInt64;
  1343. case GPBDataTypeMessage:
  1344. case GPBDataTypeGroup:
  1345. return GPBDataTypeMessage;
  1346. case GPBDataTypeBool:
  1347. case GPBDataTypeFloat:
  1348. case GPBDataTypeDouble:
  1349. case GPBDataTypeBytes:
  1350. case GPBDataTypeString:
  1351. return type;
  1352. }
  1353. }
  1354. static BOOL DataTypesEquivalent(GPBDataType type1, GPBDataType type2) {
  1355. return BaseDataType(type1) == BaseDataType(type2);
  1356. }
  1357. static NSString *TypeToString(GPBDataType dataType) {
  1358. switch (dataType) {
  1359. case GPBDataTypeBool:
  1360. return @"Bool";
  1361. case GPBDataTypeSFixed32:
  1362. case GPBDataTypeInt32:
  1363. case GPBDataTypeSInt32:
  1364. return @"Int32";
  1365. case GPBDataTypeFixed32:
  1366. case GPBDataTypeUInt32:
  1367. return @"UInt32";
  1368. case GPBDataTypeSFixed64:
  1369. case GPBDataTypeInt64:
  1370. case GPBDataTypeSInt64:
  1371. return @"Int64";
  1372. case GPBDataTypeFixed64:
  1373. case GPBDataTypeUInt64:
  1374. return @"UInt64";
  1375. case GPBDataTypeFloat:
  1376. return @"Float";
  1377. case GPBDataTypeDouble:
  1378. return @"Double";
  1379. case GPBDataTypeBytes:
  1380. case GPBDataTypeString:
  1381. case GPBDataTypeMessage:
  1382. case GPBDataTypeGroup:
  1383. return @"Object";
  1384. case GPBDataTypeEnum:
  1385. return @"Enum";
  1386. }
  1387. }
  1388. // GPBGetMessageMapField is defined in GPBMessage.m
  1389. // Only exists for public api, no core code should use this.
  1390. void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field,
  1391. id dictionary) {
  1392. #if defined(DEBUG) && DEBUG
  1393. if (field.fieldType != GPBFieldTypeMap) {
  1394. [NSException raise:NSInvalidArgumentException
  1395. format:@"%@.%@ is not a map<> field.",
  1396. [self class], field.name];
  1397. }
  1398. if (dictionary) {
  1399. GPBDataType keyDataType = field.mapKeyDataType;
  1400. GPBDataType valueDataType = GPBGetFieldDataType(field);
  1401. NSString *keyStr = TypeToString(keyDataType);
  1402. NSString *valueStr = TypeToString(valueDataType);
  1403. if (keyDataType == GPBDataTypeString) {
  1404. keyStr = @"String";
  1405. }
  1406. Class expectedClass = Nil;
  1407. if ((keyDataType == GPBDataTypeString) &&
  1408. GPBDataTypeIsObject(valueDataType)) {
  1409. expectedClass = [NSMutableDictionary class];
  1410. } else {
  1411. NSString *className =
  1412. [NSString stringWithFormat:@"GPB%@%@Dictionary", keyStr, valueStr];
  1413. expectedClass = NSClassFromString(className);
  1414. NSCAssert(expectedClass, @"Missing a class (%@)?", expectedClass);
  1415. }
  1416. if (![dictionary isKindOfClass:expectedClass]) {
  1417. [NSException raise:NSInvalidArgumentException
  1418. format:@"%@.%@: Expected %@ object, got %@.",
  1419. [self class], field.name, expectedClass,
  1420. [dictionary class]];
  1421. }
  1422. }
  1423. #endif
  1424. GPBSetObjectIvarWithField(self, field, dictionary);
  1425. }
  1426. #pragma mark - Misc Dynamic Runtime Utils
  1427. const char *GPBMessageEncodingForSelector(SEL selector, BOOL instanceSel) {
  1428. Protocol *protocol =
  1429. objc_getProtocol(GPBStringifySymbol(GPBMessageSignatureProtocol));
  1430. NSCAssert(protocol, @"Missing GPBMessageSignatureProtocol");
  1431. struct objc_method_description description =
  1432. protocol_getMethodDescription(protocol, selector, NO, instanceSel);
  1433. NSCAssert(description.name != Nil && description.types != nil,
  1434. @"Missing method for selector %@", NSStringFromSelector(selector));
  1435. return description.types;
  1436. }
  1437. #pragma mark - Text Format Support
  1438. static void AppendStringEscaped(NSString *toPrint, NSMutableString *destStr) {
  1439. [destStr appendString:@"\""];
  1440. NSUInteger len = [toPrint length];
  1441. for (NSUInteger i = 0; i < len; ++i) {
  1442. unichar aChar = [toPrint characterAtIndex:i];
  1443. switch (aChar) {
  1444. case '\n': [destStr appendString:@"\\n"]; break;
  1445. case '\r': [destStr appendString:@"\\r"]; break;
  1446. case '\t': [destStr appendString:@"\\t"]; break;
  1447. case '\"': [destStr appendString:@"\\\""]; break;
  1448. case '\'': [destStr appendString:@"\\\'"]; break;
  1449. case '\\': [destStr appendString:@"\\\\"]; break;
  1450. default:
  1451. // This differs slightly from the C++ code in that the C++ doesn't
  1452. // generate UTF8; it looks at the string in UTF8, but escapes every
  1453. // byte > 0x7E.
  1454. if (aChar < 0x20) {
  1455. [destStr appendFormat:@"\\%d%d%d",
  1456. (aChar / 64), ((aChar % 64) / 8), (aChar % 8)];
  1457. } else {
  1458. [destStr appendFormat:@"%C", aChar];
  1459. }
  1460. break;
  1461. }
  1462. }
  1463. [destStr appendString:@"\""];
  1464. }
  1465. static void AppendBufferAsString(NSData *buffer, NSMutableString *destStr) {
  1466. const char *src = (const char *)[buffer bytes];
  1467. size_t srcLen = [buffer length];
  1468. [destStr appendString:@"\""];
  1469. for (const char *srcEnd = src + srcLen; src < srcEnd; src++) {
  1470. switch (*src) {
  1471. case '\n': [destStr appendString:@"\\n"]; break;
  1472. case '\r': [destStr appendString:@"\\r"]; break;
  1473. case '\t': [destStr appendString:@"\\t"]; break;
  1474. case '\"': [destStr appendString:@"\\\""]; break;
  1475. case '\'': [destStr appendString:@"\\\'"]; break;
  1476. case '\\': [destStr appendString:@"\\\\"]; break;
  1477. default:
  1478. if (isprint(*src)) {
  1479. [destStr appendFormat:@"%c", *src];
  1480. } else {
  1481. // NOTE: doing hex means you have to worry about the letter after
  1482. // the hex being another hex char and forcing that to be escaped, so
  1483. // use octal to keep it simple.
  1484. [destStr appendFormat:@"\\%03o", (uint8_t)(*src)];
  1485. }
  1486. break;
  1487. }
  1488. }
  1489. [destStr appendString:@"\""];
  1490. }
  1491. static void AppendTextFormatForMapMessageField(
  1492. id map, GPBFieldDescriptor *field, NSMutableString *toStr,
  1493. NSString *lineIndent, NSString *fieldName, NSString *lineEnding) {
  1494. GPBDataType keyDataType = field.mapKeyDataType;
  1495. GPBDataType valueDataType = GPBGetFieldDataType(field);
  1496. BOOL isMessageValue = GPBDataTypeIsMessage(valueDataType);
  1497. NSString *msgStartFirst =
  1498. [NSString stringWithFormat:@"%@%@ {%@\n", lineIndent, fieldName, lineEnding];
  1499. NSString *msgStart =
  1500. [NSString stringWithFormat:@"%@%@ {\n", lineIndent, fieldName];
  1501. NSString *msgEnd = [NSString stringWithFormat:@"%@}\n", lineIndent];
  1502. NSString *keyLine = [NSString stringWithFormat:@"%@ key: ", lineIndent];
  1503. NSString *valueLine = [NSString stringWithFormat:@"%@ value%s ", lineIndent,
  1504. (isMessageValue ? "" : ":")];
  1505. __block BOOL isFirst = YES;
  1506. if ((keyDataType == GPBDataTypeString) &&
  1507. GPBDataTypeIsObject(valueDataType)) {
  1508. // map is an NSDictionary.
  1509. NSDictionary *dict = map;
  1510. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  1511. #pragma unused(stop)
  1512. [toStr appendString:(isFirst ? msgStartFirst : msgStart)];
  1513. isFirst = NO;
  1514. [toStr appendString:keyLine];
  1515. AppendStringEscaped(key, toStr);
  1516. [toStr appendString:@"\n"];
  1517. [toStr appendString:valueLine];
  1518. #pragma clang diagnostic push
  1519. #pragma clang diagnostic ignored "-Wswitch-enum"
  1520. switch (valueDataType) {
  1521. case GPBDataTypeString:
  1522. AppendStringEscaped(value, toStr);
  1523. break;
  1524. case GPBDataTypeBytes:
  1525. AppendBufferAsString(value, toStr);
  1526. break;
  1527. case GPBDataTypeMessage:
  1528. [toStr appendString:@"{\n"];
  1529. NSString *subIndent = [lineIndent stringByAppendingString:@" "];
  1530. AppendTextFormatForMessage(value, toStr, subIndent);
  1531. [toStr appendFormat:@"%@ }", lineIndent];
  1532. break;
  1533. default:
  1534. NSCAssert(NO, @"Can't happen");
  1535. break;
  1536. }
  1537. #pragma clang diagnostic pop
  1538. [toStr appendString:@"\n"];
  1539. [toStr appendString:msgEnd];
  1540. }];
  1541. } else {
  1542. // map is one of the GPB*Dictionary classes, type doesn't matter.
  1543. GPBInt32Int32Dictionary *dict = map;
  1544. [dict enumerateForTextFormat:^(id keyObj, id valueObj) {
  1545. [toStr appendString:(isFirst ? msgStartFirst : msgStart)];
  1546. isFirst = NO;
  1547. // Key always is a NSString.
  1548. if (keyDataType == GPBDataTypeString) {
  1549. [toStr appendString:keyLine];
  1550. AppendStringEscaped(keyObj, toStr);
  1551. [toStr appendString:@"\n"];
  1552. } else {
  1553. [toStr appendFormat:@"%@%@\n", keyLine, keyObj];
  1554. }
  1555. [toStr appendString:valueLine];
  1556. #pragma clang diagnostic push
  1557. #pragma clang diagnostic ignored "-Wswitch-enum"
  1558. switch (valueDataType) {
  1559. case GPBDataTypeString:
  1560. AppendStringEscaped(valueObj, toStr);
  1561. break;
  1562. case GPBDataTypeBytes:
  1563. AppendBufferAsString(valueObj, toStr);
  1564. break;
  1565. case GPBDataTypeMessage:
  1566. [toStr appendString:@"{\n"];
  1567. NSString *subIndent = [lineIndent stringByAppendingString:@" "];
  1568. AppendTextFormatForMessage(valueObj, toStr, subIndent);
  1569. [toStr appendFormat:@"%@ }", lineIndent];
  1570. break;
  1571. case GPBDataTypeEnum: {
  1572. int32_t enumValue = [valueObj intValue];
  1573. NSString *valueStr = nil;
  1574. GPBEnumDescriptor *descriptor = field.enumDescriptor;
  1575. if (descriptor) {
  1576. valueStr = [descriptor textFormatNameForValue:enumValue];
  1577. }
  1578. if (valueStr) {
  1579. [toStr appendString:valueStr];
  1580. } else {
  1581. [toStr appendFormat:@"%d", enumValue];
  1582. }
  1583. break;
  1584. }
  1585. default:
  1586. NSCAssert(valueDataType != GPBDataTypeGroup, @"Can't happen");
  1587. // Everything else is a NSString.
  1588. [toStr appendString:valueObj];
  1589. break;
  1590. }
  1591. #pragma clang diagnostic pop
  1592. [toStr appendString:@"\n"];
  1593. [toStr appendString:msgEnd];
  1594. }];
  1595. }
  1596. }
  1597. static void AppendTextFormatForMessageField(GPBMessage *message,
  1598. GPBFieldDescriptor *field,
  1599. NSMutableString *toStr,
  1600. NSString *lineIndent) {
  1601. id arrayOrMap;
  1602. NSUInteger count;
  1603. GPBFieldType fieldType = field.fieldType;
  1604. switch (fieldType) {
  1605. case GPBFieldTypeSingle:
  1606. arrayOrMap = nil;
  1607. count = (GPBGetHasIvarField(message, field) ? 1 : 0);
  1608. break;
  1609. case GPBFieldTypeRepeated:
  1610. // Will be NSArray or GPB*Array, type doesn't matter, they both
  1611. // implement count.
  1612. arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(message, field);
  1613. count = [(NSArray *)arrayOrMap count];
  1614. break;
  1615. case GPBFieldTypeMap: {
  1616. // Will be GPB*Dictionary or NSMutableDictionary, type doesn't matter,
  1617. // they both implement count.
  1618. arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(message, field);
  1619. count = [(NSDictionary *)arrayOrMap count];
  1620. break;
  1621. }
  1622. }
  1623. if (count == 0) {
  1624. // Nothing to print, out of here.
  1625. return;
  1626. }
  1627. NSString *lineEnding = @"";
  1628. // If the name can't be reversed or support for extra info was turned off,
  1629. // this can return nil.
  1630. NSString *fieldName = [field textFormatName];
  1631. if ([fieldName length] == 0) {
  1632. fieldName = [NSString stringWithFormat:@"%u", GPBFieldNumber(field)];
  1633. // If there is only one entry, put the objc name as a comment, other wise
  1634. // add it before the repeated values.
  1635. if (count > 1) {
  1636. [toStr appendFormat:@"%@# %@\n", lineIndent, field.name];
  1637. } else {
  1638. lineEnding = [NSString stringWithFormat:@" # %@", field.name];
  1639. }
  1640. }
  1641. if (fieldType == GPBFieldTypeMap) {
  1642. AppendTextFormatForMapMessageField(arrayOrMap, field, toStr, lineIndent,
  1643. fieldName, lineEnding);
  1644. return;
  1645. }
  1646. id array = arrayOrMap;
  1647. const BOOL isRepeated = (array != nil);
  1648. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  1649. BOOL isMessageField = GPBDataTypeIsMessage(fieldDataType);
  1650. for (NSUInteger j = 0; j < count; ++j) {
  1651. // Start the line.
  1652. [toStr appendFormat:@"%@%@%s ", lineIndent, fieldName,
  1653. (isMessageField ? "" : ":")];
  1654. // The value.
  1655. switch (fieldDataType) {
  1656. #define FIELD_CASE(GPBDATATYPE, CTYPE, REAL_TYPE, ...) \
  1657. case GPBDataType##GPBDATATYPE: { \
  1658. CTYPE v = (isRepeated ? [(GPB##REAL_TYPE##Array *)array valueAtIndex:j] \
  1659. : GPBGetMessage##REAL_TYPE##Field(message, field)); \
  1660. [toStr appendFormat:__VA_ARGS__, v]; \
  1661. break; \
  1662. }
  1663. FIELD_CASE(Int32, int32_t, Int32, @"%d")
  1664. FIELD_CASE(SInt32, int32_t, Int32, @"%d")
  1665. FIELD_CASE(SFixed32, int32_t, Int32, @"%d")
  1666. FIELD_CASE(UInt32, uint32_t, UInt32, @"%u")
  1667. FIELD_CASE(Fixed32, uint32_t, UInt32, @"%u")
  1668. FIELD_CASE(Int64, int64_t, Int64, @"%lld")
  1669. FIELD_CASE(SInt64, int64_t, Int64, @"%lld")
  1670. FIELD_CASE(SFixed64, int64_t, Int64, @"%lld")
  1671. FIELD_CASE(UInt64, uint64_t, UInt64, @"%llu")
  1672. FIELD_CASE(Fixed64, uint64_t, UInt64, @"%llu")
  1673. FIELD_CASE(Float, float, Float, @"%.*g", FLT_DIG)
  1674. FIELD_CASE(Double, double, Double, @"%.*lg", DBL_DIG)
  1675. #undef FIELD_CASE
  1676. case GPBDataTypeEnum: {
  1677. int32_t v = (isRepeated ? [(GPBEnumArray *)array rawValueAtIndex:j]
  1678. : GPBGetMessageInt32Field(message, field));
  1679. NSString *valueStr = nil;
  1680. GPBEnumDescriptor *descriptor = field.enumDescriptor;
  1681. if (descriptor) {
  1682. valueStr = [descriptor textFormatNameForValue:v];
  1683. }
  1684. if (valueStr) {
  1685. [toStr appendString:valueStr];
  1686. } else {
  1687. [toStr appendFormat:@"%d", v];
  1688. }
  1689. break;
  1690. }
  1691. case GPBDataTypeBool: {
  1692. BOOL v = (isRepeated ? [(GPBBoolArray *)array valueAtIndex:j]
  1693. : GPBGetMessageBoolField(message, field));
  1694. [toStr appendString:(v ? @"true" : @"false")];
  1695. break;
  1696. }
  1697. case GPBDataTypeString: {
  1698. NSString *v = (isRepeated ? [(NSArray *)array objectAtIndex:j]
  1699. : GPBGetMessageStringField(message, field));
  1700. AppendStringEscaped(v, toStr);
  1701. break;
  1702. }
  1703. case GPBDataTypeBytes: {
  1704. NSData *v = (isRepeated ? [(NSArray *)array objectAtIndex:j]
  1705. : GPBGetMessageBytesField(message, field));
  1706. AppendBufferAsString(v, toStr);
  1707. break;
  1708. }
  1709. case GPBDataTypeGroup:
  1710. case GPBDataTypeMessage: {
  1711. GPBMessage *v =
  1712. (isRepeated ? [(NSArray *)array objectAtIndex:j]
  1713. : GPBGetObjectIvarWithField(message, field));
  1714. [toStr appendFormat:@"{%@\n", lineEnding];
  1715. NSString *subIndent = [lineIndent stringByAppendingString:@" "];
  1716. AppendTextFormatForMessage(v, toStr, subIndent);
  1717. [toStr appendFormat:@"%@}", lineIndent];
  1718. lineEnding = @"";
  1719. break;
  1720. }
  1721. } // switch(fieldDataType)
  1722. // End the line.
  1723. [toStr appendFormat:@"%@\n", lineEnding];
  1724. } // for(count)
  1725. }
  1726. static void AppendTextFormatForMessageExtensionRange(GPBMessage *message,
  1727. NSArray *activeExtensions,
  1728. GPBExtensionRange range,
  1729. NSMutableString *toStr,
  1730. NSString *lineIndent) {
  1731. uint32_t start = range.start;
  1732. uint32_t end = range.end;
  1733. for (GPBExtensionDescriptor *extension in activeExtensions) {
  1734. uint32_t fieldNumber = extension.fieldNumber;
  1735. if (fieldNumber < start) {
  1736. // Not there yet.
  1737. continue;
  1738. }
  1739. if (fieldNumber >= end) {
  1740. // Done.
  1741. break;
  1742. }
  1743. id rawExtValue = [message getExtension:extension];
  1744. BOOL isRepeated = extension.isRepeated;
  1745. NSUInteger numValues = 1;
  1746. NSString *lineEnding = @"";
  1747. if (isRepeated) {
  1748. numValues = [(NSArray *)rawExtValue count];
  1749. }
  1750. NSString *singletonName = extension.singletonName;
  1751. if (numValues == 1) {
  1752. lineEnding = [NSString stringWithFormat:@" # [%@]", singletonName];
  1753. } else {
  1754. [toStr appendFormat:@"%@# [%@]\n", lineIndent, singletonName];
  1755. }
  1756. GPBDataType extDataType = extension.dataType;
  1757. for (NSUInteger j = 0; j < numValues; ++j) {
  1758. id curValue = (isRepeated ? [rawExtValue objectAtIndex:j] : rawExtValue);
  1759. // Start the line.
  1760. [toStr appendFormat:@"%@%u%s ", lineIndent, fieldNumber,
  1761. (GPBDataTypeIsMessage(extDataType) ? "" : ":")];
  1762. // The value.
  1763. switch (extDataType) {
  1764. #define FIELD_CASE(GPBDATATYPE, CTYPE, NUMSELECTOR, ...) \
  1765. case GPBDataType##GPBDATATYPE: { \
  1766. CTYPE v = [(NSNumber *)curValue NUMSELECTOR]; \
  1767. [toStr appendFormat:__VA_ARGS__, v]; \
  1768. break; \
  1769. }
  1770. FIELD_CASE(Int32, int32_t, intValue, @"%d")
  1771. FIELD_CASE(SInt32, int32_t, intValue, @"%d")
  1772. FIELD_CASE(SFixed32, int32_t, unsignedIntValue, @"%d")
  1773. FIELD_CASE(UInt32, uint32_t, unsignedIntValue, @"%u")
  1774. FIELD_CASE(Fixed32, uint32_t, unsignedIntValue, @"%u")
  1775. FIELD_CASE(Int64, int64_t, longLongValue, @"%lld")
  1776. FIELD_CASE(SInt64, int64_t, longLongValue, @"%lld")
  1777. FIELD_CASE(SFixed64, int64_t, longLongValue, @"%lld")
  1778. FIELD_CASE(UInt64, uint64_t, unsignedLongLongValue, @"%llu")
  1779. FIELD_CASE(Fixed64, uint64_t, unsignedLongLongValue, @"%llu")
  1780. FIELD_CASE(Float, float, floatValue, @"%.*g", FLT_DIG)
  1781. FIELD_CASE(Double, double, doubleValue, @"%.*lg", DBL_DIG)
  1782. // TODO: Add a comment with the enum name from enum descriptors
  1783. // (might not be real value, so leave it as a comment, ObjC compiler
  1784. // name mangles differently). Doesn't look like we actually generate
  1785. // an enum descriptor reference like we do for normal fields, so this
  1786. // will take a compiler change.
  1787. FIELD_CASE(Enum, int32_t, intValue, @"%d")
  1788. #undef FIELD_CASE
  1789. case GPBDataTypeBool:
  1790. [toStr appendString:([(NSNumber *)curValue boolValue] ? @"true"
  1791. : @"false")];
  1792. break;
  1793. case GPBDataTypeString:
  1794. AppendStringEscaped(curValue, toStr);
  1795. break;
  1796. case GPBDataTypeBytes:
  1797. AppendBufferAsString((NSData *)curValue, toStr);
  1798. break;
  1799. case GPBDataTypeGroup:
  1800. case GPBDataTypeMessage: {
  1801. [toStr appendFormat:@"{%@\n", lineEnding];
  1802. NSString *subIndent = [lineIndent stringByAppendingString:@" "];
  1803. AppendTextFormatForMessage(curValue, toStr, subIndent);
  1804. [toStr appendFormat:@"%@}", lineIndent];
  1805. lineEnding = @"";
  1806. break;
  1807. }
  1808. } // switch(extDataType)
  1809. // End the line.
  1810. [toStr appendFormat:@"%@\n", lineEnding];
  1811. } // for(numValues)
  1812. } // for..in(activeExtensions)
  1813. }
  1814. static void AppendTextFormatForMessage(GPBMessage *message,
  1815. NSMutableString *toStr,
  1816. NSString *lineIndent) {
  1817. GPBDescriptor *descriptor = [message descriptor];
  1818. NSArray *fieldsArray = descriptor->fields_;
  1819. NSUInteger fieldCount = fieldsArray.count;
  1820. const GPBExtensionRange *extensionRanges = descriptor.extensionRanges;
  1821. NSUInteger extensionRangesCount = descriptor.extensionRangesCount;
  1822. NSArray *activeExtensions = [[message extensionsCurrentlySet]
  1823. sortedArrayUsingSelector:@selector(compareByFieldNumber:)];
  1824. for (NSUInteger i = 0, j = 0; i < fieldCount || j < extensionRangesCount;) {
  1825. if (i == fieldCount) {
  1826. AppendTextFormatForMessageExtensionRange(
  1827. message, activeExtensions, extensionRanges[j++], toStr, lineIndent);
  1828. } else if (j == extensionRangesCount ||
  1829. GPBFieldNumber(fieldsArray[i]) < extensionRanges[j].start) {
  1830. AppendTextFormatForMessageField(message, fieldsArray[i++], toStr,
  1831. lineIndent);
  1832. } else {
  1833. AppendTextFormatForMessageExtensionRange(
  1834. message, activeExtensions, extensionRanges[j++], toStr, lineIndent);
  1835. }
  1836. }
  1837. NSString *unknownFieldsStr =
  1838. GPBTextFormatForUnknownFieldSet(message.unknownFields, lineIndent);
  1839. if ([unknownFieldsStr length] > 0) {
  1840. [toStr appendFormat:@"%@# --- Unknown fields ---\n", lineIndent];
  1841. [toStr appendString:unknownFieldsStr];
  1842. }
  1843. }
  1844. NSString *GPBTextFormatForMessage(GPBMessage *message, NSString *lineIndent) {
  1845. if (message == nil) return @"";
  1846. if (lineIndent == nil) lineIndent = @"";
  1847. NSMutableString *buildString = [NSMutableString string];
  1848. AppendTextFormatForMessage(message, buildString, lineIndent);
  1849. return buildString;
  1850. }
  1851. NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *unknownSet,
  1852. NSString *lineIndent) {
  1853. if (unknownSet == nil) return @"";
  1854. if (lineIndent == nil) lineIndent = @"";
  1855. NSMutableString *result = [NSMutableString string];
  1856. for (GPBUnknownField *field in [unknownSet sortedFields]) {
  1857. int32_t fieldNumber = [field number];
  1858. #define PRINT_LOOP(PROPNAME, CTYPE, FORMAT) \
  1859. [field.PROPNAME \
  1860. enumerateValuesWithBlock:^(CTYPE value, NSUInteger idx, BOOL * stop) { \
  1861. _Pragma("unused(idx, stop)"); \
  1862. [result \
  1863. appendFormat:@"%@%d: " #FORMAT "\n", lineIndent, fieldNumber, value]; \
  1864. }];
  1865. PRINT_LOOP(varintList, uint64_t, %llu);
  1866. PRINT_LOOP(fixed32List, uint32_t, 0x%X);
  1867. PRINT_LOOP(fixed64List, uint64_t, 0x%llX);
  1868. #undef PRINT_LOOP
  1869. // NOTE: C++ version of TextFormat tries to parse this as a message
  1870. // and print that if it succeeds.
  1871. for (NSData *data in field.lengthDelimitedList) {
  1872. [result appendFormat:@"%@%d: ", lineIndent, fieldNumber];
  1873. AppendBufferAsString(data, result);
  1874. [result appendString:@"\n"];
  1875. }
  1876. for (GPBUnknownFieldSet *subUnknownSet in field.groupList) {
  1877. [result appendFormat:@"%@%d: {\n", lineIndent, fieldNumber];
  1878. NSString *subIndent = [lineIndent stringByAppendingString:@" "];
  1879. NSString *subUnknwonSetStr =
  1880. GPBTextFormatForUnknownFieldSet(subUnknownSet, subIndent);
  1881. [result appendString:subUnknwonSetStr];
  1882. [result appendFormat:@"%@}\n", lineIndent];
  1883. }
  1884. }
  1885. return result;
  1886. }
  1887. // Helpers to decode a varint. Not using GPBCodedInputStream version because
  1888. // that needs a state object, and we don't want to create an input stream out
  1889. // of the data.
  1890. GPB_INLINE int8_t ReadRawByteFromData(const uint8_t **data) {
  1891. int8_t result = *((int8_t *)(*data));
  1892. ++(*data);
  1893. return result;
  1894. }
  1895. static int32_t ReadRawVarint32FromData(const uint8_t **data) {
  1896. int8_t tmp = ReadRawByteFromData(data);
  1897. if (tmp >= 0) {
  1898. return tmp;
  1899. }
  1900. int32_t result = tmp & 0x7f;
  1901. if ((tmp = ReadRawByteFromData(data)) >= 0) {
  1902. result |= tmp << 7;
  1903. } else {
  1904. result |= (tmp & 0x7f) << 7;
  1905. if ((tmp = ReadRawByteFromData(data)) >= 0) {
  1906. result |= tmp << 14;
  1907. } else {
  1908. result |= (tmp & 0x7f) << 14;
  1909. if ((tmp = ReadRawByteFromData(data)) >= 0) {
  1910. result |= tmp << 21;
  1911. } else {
  1912. result |= (tmp & 0x7f) << 21;
  1913. result |= (tmp = ReadRawByteFromData(data)) << 28;
  1914. if (tmp < 0) {
  1915. // Discard upper 32 bits.
  1916. for (int i = 0; i < 5; i++) {
  1917. if (ReadRawByteFromData(data) >= 0) {
  1918. return result;
  1919. }
  1920. }
  1921. [NSException raise:NSParseErrorException
  1922. format:@"Unable to read varint32"];
  1923. }
  1924. }
  1925. }
  1926. }
  1927. return result;
  1928. }
  1929. NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key,
  1930. NSString *inputStr) {
  1931. // decodData form:
  1932. // varint32: num entries
  1933. // for each entry:
  1934. // varint32: key
  1935. // bytes*: decode data
  1936. //
  1937. // decode data one of two forms:
  1938. // 1: a \0 followed by the string followed by an \0
  1939. // 2: bytecodes to transform an input into the right thing, ending with \0
  1940. //
  1941. // the bytes codes are of the form:
  1942. // 0xabbccccc
  1943. // 0x0 (all zeros), end.
  1944. // a - if set, add an underscore
  1945. // bb - 00 ccccc bytes as is
  1946. // bb - 10 ccccc upper first, as is on rest, ccccc byte total
  1947. // bb - 01 ccccc lower first, as is on rest, ccccc byte total
  1948. // bb - 11 ccccc all upper, ccccc byte total
  1949. if (!decodeData || !inputStr) {
  1950. return nil;
  1951. }
  1952. // Find key
  1953. const uint8_t *scan = decodeData;
  1954. int32_t numEntries = ReadRawVarint32FromData(&scan);
  1955. BOOL foundKey = NO;
  1956. while (!foundKey && (numEntries > 0)) {
  1957. --numEntries;
  1958. int32_t dataKey = ReadRawVarint32FromData(&scan);
  1959. if (dataKey == key) {
  1960. foundKey = YES;
  1961. } else {
  1962. // If it is a inlined string, it will start with \0; if it is bytecode it
  1963. // will start with a code. So advance one (skipping the inline string
  1964. // marker), and then loop until reaching the end marker (\0).
  1965. ++scan;
  1966. while (*scan != 0) ++scan;
  1967. // Now move past the end marker.
  1968. ++scan;
  1969. }
  1970. }
  1971. if (!foundKey) {
  1972. return nil;
  1973. }
  1974. // Decode
  1975. if (*scan == 0) {
  1976. // Inline string. Move over the marker, and NSString can take it as
  1977. // UTF8.
  1978. ++scan;
  1979. NSString *result = [NSString stringWithUTF8String:(const char *)scan];
  1980. return result;
  1981. }
  1982. NSMutableString *result =
  1983. [NSMutableString stringWithCapacity:[inputStr length]];
  1984. const uint8_t kAddUnderscore = 0b10000000;
  1985. const uint8_t kOpMask = 0b01100000;
  1986. // const uint8_t kOpAsIs = 0b00000000;
  1987. const uint8_t kOpFirstUpper = 0b01000000;
  1988. const uint8_t kOpFirstLower = 0b00100000;
  1989. const uint8_t kOpAllUpper = 0b01100000;
  1990. const uint8_t kSegmentLenMask = 0b00011111;
  1991. NSInteger i = 0;
  1992. for (; *scan != 0; ++scan) {
  1993. if (*scan & kAddUnderscore) {
  1994. [result appendString:@"_"];
  1995. }
  1996. int segmentLen = *scan & kSegmentLenMask;
  1997. uint8_t decodeOp = *scan & kOpMask;
  1998. // Do op specific handling of the first character.
  1999. if (decodeOp == kOpFirstUpper) {
  2000. unichar c = [inputStr characterAtIndex:i];
  2001. [result appendFormat:@"%c", toupper((char)c)];
  2002. ++i;
  2003. --segmentLen;
  2004. } else if (decodeOp == kOpFirstLower) {
  2005. unichar c = [inputStr characterAtIndex:i];
  2006. [result appendFormat:@"%c", tolower((char)c)];
  2007. ++i;
  2008. --segmentLen;
  2009. }
  2010. // else op == kOpAsIs || op == kOpAllUpper
  2011. // Now pull over the rest of the length for this segment.
  2012. for (int x = 0; x < segmentLen; ++x) {
  2013. unichar c = [inputStr characterAtIndex:(i + x)];
  2014. if (decodeOp == kOpAllUpper) {
  2015. [result appendFormat:@"%c", toupper((char)c)];
  2016. } else {
  2017. [result appendFormat:@"%C", c];
  2018. }
  2019. }
  2020. i += segmentLen;
  2021. }
  2022. return result;
  2023. }
  2024. #pragma clang diagnostic pop
  2025. BOOL GPBClassHasSel(Class aClass, SEL sel) {
  2026. // NOTE: We have to use class_copyMethodList, all other runtime method
  2027. // lookups actually also resolve the method implementation and this
  2028. // is called from within those methods.
  2029. BOOL result = NO;
  2030. unsigned int methodCount = 0;
  2031. Method *methodList = class_copyMethodList(aClass, &methodCount);
  2032. for (unsigned int i = 0; i < methodCount; ++i) {
  2033. SEL methodSelector = method_getName(methodList[i]);
  2034. if (methodSelector == sel) {
  2035. result = YES;
  2036. break;
  2037. }
  2038. }
  2039. free(methodList);
  2040. return result;
  2041. }