GPBUtilities.m 63 KB

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