GPBUtilities.m 84 KB

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