GPBUtilities.m 64 KB

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