GPBUtilities.m 67 KB

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