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

GPBUtilities.m 82KB

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