GPBUtilities.m 67 KB

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