GPBUtilities.m 62 KB

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