GPBUtilities.m 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731
  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. NSData *GPBEmptyNSData(void) {
  47. static dispatch_once_t onceToken;
  48. static NSData *defaultNSData = nil;
  49. dispatch_once(&onceToken, ^{
  50. defaultNSData = [[NSData alloc] init];
  51. });
  52. return defaultNSData;
  53. }
  54. void GPBCheckRuntimeVersionInternal(int32_t version) {
  55. if (version != GOOGLE_PROTOBUF_OBJC_GEN_VERSION) {
  56. [NSException raise:NSInternalInconsistencyException
  57. format:@"Linked to ProtocolBuffer runtime version %d,"
  58. @" but code compiled with version %d!",
  59. GOOGLE_PROTOBUF_OBJC_GEN_VERSION, version];
  60. }
  61. }
  62. BOOL GPBMessageHasFieldNumberSet(GPBMessage *self, uint32_t fieldNumber) {
  63. GPBDescriptor *descriptor = [self descriptor];
  64. GPBFieldDescriptor *field = [descriptor fieldWithNumber:fieldNumber];
  65. return GPBMessageHasFieldSet(self, field);
  66. }
  67. BOOL GPBMessageHasFieldSet(GPBMessage *self, GPBFieldDescriptor *field) {
  68. if (self == nil || field == nil) return NO;
  69. // Repeated/Map don't use the bit, they check the count.
  70. if (GPBFieldIsMapOrArray(field)) {
  71. // Array/map type doesn't matter, since GPB*Array/NSArray and
  72. // GPB*Dictionary/NSDictionary all support -count;
  73. NSArray *arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  74. return (arrayOrMap.count > 0);
  75. } else {
  76. return GPBGetHasIvarField(self, field);
  77. }
  78. }
  79. void GPBClearMessageField(GPBMessage *self, GPBFieldDescriptor *field) {
  80. // If not set, nothing to do.
  81. if (!GPBGetHasIvarField(self, field)) {
  82. return;
  83. }
  84. if (GPBFieldStoresObject(field)) {
  85. // Object types are handled slightly differently, they need to be released.
  86. uint8_t *storage = (uint8_t *)self->messageStorage_;
  87. id *typePtr = (id *)&storage[field->description_->offset];
  88. [*typePtr release];
  89. *typePtr = nil;
  90. } else {
  91. // POD types just need to clear the has bit as the Get* method will
  92. // fetch the default when needed.
  93. }
  94. GPBSetHasIvarField(self, field, NO);
  95. }
  96. BOOL GPBGetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber) {
  97. NSCAssert(self->messageStorage_ != NULL,
  98. @"%@: All messages should have storage (from init)",
  99. [self class]);
  100. if (idx < 0) {
  101. NSCAssert(fieldNumber != 0, @"Invalid field number.");
  102. BOOL hasIvar = (self->messageStorage_->_has_storage_[-idx] == fieldNumber);
  103. return hasIvar;
  104. } else {
  105. NSCAssert(idx != GPBNoHasBit, @"Invalid has bit.");
  106. uint32_t byteIndex = idx / 32;
  107. uint32_t bitMask = (1 << (idx % 32));
  108. BOOL hasIvar =
  109. (self->messageStorage_->_has_storage_[byteIndex] & bitMask) ? YES : NO;
  110. return hasIvar;
  111. }
  112. }
  113. uint32_t GPBGetHasOneof(GPBMessage *self, int32_t idx) {
  114. NSCAssert(idx < 0, @"%@: invalid index (%d) for oneof.",
  115. [self class], idx);
  116. uint32_t result = self->messageStorage_->_has_storage_[-idx];
  117. return result;
  118. }
  119. void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber,
  120. BOOL value) {
  121. if (idx < 0) {
  122. NSCAssert(fieldNumber != 0, @"Invalid field number.");
  123. uint32_t *has_storage = self->messageStorage_->_has_storage_;
  124. has_storage[-idx] = (value ? fieldNumber : 0);
  125. } else {
  126. NSCAssert(idx != GPBNoHasBit, @"Invalid has bit.");
  127. uint32_t *has_storage = self->messageStorage_->_has_storage_;
  128. uint32_t byte = idx / 32;
  129. uint32_t bitMask = (1 << (idx % 32));
  130. if (value) {
  131. has_storage[byte] |= bitMask;
  132. } else {
  133. has_storage[byte] &= ~bitMask;
  134. }
  135. }
  136. }
  137. void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
  138. int32_t oneofHasIndex, uint32_t fieldNumberNotToClear) {
  139. uint32_t fieldNumberSet = GPBGetHasOneof(self, oneofHasIndex);
  140. if ((fieldNumberSet == fieldNumberNotToClear) || (fieldNumberSet == 0)) {
  141. // Do nothing/nothing set in the oneof.
  142. return;
  143. }
  144. // Like GPBClearMessageField(), free the memory if an objecttype is set,
  145. // pod types don't need to do anything.
  146. GPBFieldDescriptor *fieldSet = [oneof fieldWithNumber:fieldNumberSet];
  147. NSCAssert(fieldSet,
  148. @"%@: oneof set to something (%u) not in the oneof?",
  149. [self class], fieldNumberSet);
  150. if (fieldSet && GPBFieldStoresObject(fieldSet)) {
  151. uint8_t *storage = (uint8_t *)self->messageStorage_;
  152. id *typePtr = (id *)&storage[fieldSet->description_->offset];
  153. [*typePtr release];
  154. *typePtr = nil;
  155. }
  156. // Set to nothing stored in the oneof.
  157. // (field number doesn't matter since setting to nothing).
  158. GPBSetHasIvar(self, oneofHasIndex, 1, NO);
  159. }
  160. #pragma mark - IVar accessors
  161. //%PDDM-DEFINE IVAR_POD_ACCESSORS_DEFN(NAME, TYPE)
  162. //%TYPE GPBGetMessage##NAME##Field(GPBMessage *self,
  163. //% TYPE$S NAME$S GPBFieldDescriptor *field) {
  164. //% if (GPBGetHasIvarField(self, field)) {
  165. //% uint8_t *storage = (uint8_t *)self->messageStorage_;
  166. //% TYPE *typePtr = (TYPE *)&storage[field->description_->offset];
  167. //% return *typePtr;
  168. //% } else {
  169. //% return field.defaultValue.value##NAME;
  170. //% }
  171. //%}
  172. //%
  173. //%// Only exists for public api, no core code should use this.
  174. //%void GPBSetMessage##NAME##Field(GPBMessage *self,
  175. //% NAME$S GPBFieldDescriptor *field,
  176. //% NAME$S TYPE value) {
  177. //% if (self == nil || field == nil) return;
  178. //% GPBFileSyntax syntax = [self descriptor].file.syntax;
  179. //% GPBSet##NAME##IvarWithFieldInternal(self, field, value, syntax);
  180. //%}
  181. //%
  182. //%void GPBSet##NAME##IvarWithFieldInternal(GPBMessage *self,
  183. //% NAME$S GPBFieldDescriptor *field,
  184. //% NAME$S TYPE value,
  185. //% NAME$S GPBFileSyntax syntax) {
  186. //% GPBOneofDescriptor *oneof = field->containingOneof_;
  187. //% if (oneof) {
  188. //% GPBMessageFieldDescription *fieldDesc = field->description_;
  189. //% GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  190. //% }
  191. //% NSCAssert(self->messageStorage_ != NULL,
  192. //% @"%@: All messages should have storage (from init)",
  193. //% [self class]);
  194. //%#if defined(__clang_analyzer__)
  195. //% if (self->messageStorage_ == NULL) return;
  196. //%#endif
  197. //% uint8_t *storage = (uint8_t *)self->messageStorage_;
  198. //% TYPE *typePtr = (TYPE *)&storage[field->description_->offset];
  199. //% *typePtr = value;
  200. //% // proto2: any value counts as having been set; proto3, it
  201. //% // has to be a non zero value.
  202. //% BOOL hasValue =
  203. //% (syntax == GPBFileSyntaxProto2) || (value != (TYPE)0);
  204. //% GPBSetHasIvarField(self, field, hasValue);
  205. //% GPBBecomeVisibleToAutocreator(self);
  206. //%}
  207. //%
  208. //%PDDM-DEFINE IVAR_ALIAS_DEFN_OBJECT(NAME, TYPE)
  209. //%// Only exists for public api, no core code should use this.
  210. //%TYPE *GPBGetMessage##NAME##Field(GPBMessage *self,
  211. //% TYPE$S NAME$S GPBFieldDescriptor *field) {
  212. //% return (TYPE *)GPBGetObjectIvarWithField(self, field);
  213. //%}
  214. //%
  215. //%// Only exists for public api, no core code should use this.
  216. //%void GPBSetMessage##NAME##Field(GPBMessage *self,
  217. //% NAME$S GPBFieldDescriptor *field,
  218. //% NAME$S TYPE *value) {
  219. //% GPBSetObjectIvarWithField(self, field, (id)value);
  220. //%}
  221. //%
  222. // Object types are handled slightly differently, they need to be released
  223. // and retained.
  224. void GPBSetAutocreatedRetainedObjectIvarWithField(
  225. GPBMessage *self, GPBFieldDescriptor *field,
  226. id __attribute__((ns_consumed)) value) {
  227. uint8_t *storage = (uint8_t *)self->messageStorage_;
  228. id *typePtr = (id *)&storage[field->description_->offset];
  229. NSCAssert(*typePtr == NULL, @"Can't set autocreated object more than once.");
  230. *typePtr = value;
  231. }
  232. void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self,
  233. GPBFieldDescriptor *field) {
  234. if (GPBGetHasIvarField(self, field)) {
  235. return;
  236. }
  237. uint8_t *storage = (uint8_t *)self->messageStorage_;
  238. id *typePtr = (id *)&storage[field->description_->offset];
  239. GPBMessage *oldValue = *typePtr;
  240. *typePtr = NULL;
  241. GPBClearMessageAutocreator(oldValue);
  242. [oldValue release];
  243. }
  244. // This exists only for briging some aliased types, nothing else should use it.
  245. static void GPBSetObjectIvarWithField(GPBMessage *self,
  246. GPBFieldDescriptor *field, id value) {
  247. if (self == nil || field == nil) return;
  248. GPBFileSyntax syntax = [self descriptor].file.syntax;
  249. GPBSetRetainedObjectIvarWithFieldInternal(self, field, [value retain],
  250. syntax);
  251. }
  252. void GPBSetObjectIvarWithFieldInternal(GPBMessage *self,
  253. GPBFieldDescriptor *field, id value,
  254. GPBFileSyntax syntax) {
  255. GPBSetRetainedObjectIvarWithFieldInternal(self, field, [value retain],
  256. syntax);
  257. }
  258. void GPBSetRetainedObjectIvarWithFieldInternal(GPBMessage *self,
  259. GPBFieldDescriptor *field,
  260. id value, GPBFileSyntax syntax) {
  261. NSCAssert(self->messageStorage_ != NULL,
  262. @"%@: All messages should have storage (from init)",
  263. [self class]);
  264. #if defined(__clang_analyzer__)
  265. if (self->messageStorage_ == NULL) return;
  266. #endif
  267. GPBDataType fieldType = GPBGetFieldDataType(field);
  268. BOOL isMapOrArray = GPBFieldIsMapOrArray(field);
  269. BOOL fieldIsMessage = GPBDataTypeIsMessage(fieldType);
  270. #ifdef DEBUG
  271. if (value == nil && !isMapOrArray && !fieldIsMessage &&
  272. field.hasDefaultValue) {
  273. // Setting a message to nil is an obvious way to "clear" the value
  274. // as there is no way to set a non-empty default value for messages.
  275. //
  276. // For Strings and Bytes that have default values set it is not clear what
  277. // should be done when their value is set to nil. Is the intention just to
  278. // clear the set value and reset to default, or is the intention to set the
  279. // value to the empty string/data? Arguments can be made for both cases.
  280. // 'nil' has been abused as a replacement for an empty string/data in ObjC.
  281. // We decided to be consistent with all "object" types and clear the has
  282. // field, and fall back on the default value. The warning below will only
  283. // appear in debug, but the could should be changed so the intention is
  284. // clear.
  285. NSString *hasSel = NSStringFromSelector(field->hasOrCountSel_);
  286. NSString *propName = field.name;
  287. NSString *className = self.descriptor.name;
  288. NSLog(@"warning: '%@.%@ = nil;' is not clearly defined for fields with "
  289. @"default values. Please use '%@.%@ = %@' if you want to set it to "
  290. @"empty, or call '%@.%@ = NO' to reset it to it's default value of "
  291. @"'%@'. Defaulting to resetting default value.",
  292. className, propName, className, propName,
  293. (fieldType == GPBDataTypeString) ? @"@\"\"" : @"GPBEmptyNSData()",
  294. className, hasSel, field.defaultValue.valueString);
  295. // Note: valueString, depending on the type, it could easily be
  296. // valueData/valueMessage.
  297. }
  298. #endif // DEBUG
  299. if (!isMapOrArray) {
  300. // Non repeated/map can be in an oneof, clear any existing value from the
  301. // oneof.
  302. GPBOneofDescriptor *oneof = field->containingOneof_;
  303. if (oneof) {
  304. GPBMessageFieldDescription *fieldDesc = field->description_;
  305. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  306. }
  307. // Clear "has" if they are being set to nil.
  308. BOOL setHasValue = (value != nil);
  309. // Under proto3, Bytes & String fields get cleared by resetting them to
  310. // their default (empty) values, so if they are set to something of length
  311. // zero, they are being cleared.
  312. if ((syntax == GPBFileSyntaxProto3) && !fieldIsMessage &&
  313. ([value length] == 0)) {
  314. setHasValue = NO;
  315. value = nil;
  316. }
  317. GPBSetHasIvarField(self, field, setHasValue);
  318. }
  319. uint8_t *storage = (uint8_t *)self->messageStorage_;
  320. id *typePtr = (id *)&storage[field->description_->offset];
  321. id oldValue = *typePtr;
  322. *typePtr = value;
  323. if (oldValue) {
  324. if (isMapOrArray) {
  325. if (field.fieldType == GPBFieldTypeRepeated) {
  326. // If the old array was autocreated by us, then clear it.
  327. if (GPBDataTypeIsObject(fieldType)) {
  328. GPBAutocreatedArray *autoArray = oldValue;
  329. if (autoArray->_autocreator == self) {
  330. autoArray->_autocreator = nil;
  331. }
  332. } else {
  333. // Type doesn't matter, it is a GPB*Array.
  334. GPBInt32Array *gpbArray = oldValue;
  335. if (gpbArray->_autocreator == self) {
  336. gpbArray->_autocreator = nil;
  337. }
  338. }
  339. } else { // GPBFieldTypeMap
  340. // If the old map was autocreated by us, then clear it.
  341. if ((field.mapKeyDataType == GPBDataTypeString) &&
  342. GPBDataTypeIsObject(fieldType)) {
  343. GPBAutocreatedDictionary *autoDict = oldValue;
  344. if (autoDict->_autocreator == self) {
  345. autoDict->_autocreator = nil;
  346. }
  347. } else {
  348. // Type doesn't matter, it is a GPB*Dictionary.
  349. GPBInt32Int32Dictionary *gpbDict = oldValue;
  350. if (gpbDict->_autocreator == self) {
  351. gpbDict->_autocreator = nil;
  352. }
  353. }
  354. }
  355. } else if (fieldIsMessage) {
  356. // If the old message value was autocreated by us, then clear it.
  357. GPBMessage *oldMessageValue = oldValue;
  358. if (GPBWasMessageAutocreatedBy(oldMessageValue, self)) {
  359. GPBClearMessageAutocreator(oldMessageValue);
  360. }
  361. }
  362. [oldValue release];
  363. }
  364. GPBBecomeVisibleToAutocreator(self);
  365. }
  366. id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self,
  367. GPBFieldDescriptor *field) {
  368. if (self->messageStorage_ == nil) {
  369. return nil;
  370. }
  371. uint8_t *storage = (uint8_t *)self->messageStorage_;
  372. id *typePtr = (id *)&storage[field->description_->offset];
  373. return *typePtr;
  374. }
  375. id GPBGetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
  376. NSCAssert(!GPBFieldIsMapOrArray(field), @"Shouldn't get here");
  377. if (GPBGetHasIvarField(self, field)) {
  378. uint8_t *storage = (uint8_t *)self->messageStorage_;
  379. id *typePtr = (id *)&storage[field->description_->offset];
  380. return *typePtr;
  381. }
  382. // Not set...
  383. // Non messages (string/data), get their default.
  384. if (!GPBFieldDataTypeIsMessage(field)) {
  385. return field.defaultValue.valueMessage;
  386. }
  387. GPBPrepareReadOnlySemaphore(self);
  388. dispatch_semaphore_wait(self->readOnlySemaphore_, DISPATCH_TIME_FOREVER);
  389. GPBMessage *result = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
  390. if (!result) {
  391. // For non repeated messages, create the object, set it and return it.
  392. // This object will not initially be visible via GPBGetHasIvar, so
  393. // we save its creator so it can become visible if it's mutated later.
  394. result = GPBCreateMessageWithAutocreator(field.msgClass, self, field);
  395. GPBSetAutocreatedRetainedObjectIvarWithField(self, field, result);
  396. }
  397. dispatch_semaphore_signal(self->readOnlySemaphore_);
  398. return result;
  399. }
  400. // Only exists for public api, no core code should use this.
  401. int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field) {
  402. GPBFileSyntax syntax = [self descriptor].file.syntax;
  403. return GPBGetEnumIvarWithFieldInternal(self, field, syntax);
  404. }
  405. int32_t GPBGetEnumIvarWithFieldInternal(GPBMessage *self,
  406. GPBFieldDescriptor *field,
  407. GPBFileSyntax syntax) {
  408. int32_t result = GPBGetMessageInt32Field(self, field);
  409. // If this is presevering unknown enums, make sure the value is valid before
  410. // returning it.
  411. if (GPBHasPreservingUnknownEnumSemantics(syntax) &&
  412. ![field isValidEnumValue:result]) {
  413. result = kGPBUnrecognizedEnumeratorValue;
  414. }
  415. return result;
  416. }
  417. // Only exists for public api, no core code should use this.
  418. void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field,
  419. int32_t value) {
  420. GPBFileSyntax syntax = [self descriptor].file.syntax;
  421. GPBSetInt32IvarWithFieldInternal(self, field, value, syntax);
  422. }
  423. void GPBSetEnumIvarWithFieldInternal(GPBMessage *self,
  424. GPBFieldDescriptor *field, int32_t value,
  425. GPBFileSyntax syntax) {
  426. // Don't allow in unknown values. Proto3 can use the Raw method.
  427. if (![field isValidEnumValue:value]) {
  428. [NSException raise:NSInvalidArgumentException
  429. format:@"%@.%@: Attempt to set an unknown enum value (%d)",
  430. [self class], field.name, value];
  431. }
  432. GPBSetInt32IvarWithFieldInternal(self, field, value, syntax);
  433. }
  434. // Only exists for public api, no core code should use this.
  435. int32_t GPBGetMessageRawEnumField(GPBMessage *self,
  436. GPBFieldDescriptor *field) {
  437. int32_t result = GPBGetMessageInt32Field(self, field);
  438. return result;
  439. }
  440. // Only exists for public api, no core code should use this.
  441. void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field,
  442. int32_t value) {
  443. GPBFileSyntax syntax = [self descriptor].file.syntax;
  444. GPBSetInt32IvarWithFieldInternal(self, field, value, syntax);
  445. }
  446. BOOL GPBGetMessageBoolField(GPBMessage *self,
  447. GPBFieldDescriptor *field) {
  448. if (GPBGetHasIvarField(self, field)) {
  449. // Bools are stored in the has bits to avoid needing explicit space in the
  450. // storage structure.
  451. // (the field number passed to the HasIvar helper doesn't really matter
  452. // since the offset is never negative)
  453. GPBMessageFieldDescription *fieldDesc = field->description_;
  454. return GPBGetHasIvar(self, (int32_t)(fieldDesc->offset), fieldDesc->number);
  455. } else {
  456. return field.defaultValue.valueBool;
  457. }
  458. }
  459. // Only exists for public api, no core code should use this.
  460. void GPBSetMessageBoolField(GPBMessage *self,
  461. GPBFieldDescriptor *field,
  462. BOOL value) {
  463. if (self == nil || field == nil) return;
  464. GPBFileSyntax syntax = [self descriptor].file.syntax;
  465. GPBSetBoolIvarWithFieldInternal(self, field, value, syntax);
  466. }
  467. void GPBSetBoolIvarWithFieldInternal(GPBMessage *self,
  468. GPBFieldDescriptor *field,
  469. BOOL value,
  470. GPBFileSyntax syntax) {
  471. GPBMessageFieldDescription *fieldDesc = field->description_;
  472. GPBOneofDescriptor *oneof = field->containingOneof_;
  473. if (oneof) {
  474. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  475. }
  476. // Bools are stored in the has bits to avoid needing explicit space in the
  477. // storage structure.
  478. // (the field number passed to the HasIvar helper doesn't really matter since
  479. // the offset is never negative)
  480. GPBSetHasIvar(self, (int32_t)(fieldDesc->offset), fieldDesc->number, value);
  481. // proto2: any value counts as having been set; proto3, it
  482. // has to be a non zero value.
  483. BOOL hasValue =
  484. (syntax == GPBFileSyntaxProto2) || (value != (BOOL)0);
  485. GPBSetHasIvarField(self, field, hasValue);
  486. GPBBecomeVisibleToAutocreator(self);
  487. }
  488. //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Int32, int32_t)
  489. // This block of code is generated, do not edit it directly.
  490. int32_t GPBGetMessageInt32Field(GPBMessage *self,
  491. GPBFieldDescriptor *field) {
  492. if (GPBGetHasIvarField(self, field)) {
  493. uint8_t *storage = (uint8_t *)self->messageStorage_;
  494. int32_t *typePtr = (int32_t *)&storage[field->description_->offset];
  495. return *typePtr;
  496. } else {
  497. return field.defaultValue.valueInt32;
  498. }
  499. }
  500. // Only exists for public api, no core code should use this.
  501. void GPBSetMessageInt32Field(GPBMessage *self,
  502. GPBFieldDescriptor *field,
  503. int32_t value) {
  504. if (self == nil || field == nil) return;
  505. GPBFileSyntax syntax = [self descriptor].file.syntax;
  506. GPBSetInt32IvarWithFieldInternal(self, field, value, syntax);
  507. }
  508. void GPBSetInt32IvarWithFieldInternal(GPBMessage *self,
  509. GPBFieldDescriptor *field,
  510. int32_t value,
  511. GPBFileSyntax syntax) {
  512. GPBOneofDescriptor *oneof = field->containingOneof_;
  513. if (oneof) {
  514. GPBMessageFieldDescription *fieldDesc = field->description_;
  515. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  516. }
  517. NSCAssert(self->messageStorage_ != NULL,
  518. @"%@: All messages should have storage (from init)",
  519. [self class]);
  520. #if defined(__clang_analyzer__)
  521. if (self->messageStorage_ == NULL) return;
  522. #endif
  523. uint8_t *storage = (uint8_t *)self->messageStorage_;
  524. int32_t *typePtr = (int32_t *)&storage[field->description_->offset];
  525. *typePtr = value;
  526. // proto2: any value counts as having been set; proto3, it
  527. // has to be a non zero value.
  528. BOOL hasValue =
  529. (syntax == GPBFileSyntaxProto2) || (value != (int32_t)0);
  530. GPBSetHasIvarField(self, field, hasValue);
  531. GPBBecomeVisibleToAutocreator(self);
  532. }
  533. //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(UInt32, uint32_t)
  534. // This block of code is generated, do not edit it directly.
  535. uint32_t GPBGetMessageUInt32Field(GPBMessage *self,
  536. GPBFieldDescriptor *field) {
  537. if (GPBGetHasIvarField(self, field)) {
  538. uint8_t *storage = (uint8_t *)self->messageStorage_;
  539. uint32_t *typePtr = (uint32_t *)&storage[field->description_->offset];
  540. return *typePtr;
  541. } else {
  542. return field.defaultValue.valueUInt32;
  543. }
  544. }
  545. // Only exists for public api, no core code should use this.
  546. void GPBSetMessageUInt32Field(GPBMessage *self,
  547. GPBFieldDescriptor *field,
  548. uint32_t value) {
  549. if (self == nil || field == nil) return;
  550. GPBFileSyntax syntax = [self descriptor].file.syntax;
  551. GPBSetUInt32IvarWithFieldInternal(self, field, value, syntax);
  552. }
  553. void GPBSetUInt32IvarWithFieldInternal(GPBMessage *self,
  554. GPBFieldDescriptor *field,
  555. uint32_t value,
  556. GPBFileSyntax syntax) {
  557. GPBOneofDescriptor *oneof = field->containingOneof_;
  558. if (oneof) {
  559. GPBMessageFieldDescription *fieldDesc = field->description_;
  560. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  561. }
  562. NSCAssert(self->messageStorage_ != NULL,
  563. @"%@: All messages should have storage (from init)",
  564. [self class]);
  565. #if defined(__clang_analyzer__)
  566. if (self->messageStorage_ == NULL) return;
  567. #endif
  568. uint8_t *storage = (uint8_t *)self->messageStorage_;
  569. uint32_t *typePtr = (uint32_t *)&storage[field->description_->offset];
  570. *typePtr = value;
  571. // proto2: any value counts as having been set; proto3, it
  572. // has to be a non zero value.
  573. BOOL hasValue =
  574. (syntax == GPBFileSyntaxProto2) || (value != (uint32_t)0);
  575. GPBSetHasIvarField(self, field, hasValue);
  576. GPBBecomeVisibleToAutocreator(self);
  577. }
  578. //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Int64, int64_t)
  579. // This block of code is generated, do not edit it directly.
  580. int64_t GPBGetMessageInt64Field(GPBMessage *self,
  581. GPBFieldDescriptor *field) {
  582. if (GPBGetHasIvarField(self, field)) {
  583. uint8_t *storage = (uint8_t *)self->messageStorage_;
  584. int64_t *typePtr = (int64_t *)&storage[field->description_->offset];
  585. return *typePtr;
  586. } else {
  587. return field.defaultValue.valueInt64;
  588. }
  589. }
  590. // Only exists for public api, no core code should use this.
  591. void GPBSetMessageInt64Field(GPBMessage *self,
  592. GPBFieldDescriptor *field,
  593. int64_t value) {
  594. if (self == nil || field == nil) return;
  595. GPBFileSyntax syntax = [self descriptor].file.syntax;
  596. GPBSetInt64IvarWithFieldInternal(self, field, value, syntax);
  597. }
  598. void GPBSetInt64IvarWithFieldInternal(GPBMessage *self,
  599. GPBFieldDescriptor *field,
  600. int64_t value,
  601. GPBFileSyntax syntax) {
  602. GPBOneofDescriptor *oneof = field->containingOneof_;
  603. if (oneof) {
  604. GPBMessageFieldDescription *fieldDesc = field->description_;
  605. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  606. }
  607. NSCAssert(self->messageStorage_ != NULL,
  608. @"%@: All messages should have storage (from init)",
  609. [self class]);
  610. #if defined(__clang_analyzer__)
  611. if (self->messageStorage_ == NULL) return;
  612. #endif
  613. uint8_t *storage = (uint8_t *)self->messageStorage_;
  614. int64_t *typePtr = (int64_t *)&storage[field->description_->offset];
  615. *typePtr = value;
  616. // proto2: any value counts as having been set; proto3, it
  617. // has to be a non zero value.
  618. BOOL hasValue =
  619. (syntax == GPBFileSyntaxProto2) || (value != (int64_t)0);
  620. GPBSetHasIvarField(self, field, hasValue);
  621. GPBBecomeVisibleToAutocreator(self);
  622. }
  623. //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(UInt64, uint64_t)
  624. // This block of code is generated, do not edit it directly.
  625. uint64_t GPBGetMessageUInt64Field(GPBMessage *self,
  626. GPBFieldDescriptor *field) {
  627. if (GPBGetHasIvarField(self, field)) {
  628. uint8_t *storage = (uint8_t *)self->messageStorage_;
  629. uint64_t *typePtr = (uint64_t *)&storage[field->description_->offset];
  630. return *typePtr;
  631. } else {
  632. return field.defaultValue.valueUInt64;
  633. }
  634. }
  635. // Only exists for public api, no core code should use this.
  636. void GPBSetMessageUInt64Field(GPBMessage *self,
  637. GPBFieldDescriptor *field,
  638. uint64_t value) {
  639. if (self == nil || field == nil) return;
  640. GPBFileSyntax syntax = [self descriptor].file.syntax;
  641. GPBSetUInt64IvarWithFieldInternal(self, field, value, syntax);
  642. }
  643. void GPBSetUInt64IvarWithFieldInternal(GPBMessage *self,
  644. GPBFieldDescriptor *field,
  645. uint64_t value,
  646. GPBFileSyntax syntax) {
  647. GPBOneofDescriptor *oneof = field->containingOneof_;
  648. if (oneof) {
  649. GPBMessageFieldDescription *fieldDesc = field->description_;
  650. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  651. }
  652. NSCAssert(self->messageStorage_ != NULL,
  653. @"%@: All messages should have storage (from init)",
  654. [self class]);
  655. #if defined(__clang_analyzer__)
  656. if (self->messageStorage_ == NULL) return;
  657. #endif
  658. uint8_t *storage = (uint8_t *)self->messageStorage_;
  659. uint64_t *typePtr = (uint64_t *)&storage[field->description_->offset];
  660. *typePtr = value;
  661. // proto2: any value counts as having been set; proto3, it
  662. // has to be a non zero value.
  663. BOOL hasValue =
  664. (syntax == GPBFileSyntaxProto2) || (value != (uint64_t)0);
  665. GPBSetHasIvarField(self, field, hasValue);
  666. GPBBecomeVisibleToAutocreator(self);
  667. }
  668. //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Float, float)
  669. // This block of code is generated, do not edit it directly.
  670. float GPBGetMessageFloatField(GPBMessage *self,
  671. GPBFieldDescriptor *field) {
  672. if (GPBGetHasIvarField(self, field)) {
  673. uint8_t *storage = (uint8_t *)self->messageStorage_;
  674. float *typePtr = (float *)&storage[field->description_->offset];
  675. return *typePtr;
  676. } else {
  677. return field.defaultValue.valueFloat;
  678. }
  679. }
  680. // Only exists for public api, no core code should use this.
  681. void GPBSetMessageFloatField(GPBMessage *self,
  682. GPBFieldDescriptor *field,
  683. float value) {
  684. if (self == nil || field == nil) return;
  685. GPBFileSyntax syntax = [self descriptor].file.syntax;
  686. GPBSetFloatIvarWithFieldInternal(self, field, value, syntax);
  687. }
  688. void GPBSetFloatIvarWithFieldInternal(GPBMessage *self,
  689. GPBFieldDescriptor *field,
  690. float value,
  691. GPBFileSyntax syntax) {
  692. GPBOneofDescriptor *oneof = field->containingOneof_;
  693. if (oneof) {
  694. GPBMessageFieldDescription *fieldDesc = field->description_;
  695. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  696. }
  697. NSCAssert(self->messageStorage_ != NULL,
  698. @"%@: All messages should have storage (from init)",
  699. [self class]);
  700. #if defined(__clang_analyzer__)
  701. if (self->messageStorage_ == NULL) return;
  702. #endif
  703. uint8_t *storage = (uint8_t *)self->messageStorage_;
  704. float *typePtr = (float *)&storage[field->description_->offset];
  705. *typePtr = value;
  706. // proto2: any value counts as having been set; proto3, it
  707. // has to be a non zero value.
  708. BOOL hasValue =
  709. (syntax == GPBFileSyntaxProto2) || (value != (float)0);
  710. GPBSetHasIvarField(self, field, hasValue);
  711. GPBBecomeVisibleToAutocreator(self);
  712. }
  713. //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Double, double)
  714. // This block of code is generated, do not edit it directly.
  715. double GPBGetMessageDoubleField(GPBMessage *self,
  716. GPBFieldDescriptor *field) {
  717. if (GPBGetHasIvarField(self, field)) {
  718. uint8_t *storage = (uint8_t *)self->messageStorage_;
  719. double *typePtr = (double *)&storage[field->description_->offset];
  720. return *typePtr;
  721. } else {
  722. return field.defaultValue.valueDouble;
  723. }
  724. }
  725. // Only exists for public api, no core code should use this.
  726. void GPBSetMessageDoubleField(GPBMessage *self,
  727. GPBFieldDescriptor *field,
  728. double value) {
  729. if (self == nil || field == nil) return;
  730. GPBFileSyntax syntax = [self descriptor].file.syntax;
  731. GPBSetDoubleIvarWithFieldInternal(self, field, value, syntax);
  732. }
  733. void GPBSetDoubleIvarWithFieldInternal(GPBMessage *self,
  734. GPBFieldDescriptor *field,
  735. double value,
  736. GPBFileSyntax syntax) {
  737. GPBOneofDescriptor *oneof = field->containingOneof_;
  738. if (oneof) {
  739. GPBMessageFieldDescription *fieldDesc = field->description_;
  740. GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
  741. }
  742. NSCAssert(self->messageStorage_ != NULL,
  743. @"%@: All messages should have storage (from init)",
  744. [self class]);
  745. #if defined(__clang_analyzer__)
  746. if (self->messageStorage_ == NULL) return;
  747. #endif
  748. uint8_t *storage = (uint8_t *)self->messageStorage_;
  749. double *typePtr = (double *)&storage[field->description_->offset];
  750. *typePtr = value;
  751. // proto2: any value counts as having been set; proto3, it
  752. // has to be a non zero value.
  753. BOOL hasValue =
  754. (syntax == GPBFileSyntaxProto2) || (value != (double)0);
  755. GPBSetHasIvarField(self, field, hasValue);
  756. GPBBecomeVisibleToAutocreator(self);
  757. }
  758. //%PDDM-EXPAND-END (6 expansions)
  759. // Aliases are function calls that are virtually the same.
  760. //%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(String, NSString)
  761. // This block of code is generated, do not edit it directly.
  762. // Only exists for public api, no core code should use this.
  763. NSString *GPBGetMessageStringField(GPBMessage *self,
  764. GPBFieldDescriptor *field) {
  765. return (NSString *)GPBGetObjectIvarWithField(self, field);
  766. }
  767. // Only exists for public api, no core code should use this.
  768. void GPBSetMessageStringField(GPBMessage *self,
  769. GPBFieldDescriptor *field,
  770. NSString *value) {
  771. GPBSetObjectIvarWithField(self, field, (id)value);
  772. }
  773. //%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Bytes, NSData)
  774. // This block of code is generated, do not edit it directly.
  775. // Only exists for public api, no core code should use this.
  776. NSData *GPBGetMessageBytesField(GPBMessage *self,
  777. GPBFieldDescriptor *field) {
  778. return (NSData *)GPBGetObjectIvarWithField(self, field);
  779. }
  780. // Only exists for public api, no core code should use this.
  781. void GPBSetMessageBytesField(GPBMessage *self,
  782. GPBFieldDescriptor *field,
  783. NSData *value) {
  784. GPBSetObjectIvarWithField(self, field, (id)value);
  785. }
  786. //%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Message, GPBMessage)
  787. // This block of code is generated, do not edit it directly.
  788. // Only exists for public api, no core code should use this.
  789. GPBMessage *GPBGetMessageMessageField(GPBMessage *self,
  790. GPBFieldDescriptor *field) {
  791. return (GPBMessage *)GPBGetObjectIvarWithField(self, field);
  792. }
  793. // Only exists for public api, no core code should use this.
  794. void GPBSetMessageMessageField(GPBMessage *self,
  795. GPBFieldDescriptor *field,
  796. GPBMessage *value) {
  797. GPBSetObjectIvarWithField(self, field, (id)value);
  798. }
  799. //%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Group, GPBMessage)
  800. // This block of code is generated, do not edit it directly.
  801. // Only exists for public api, no core code should use this.
  802. GPBMessage *GPBGetMessageGroupField(GPBMessage *self,
  803. GPBFieldDescriptor *field) {
  804. return (GPBMessage *)GPBGetObjectIvarWithField(self, field);
  805. }
  806. // Only exists for public api, no core code should use this.
  807. void GPBSetMessageGroupField(GPBMessage *self,
  808. GPBFieldDescriptor *field,
  809. GPBMessage *value) {
  810. GPBSetObjectIvarWithField(self, field, (id)value);
  811. }
  812. //%PDDM-EXPAND-END (4 expansions)
  813. // Only exists for public api, no core code should use this.
  814. id GPBGetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field) {
  815. #if defined(DEBUG) && DEBUG
  816. if (field.fieldType != GPBFieldTypeRepeated) {
  817. [NSException raise:NSInvalidArgumentException
  818. format:@"%@.%@ is not a repeated field.",
  819. [self class], field.name];
  820. }
  821. #endif
  822. return GPBGetObjectIvarWithField(self, field);
  823. }
  824. // Only exists for public api, no core code should use this.
  825. void GPBSetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field, id array) {
  826. #if defined(DEBUG) && DEBUG
  827. if (field.fieldType != GPBFieldTypeRepeated) {
  828. [NSException raise:NSInvalidArgumentException
  829. format:@"%@.%@ is not a repeated field.",
  830. [self class], field.name];
  831. }
  832. Class expectedClass = Nil;
  833. switch (GPBGetFieldDataType(field)) {
  834. case GPBDataTypeBool:
  835. expectedClass = [GPBBoolArray class];
  836. break;
  837. case GPBDataTypeSFixed32:
  838. case GPBDataTypeInt32:
  839. case GPBDataTypeSInt32:
  840. expectedClass = [GPBInt32Array class];
  841. break;
  842. case GPBDataTypeFixed32:
  843. case GPBDataTypeUInt32:
  844. expectedClass = [GPBUInt32Array class];
  845. break;
  846. case GPBDataTypeSFixed64:
  847. case GPBDataTypeInt64:
  848. case GPBDataTypeSInt64:
  849. expectedClass = [GPBInt64Array class];
  850. break;
  851. case GPBDataTypeFixed64:
  852. case GPBDataTypeUInt64:
  853. expectedClass = [GPBUInt64Array class];
  854. break;
  855. case GPBDataTypeFloat:
  856. expectedClass = [GPBFloatArray class];
  857. break;
  858. case GPBDataTypeDouble:
  859. expectedClass = [GPBDoubleArray class];
  860. break;
  861. case GPBDataTypeBytes:
  862. case GPBDataTypeString:
  863. case GPBDataTypeMessage:
  864. case GPBDataTypeGroup:
  865. expectedClass = [NSMutableArray class];
  866. break;
  867. case GPBDataTypeEnum:
  868. expectedClass = [GPBEnumArray class];
  869. break;
  870. }
  871. if (array && ![array isKindOfClass:expectedClass]) {
  872. [NSException raise:NSInvalidArgumentException
  873. format:@"%@.%@: Expected %@ object, got %@.",
  874. [self class], field.name, expectedClass, [array class]];
  875. }
  876. #endif
  877. GPBSetObjectIvarWithField(self, field, array);
  878. }
  879. #if defined(DEBUG) && DEBUG
  880. static NSString *TypeToStr(GPBDataType dataType) {
  881. switch (dataType) {
  882. case GPBDataTypeBool:
  883. return @"Bool";
  884. case GPBDataTypeSFixed32:
  885. case GPBDataTypeInt32:
  886. case GPBDataTypeSInt32:
  887. return @"Int32";
  888. case GPBDataTypeFixed32:
  889. case GPBDataTypeUInt32:
  890. return @"UInt32";
  891. case GPBDataTypeSFixed64:
  892. case GPBDataTypeInt64:
  893. case GPBDataTypeSInt64:
  894. return @"Int64";
  895. case GPBDataTypeFixed64:
  896. case GPBDataTypeUInt64:
  897. return @"UInt64";
  898. case GPBDataTypeFloat:
  899. return @"Float";
  900. case GPBDataTypeDouble:
  901. return @"Double";
  902. case GPBDataTypeBytes:
  903. case GPBDataTypeString:
  904. case GPBDataTypeMessage:
  905. case GPBDataTypeGroup:
  906. return @"Object";
  907. case GPBDataTypeEnum:
  908. return @"Bool";
  909. }
  910. }
  911. #endif
  912. // Only exists for public api, no core code should use this.
  913. id GPBGetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field) {
  914. #if defined(DEBUG) && DEBUG
  915. if (field.fieldType != GPBFieldTypeMap) {
  916. [NSException raise:NSInvalidArgumentException
  917. format:@"%@.%@ is not a map<> field.",
  918. [self class], field.name];
  919. }
  920. #endif
  921. return GPBGetObjectIvarWithField(self, field);
  922. }
  923. // Only exists for public api, no core code should use this.
  924. void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field,
  925. id dictionary) {
  926. #if defined(DEBUG) && DEBUG
  927. if (field.fieldType != GPBFieldTypeMap) {
  928. [NSException raise:NSInvalidArgumentException
  929. format:@"%@.%@ is not a map<> field.",
  930. [self class], field.name];
  931. }
  932. if (dictionary) {
  933. GPBDataType keyDataType = field.mapKeyDataType;
  934. GPBDataType valueDataType = GPBGetFieldDataType(field);
  935. NSString *keyStr = TypeToStr(keyDataType);
  936. NSString *valueStr = TypeToStr(valueDataType);
  937. if (keyDataType == GPBDataTypeString) {
  938. keyStr = @"String";
  939. }
  940. Class expectedClass = Nil;
  941. if ((keyDataType == GPBDataTypeString) &&
  942. GPBDataTypeIsObject(valueDataType)) {
  943. expectedClass = [NSMutableDictionary class];
  944. } else {
  945. NSString *className =
  946. [NSString stringWithFormat:@"GPB%@%@Dictionary", keyStr, valueStr];
  947. expectedClass = NSClassFromString(className);
  948. NSCAssert(expectedClass, @"Missing a class (%@)?", expectedClass);
  949. }
  950. if (![dictionary isKindOfClass:expectedClass]) {
  951. [NSException raise:NSInvalidArgumentException
  952. format:@"%@.%@: Expected %@ object, got %@.",
  953. [self class], field.name, expectedClass,
  954. [dictionary class]];
  955. }
  956. }
  957. #endif
  958. GPBSetObjectIvarWithField(self, field, dictionary);
  959. }
  960. #pragma mark - Misc Dynamic Runtime Utils
  961. const char *GPBMessageEncodingForSelector(SEL selector, BOOL instanceSel) {
  962. Protocol *protocol =
  963. objc_getProtocol(GPBStringifySymbol(GPBMessageSignatureProtocol));
  964. struct objc_method_description description =
  965. protocol_getMethodDescription(protocol, selector, NO, instanceSel);
  966. return description.types;
  967. }
  968. #pragma mark - Text Format Support
  969. static void AppendStringEscaped(NSString *toPrint, NSMutableString *destStr) {
  970. [destStr appendString:@"\""];
  971. NSUInteger len = [toPrint length];
  972. for (NSUInteger i = 0; i < len; ++i) {
  973. unichar aChar = [toPrint characterAtIndex:i];
  974. switch (aChar) {
  975. case '\n': [destStr appendString:@"\\n"]; break;
  976. case '\r': [destStr appendString:@"\\r"]; break;
  977. case '\t': [destStr appendString:@"\\t"]; break;
  978. case '\"': [destStr appendString:@"\\\""]; break;
  979. case '\'': [destStr appendString:@"\\\'"]; break;
  980. case '\\': [destStr appendString:@"\\\\"]; break;
  981. default:
  982. [destStr appendFormat:@"%C", aChar];
  983. break;
  984. }
  985. }
  986. [destStr appendString:@"\""];
  987. }
  988. static void AppendBufferAsString(NSData *buffer, NSMutableString *destStr) {
  989. const char *src = (const char *)[buffer bytes];
  990. size_t srcLen = [buffer length];
  991. [destStr appendString:@"\""];
  992. for (const char *srcEnd = src + srcLen; src < srcEnd; src++) {
  993. switch (*src) {
  994. case '\n': [destStr appendString:@"\\n"]; break;
  995. case '\r': [destStr appendString:@"\\r"]; break;
  996. case '\t': [destStr appendString:@"\\t"]; break;
  997. case '\"': [destStr appendString:@"\\\""]; break;
  998. case '\'': [destStr appendString:@"\\\'"]; break;
  999. case '\\': [destStr appendString:@"\\\\"]; break;
  1000. default:
  1001. if (isprint(*src)) {
  1002. [destStr appendFormat:@"%c", *src];
  1003. } else {
  1004. // NOTE: doing hex means you have to worry about the letter after
  1005. // the hex being another hex char and forcing that to be escaped, so
  1006. // use octal to keep it simple.
  1007. [destStr appendFormat:@"\\%03o", (uint8_t)(*src)];
  1008. }
  1009. break;
  1010. }
  1011. }
  1012. [destStr appendString:@"\""];
  1013. }
  1014. static void AppendTextFormatForMapMessageField(
  1015. id map, GPBFieldDescriptor *field, NSMutableString *toStr,
  1016. NSString *lineIndent, NSString *fieldName, NSString *lineEnding) {
  1017. GPBDataType keyDataType = field.mapKeyDataType;
  1018. GPBDataType valueDataType = GPBGetFieldDataType(field);
  1019. BOOL isMessageValue = GPBDataTypeIsMessage(valueDataType);
  1020. NSString *msgStartFirst =
  1021. [NSString stringWithFormat:@"%@%@ {%@\n", lineIndent, fieldName, lineEnding];
  1022. NSString *msgStart =
  1023. [NSString stringWithFormat:@"%@%@ {\n", lineIndent, fieldName];
  1024. NSString *msgEnd = [NSString stringWithFormat:@"%@}\n", lineIndent];
  1025. NSString *keyLine = [NSString stringWithFormat:@"%@ key: ", lineIndent];
  1026. NSString *valueLine = [NSString stringWithFormat:@"%@ value%s ", lineIndent,
  1027. (isMessageValue ? "" : ":")];
  1028. __block BOOL isFirst = YES;
  1029. if ((keyDataType == GPBDataTypeString) &&
  1030. GPBDataTypeIsObject(valueDataType)) {
  1031. // map is an NSDictionary.
  1032. NSDictionary *dict = map;
  1033. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  1034. #pragma unused(stop)
  1035. [toStr appendString:(isFirst ? msgStartFirst : msgStart)];
  1036. isFirst = NO;
  1037. [toStr appendString:keyLine];
  1038. AppendStringEscaped(key, toStr);
  1039. [toStr appendString:@"\n"];
  1040. [toStr appendString:valueLine];
  1041. #pragma clang diagnostic push
  1042. #pragma clang diagnostic ignored "-Wswitch-enum"
  1043. switch (valueDataType) {
  1044. case GPBDataTypeString:
  1045. AppendStringEscaped(value, toStr);
  1046. break;
  1047. case GPBDataTypeBytes:
  1048. AppendBufferAsString(value, toStr);
  1049. break;
  1050. case GPBDataTypeMessage:
  1051. [toStr appendString:@"{\n"];
  1052. NSString *subIndent = [lineIndent stringByAppendingString:@" "];
  1053. AppendTextFormatForMessage(value, toStr, subIndent);
  1054. [toStr appendFormat:@"%@ }", lineIndent];
  1055. break;
  1056. default:
  1057. NSCAssert(NO, @"Can't happen");
  1058. break;
  1059. }
  1060. #pragma clang diagnostic pop
  1061. [toStr appendString:@"\n"];
  1062. [toStr appendString:msgEnd];
  1063. }];
  1064. } else {
  1065. // map is one of the GPB*Dictionary classes, type doesn't matter.
  1066. GPBInt32Int32Dictionary *dict = map;
  1067. [dict enumerateForTextFormat:^(id keyObj, id valueObj) {
  1068. [toStr appendString:(isFirst ? msgStartFirst : msgStart)];
  1069. isFirst = NO;
  1070. // Key always is a NSString.
  1071. if (keyDataType == GPBDataTypeString) {
  1072. [toStr appendString:keyLine];
  1073. AppendStringEscaped(keyObj, toStr);
  1074. [toStr appendString:@"\n"];
  1075. } else {
  1076. [toStr appendFormat:@"%@%@\n", keyLine, keyObj];
  1077. }
  1078. [toStr appendString:valueLine];
  1079. #pragma clang diagnostic push
  1080. #pragma clang diagnostic ignored "-Wswitch-enum"
  1081. switch (valueDataType) {
  1082. case GPBDataTypeString:
  1083. AppendStringEscaped(valueObj, toStr);
  1084. break;
  1085. case GPBDataTypeBytes:
  1086. AppendBufferAsString(valueObj, toStr);
  1087. break;
  1088. case GPBDataTypeMessage:
  1089. [toStr appendString:@"{\n"];
  1090. NSString *subIndent = [lineIndent stringByAppendingString:@" "];
  1091. AppendTextFormatForMessage(valueObj, toStr, subIndent);
  1092. [toStr appendFormat:@"%@ }", lineIndent];
  1093. break;
  1094. case GPBDataTypeEnum: {
  1095. int32_t enumValue = [valueObj intValue];
  1096. NSString *valueStr = nil;
  1097. GPBEnumDescriptor *descriptor = field.enumDescriptor;
  1098. if (descriptor) {
  1099. valueStr = [descriptor textFormatNameForValue:enumValue];
  1100. }
  1101. if (valueStr) {
  1102. [toStr appendString:valueStr];
  1103. } else {
  1104. [toStr appendFormat:@"%d", enumValue];
  1105. }
  1106. break;
  1107. }
  1108. default:
  1109. NSCAssert(valueDataType != GPBDataTypeGroup, @"Can't happen");
  1110. // Everything else is a NSString.
  1111. [toStr appendString:valueObj];
  1112. break;
  1113. }
  1114. #pragma clang diagnostic pop
  1115. [toStr appendString:@"\n"];
  1116. [toStr appendString:msgEnd];
  1117. }];
  1118. }
  1119. }
  1120. static void AppendTextFormatForMessageField(GPBMessage *message,
  1121. GPBFieldDescriptor *field,
  1122. NSMutableString *toStr,
  1123. NSString *lineIndent) {
  1124. id arrayOrMap;
  1125. NSUInteger count;
  1126. GPBFieldType fieldType = field.fieldType;
  1127. switch (fieldType) {
  1128. case GPBFieldTypeSingle:
  1129. arrayOrMap = nil;
  1130. count = (GPBGetHasIvarField(message, field) ? 1 : 0);
  1131. break;
  1132. case GPBFieldTypeRepeated:
  1133. // Will be NSArray or GPB*Array, type doesn't matter, they both
  1134. // implement count.
  1135. arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(message, field);
  1136. count = [(NSArray *)arrayOrMap count];
  1137. break;
  1138. case GPBFieldTypeMap: {
  1139. // Will be GPB*Dictionary or NSMutableDictionary, type doesn't matter,
  1140. // they both implement count.
  1141. arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(message, field);
  1142. count = [(NSDictionary *)arrayOrMap count];
  1143. break;
  1144. }
  1145. }
  1146. if (count == 0) {
  1147. // Nothing to print, out of here.
  1148. return;
  1149. }
  1150. NSString *lineEnding = @"";
  1151. // If the name can't be reversed or support for extra info was turned off,
  1152. // this can return nil.
  1153. NSString *fieldName = [field textFormatName];
  1154. if ([fieldName length] == 0) {
  1155. fieldName = [NSString stringWithFormat:@"%u", GPBFieldNumber(field)];
  1156. // If there is only one entry, put the objc name as a comment, other wise
  1157. // add it before the repeated values.
  1158. if (count > 1) {
  1159. [toStr appendFormat:@"%@# %@\n", lineIndent, field.name];
  1160. } else {
  1161. lineEnding = [NSString stringWithFormat:@" # %@", field.name];
  1162. }
  1163. }
  1164. if (fieldType == GPBFieldTypeMap) {
  1165. AppendTextFormatForMapMessageField(arrayOrMap, field, toStr, lineIndent,
  1166. fieldName, lineEnding);
  1167. return;
  1168. }
  1169. id array = arrayOrMap;
  1170. const BOOL isRepeated = (array != nil);
  1171. GPBDataType fieldDataType = GPBGetFieldDataType(field);
  1172. BOOL isMessageField = GPBDataTypeIsMessage(fieldDataType);
  1173. for (NSUInteger j = 0; j < count; ++j) {
  1174. // Start the line.
  1175. [toStr appendFormat:@"%@%@%s ", lineIndent, fieldName,
  1176. (isMessageField ? "" : ":")];
  1177. // The value.
  1178. switch (fieldDataType) {
  1179. #define FIELD_CASE(GPBDATATYPE, CTYPE, REAL_TYPE, ...) \
  1180. case GPBDataType##GPBDATATYPE: { \
  1181. CTYPE v = (isRepeated ? [(GPB##REAL_TYPE##Array *)array valueAtIndex:j] \
  1182. : GPBGetMessage##REAL_TYPE##Field(message, field)); \
  1183. [toStr appendFormat:__VA_ARGS__, v]; \
  1184. break; \
  1185. }
  1186. FIELD_CASE(Int32, int32_t, Int32, @"%d")
  1187. FIELD_CASE(SInt32, int32_t, Int32, @"%d")
  1188. FIELD_CASE(SFixed32, int32_t, Int32, @"%d")
  1189. FIELD_CASE(UInt32, uint32_t, UInt32, @"%u")
  1190. FIELD_CASE(Fixed32, uint32_t, UInt32, @"%u")
  1191. FIELD_CASE(Int64, int64_t, Int64, @"%lld")
  1192. FIELD_CASE(SInt64, int64_t, Int64, @"%lld")
  1193. FIELD_CASE(SFixed64, int64_t, Int64, @"%lld")
  1194. FIELD_CASE(UInt64, uint64_t, UInt64, @"%llu")
  1195. FIELD_CASE(Fixed64, uint64_t, UInt64, @"%llu")
  1196. FIELD_CASE(Float, float, Float, @"%.*g", FLT_DIG)
  1197. FIELD_CASE(Double, double, Double, @"%.*lg", DBL_DIG)
  1198. #undef FIELD_CASE
  1199. case GPBDataTypeEnum: {
  1200. int32_t v = (isRepeated ? [(GPBEnumArray *)array rawValueAtIndex:j]
  1201. : GPBGetMessageInt32Field(message, field));
  1202. NSString *valueStr = nil;
  1203. GPBEnumDescriptor *descriptor = field.enumDescriptor;
  1204. if (descriptor) {
  1205. valueStr = [descriptor textFormatNameForValue:v];
  1206. }
  1207. if (valueStr) {
  1208. [toStr appendString:valueStr];
  1209. } else {
  1210. [toStr appendFormat:@"%d", v];
  1211. }
  1212. break;
  1213. }
  1214. case GPBDataTypeBool: {
  1215. BOOL v = (isRepeated ? [(GPBBoolArray *)array valueAtIndex:j]
  1216. : GPBGetMessageBoolField(message, field));
  1217. [toStr appendString:(v ? @"true" : @"false")];
  1218. break;
  1219. }
  1220. case GPBDataTypeString: {
  1221. NSString *v = (isRepeated ? [(NSArray *)array objectAtIndex:j]
  1222. : GPBGetMessageStringField(message, field));
  1223. AppendStringEscaped(v, toStr);
  1224. break;
  1225. }
  1226. case GPBDataTypeBytes: {
  1227. NSData *v = (isRepeated ? [(NSArray *)array objectAtIndex:j]
  1228. : GPBGetMessageBytesField(message, field));
  1229. AppendBufferAsString(v, toStr);
  1230. break;
  1231. }
  1232. case GPBDataTypeGroup:
  1233. case GPBDataTypeMessage: {
  1234. GPBMessage *v =
  1235. (isRepeated ? [(NSArray *)array objectAtIndex:j]
  1236. : GPBGetObjectIvarWithField(message, field));
  1237. [toStr appendFormat:@"{%@\n", lineEnding];
  1238. NSString *subIndent = [lineIndent stringByAppendingString:@" "];
  1239. AppendTextFormatForMessage(v, toStr, subIndent);
  1240. [toStr appendFormat:@"%@}", lineIndent];
  1241. lineEnding = @"";
  1242. break;
  1243. }
  1244. } // switch(fieldDataType)
  1245. // End the line.
  1246. [toStr appendFormat:@"%@\n", lineEnding];
  1247. } // for(count)
  1248. }
  1249. static void AppendTextFormatForMessageExtensionRange(GPBMessage *message,
  1250. NSArray *activeExtensions,
  1251. GPBExtensionRange range,
  1252. NSMutableString *toStr,
  1253. NSString *lineIndent) {
  1254. uint32_t start = range.start;
  1255. uint32_t end = range.end;
  1256. for (GPBExtensionDescriptor *extension in activeExtensions) {
  1257. uint32_t fieldNumber = extension.fieldNumber;
  1258. if (fieldNumber < start) {
  1259. // Not there yet.
  1260. continue;
  1261. }
  1262. if (fieldNumber > end) {
  1263. // Done.
  1264. break;
  1265. }
  1266. id rawExtValue = [message getExtension:extension];
  1267. BOOL isRepeated = extension.isRepeated;
  1268. NSUInteger numValues = 1;
  1269. NSString *lineEnding = @"";
  1270. if (isRepeated) {
  1271. numValues = [(NSArray *)rawExtValue count];
  1272. }
  1273. NSString *singletonName = extension.singletonName;
  1274. if (numValues == 1) {
  1275. lineEnding = [NSString stringWithFormat:@" # [%@]", singletonName];
  1276. } else {
  1277. [toStr appendFormat:@"%@# [%@]\n", lineIndent, singletonName];
  1278. }
  1279. GPBDataType extDataType = extension.dataType;
  1280. for (NSUInteger j = 0; j < numValues; ++j) {
  1281. id curValue = (isRepeated ? [rawExtValue objectAtIndex:j] : rawExtValue);
  1282. // Start the line.
  1283. [toStr appendFormat:@"%@%u%s ", lineIndent, fieldNumber,
  1284. (GPBDataTypeIsMessage(extDataType) ? "" : ":")];
  1285. // The value.
  1286. switch (extDataType) {
  1287. #define FIELD_CASE(GPBDATATYPE, CTYPE, NUMSELECTOR, ...) \
  1288. case GPBDataType##GPBDATATYPE: { \
  1289. CTYPE v = [(NSNumber *)curValue NUMSELECTOR]; \
  1290. [toStr appendFormat:__VA_ARGS__, v]; \
  1291. break; \
  1292. }
  1293. FIELD_CASE(Int32, int32_t, intValue, @"%d")
  1294. FIELD_CASE(SInt32, int32_t, intValue, @"%d")
  1295. FIELD_CASE(SFixed32, int32_t, unsignedIntValue, @"%d")
  1296. FIELD_CASE(UInt32, uint32_t, unsignedIntValue, @"%u")
  1297. FIELD_CASE(Fixed32, uint32_t, unsignedIntValue, @"%u")
  1298. FIELD_CASE(Int64, int64_t, longLongValue, @"%lld")
  1299. FIELD_CASE(SInt64, int64_t, longLongValue, @"%lld")
  1300. FIELD_CASE(SFixed64, int64_t, longLongValue, @"%lld")
  1301. FIELD_CASE(UInt64, uint64_t, unsignedLongLongValue, @"%llu")
  1302. FIELD_CASE(Fixed64, uint64_t, unsignedLongLongValue, @"%llu")
  1303. FIELD_CASE(Float, float, floatValue, @"%.*g", FLT_DIG)
  1304. FIELD_CASE(Double, double, doubleValue, @"%.*lg", DBL_DIG)
  1305. // TODO: Add a comment with the enum name from enum descriptors
  1306. // (might not be real value, so leave it as a comment, ObjC compiler
  1307. // name mangles differently). Doesn't look like we actually generate
  1308. // an enum descriptor reference like we do for normal fields, so this
  1309. // will take a compiler change.
  1310. FIELD_CASE(Enum, int32_t, intValue, @"%d")
  1311. #undef FIELD_CASE
  1312. case GPBDataTypeBool:
  1313. [toStr appendString:([(NSNumber *)curValue boolValue] ? @"true"
  1314. : @"false")];
  1315. break;
  1316. case GPBDataTypeString:
  1317. AppendStringEscaped(curValue, toStr);
  1318. break;
  1319. case GPBDataTypeBytes:
  1320. AppendBufferAsString((NSData *)curValue, toStr);
  1321. break;
  1322. case GPBDataTypeGroup:
  1323. case GPBDataTypeMessage: {
  1324. [toStr appendFormat:@"{%@\n", lineEnding];
  1325. NSString *subIndent = [lineIndent stringByAppendingString:@" "];
  1326. AppendTextFormatForMessage(curValue, toStr, subIndent);
  1327. [toStr appendFormat:@"%@}", lineIndent];
  1328. lineEnding = @"";
  1329. break;
  1330. }
  1331. } // switch(extDataType)
  1332. } // for(numValues)
  1333. // End the line.
  1334. [toStr appendFormat:@"%@\n", lineEnding];
  1335. } // for..in(activeExtensions)
  1336. }
  1337. static void AppendTextFormatForMessage(GPBMessage *message,
  1338. NSMutableString *toStr,
  1339. NSString *lineIndent) {
  1340. GPBDescriptor *descriptor = [message descriptor];
  1341. NSArray *fieldsArray = descriptor->fields_;
  1342. NSUInteger fieldCount = fieldsArray.count;
  1343. const GPBExtensionRange *extensionRanges = descriptor.extensionRanges;
  1344. NSUInteger extensionRangesCount = descriptor.extensionRangesCount;
  1345. NSArray *activeExtensions = [message sortedExtensionsInUse];
  1346. for (NSUInteger i = 0, j = 0; i < fieldCount || j < extensionRangesCount;) {
  1347. if (i == fieldCount) {
  1348. AppendTextFormatForMessageExtensionRange(
  1349. message, activeExtensions, extensionRanges[j++], toStr, lineIndent);
  1350. } else if (j == extensionRangesCount ||
  1351. GPBFieldNumber(fieldsArray[i]) < extensionRanges[j].start) {
  1352. AppendTextFormatForMessageField(message, fieldsArray[i++], toStr,
  1353. lineIndent);
  1354. } else {
  1355. AppendTextFormatForMessageExtensionRange(
  1356. message, activeExtensions, extensionRanges[j++], toStr, lineIndent);
  1357. }
  1358. }
  1359. NSString *unknownFieldsStr =
  1360. GPBTextFormatForUnknownFieldSet(message.unknownFields, lineIndent);
  1361. if ([unknownFieldsStr length] > 0) {
  1362. [toStr appendFormat:@"%@# --- Unknown fields ---\n", lineIndent];
  1363. [toStr appendString:unknownFieldsStr];
  1364. }
  1365. }
  1366. NSString *GPBTextFormatForMessage(GPBMessage *message, NSString *lineIndent) {
  1367. if (message == nil) return @"";
  1368. if (lineIndent == nil) lineIndent = @"";
  1369. NSMutableString *buildString = [NSMutableString string];
  1370. AppendTextFormatForMessage(message, buildString, lineIndent);
  1371. return buildString;
  1372. }
  1373. NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *unknownSet,
  1374. NSString *lineIndent) {
  1375. if (unknownSet == nil) return @"";
  1376. if (lineIndent == nil) lineIndent = @"";
  1377. NSMutableString *result = [NSMutableString string];
  1378. for (GPBUnknownField *field in [unknownSet sortedFields]) {
  1379. int32_t fieldNumber = [field number];
  1380. #define PRINT_LOOP(PROPNAME, CTYPE, FORMAT) \
  1381. [field.PROPNAME \
  1382. enumerateValuesWithBlock:^(CTYPE value, NSUInteger idx, BOOL * stop) { \
  1383. _Pragma("unused(idx, stop)"); \
  1384. [result \
  1385. appendFormat:@"%@%d: " #FORMAT "\n", lineIndent, fieldNumber, value]; \
  1386. }];
  1387. PRINT_LOOP(varintList, uint64_t, %llu);
  1388. PRINT_LOOP(fixed32List, uint32_t, 0x%X);
  1389. PRINT_LOOP(fixed64List, uint64_t, 0x%llX);
  1390. #undef PRINT_LOOP
  1391. // NOTE: C++ version of TextFormat tries to parse this as a message
  1392. // and print that if it succeeds.
  1393. for (NSData *data in field.lengthDelimitedList) {
  1394. [result appendFormat:@"%@%d: ", lineIndent, fieldNumber];
  1395. AppendBufferAsString(data, result);
  1396. [result appendString:@"\n"];
  1397. }
  1398. for (GPBUnknownFieldSet *subUnknownSet in field.groupList) {
  1399. [result appendFormat:@"%@%d: {\n", lineIndent, fieldNumber];
  1400. NSString *subIndent = [lineIndent stringByAppendingString:@" "];
  1401. NSString *subUnknwonSetStr =
  1402. GPBTextFormatForUnknownFieldSet(subUnknownSet, subIndent);
  1403. [result appendString:subUnknwonSetStr];
  1404. [result appendFormat:@"%@}\n", lineIndent];
  1405. }
  1406. }
  1407. return result;
  1408. }
  1409. // Helpers to decode a varint. Not using GPBCodedInputStream version because
  1410. // that needs a state object, and we don't want to create an input stream out
  1411. // of the data.
  1412. GPB_INLINE int8_t ReadRawByteFromData(const uint8_t **data) {
  1413. int8_t result = *((int8_t *)(*data));
  1414. ++(*data);
  1415. return result;
  1416. }
  1417. static int32_t ReadRawVarint32FromData(const uint8_t **data) {
  1418. int8_t tmp = ReadRawByteFromData(data);
  1419. if (tmp >= 0) {
  1420. return tmp;
  1421. }
  1422. int32_t result = tmp & 0x7f;
  1423. if ((tmp = ReadRawByteFromData(data)) >= 0) {
  1424. result |= tmp << 7;
  1425. } else {
  1426. result |= (tmp & 0x7f) << 7;
  1427. if ((tmp = ReadRawByteFromData(data)) >= 0) {
  1428. result |= tmp << 14;
  1429. } else {
  1430. result |= (tmp & 0x7f) << 14;
  1431. if ((tmp = ReadRawByteFromData(data)) >= 0) {
  1432. result |= tmp << 21;
  1433. } else {
  1434. result |= (tmp & 0x7f) << 21;
  1435. result |= (tmp = ReadRawByteFromData(data)) << 28;
  1436. if (tmp < 0) {
  1437. // Discard upper 32 bits.
  1438. for (int i = 0; i < 5; i++) {
  1439. if (ReadRawByteFromData(data) >= 0) {
  1440. return result;
  1441. }
  1442. }
  1443. [NSException raise:NSParseErrorException
  1444. format:@"Unable to read varint32"];
  1445. }
  1446. }
  1447. }
  1448. }
  1449. return result;
  1450. }
  1451. NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key,
  1452. NSString *inputStr) {
  1453. // decodData form:
  1454. // varint32: num entries
  1455. // for each entry:
  1456. // varint32: key
  1457. // bytes*: decode data
  1458. //
  1459. // decode data one of two forms:
  1460. // 1: a \0 followed by the string followed by an \0
  1461. // 2: bytecodes to transform an input into the right thing, ending with \0
  1462. //
  1463. // the bytes codes are of the form:
  1464. // 0xabbccccc
  1465. // 0x0 (all zeros), end.
  1466. // a - if set, add an underscore
  1467. // bb - 00 ccccc bytes as is
  1468. // bb - 10 ccccc upper first, as is on rest, ccccc byte total
  1469. // bb - 01 ccccc lower first, as is on rest, ccccc byte total
  1470. // bb - 11 ccccc all upper, ccccc byte total
  1471. if (!decodeData || !inputStr) {
  1472. return nil;
  1473. }
  1474. // Find key
  1475. const uint8_t *scan = decodeData;
  1476. int32_t numEntries = ReadRawVarint32FromData(&scan);
  1477. BOOL foundKey = NO;
  1478. while (!foundKey && (numEntries > 0)) {
  1479. --numEntries;
  1480. int32_t dataKey = ReadRawVarint32FromData(&scan);
  1481. if (dataKey == key) {
  1482. foundKey = YES;
  1483. } else {
  1484. // If it is a inlined string, it will start with \0; if it is bytecode it
  1485. // will start with a code. So advance one (skipping the inline string
  1486. // marker), and then loop until reaching the end marker (\0).
  1487. ++scan;
  1488. while (*scan != 0) ++scan;
  1489. // Now move past the end marker.
  1490. ++scan;
  1491. }
  1492. }
  1493. if (!foundKey) {
  1494. return nil;
  1495. }
  1496. // Decode
  1497. if (*scan == 0) {
  1498. // Inline string. Move over the marker, and NSString can take it as
  1499. // UTF8.
  1500. ++scan;
  1501. NSString *result = [NSString stringWithUTF8String:(const char *)scan];
  1502. return result;
  1503. }
  1504. NSMutableString *result =
  1505. [NSMutableString stringWithCapacity:[inputStr length]];
  1506. const uint8_t kAddUnderscore = 0b10000000;
  1507. const uint8_t kOpMask = 0b01100000;
  1508. // const uint8_t kOpAsIs = 0b00000000;
  1509. const uint8_t kOpFirstUpper = 0b01000000;
  1510. const uint8_t kOpFirstLower = 0b00100000;
  1511. const uint8_t kOpAllUpper = 0b01100000;
  1512. const uint8_t kSegmentLenMask = 0b00011111;
  1513. NSInteger i = 0;
  1514. for (; *scan != 0; ++scan) {
  1515. if (*scan & kAddUnderscore) {
  1516. [result appendString:@"_"];
  1517. }
  1518. int segmentLen = *scan & kSegmentLenMask;
  1519. uint8_t decodeOp = *scan & kOpMask;
  1520. // Do op specific handling of the first character.
  1521. if (decodeOp == kOpFirstUpper) {
  1522. unichar c = [inputStr characterAtIndex:i];
  1523. [result appendFormat:@"%c", toupper((char)c)];
  1524. ++i;
  1525. --segmentLen;
  1526. } else if (decodeOp == kOpFirstLower) {
  1527. unichar c = [inputStr characterAtIndex:i];
  1528. [result appendFormat:@"%c", tolower((char)c)];
  1529. ++i;
  1530. --segmentLen;
  1531. }
  1532. // else op == kOpAsIs || op == kOpAllUpper
  1533. // Now pull over the rest of the length for this segment.
  1534. for (int x = 0; x < segmentLen; ++x) {
  1535. unichar c = [inputStr characterAtIndex:(i + x)];
  1536. if (decodeOp == kOpAllUpper) {
  1537. [result appendFormat:@"%c", toupper((char)c)];
  1538. } else {
  1539. [result appendFormat:@"%C", c];
  1540. }
  1541. }
  1542. i += segmentLen;
  1543. }
  1544. return result;
  1545. }
  1546. #pragma clang diagnostic pop
  1547. #pragma mark - GPBMessageSignatureProtocol
  1548. // A series of selectors that are used solely to get @encoding values
  1549. // for them by the dynamic protobuf runtime code. An object using the protocol
  1550. // needs to be declared for the protocol to be valid at runtime.
  1551. @interface GPBMessageSignatureProtocol : NSObject<GPBMessageSignatureProtocol>
  1552. @end
  1553. @implementation GPBMessageSignatureProtocol
  1554. @end