GPBUtilities.m 83 KB

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