GPBUtilities.m 63 KB

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