GPBUtilities.m 87 KB

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