GPBUtilities.m 63 KB

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