GPBDescriptor.m 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  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 "GPBDescriptor_PackagePrivate.h"
  31. #import <objc/runtime.h>
  32. #import "GPBUtilities_PackagePrivate.h"
  33. #import "GPBWireFormat.h"
  34. #import "GPBMessage_PackagePrivate.h"
  35. // Direct access is use for speed, to avoid even internally declaring things
  36. // read/write, etc. The warning is enabled in the project to ensure code calling
  37. // protos can turn on -Wdirect-ivar-access without issues.
  38. #pragma clang diagnostic push
  39. #pragma clang diagnostic ignored "-Wdirect-ivar-access"
  40. // The address of this variable is used as a key for obj_getAssociatedObject.
  41. static const char kTextFormatExtraValueKey = 0;
  42. // Utility function to generate selectors on the fly.
  43. static SEL SelFromStrings(const char *prefix, const char *middle,
  44. const char *suffix, BOOL takesArg) {
  45. if (prefix == NULL && suffix == NULL && !takesArg) {
  46. return sel_getUid(middle);
  47. }
  48. const size_t prefixLen = prefix != NULL ? strlen(prefix) : 0;
  49. const size_t middleLen = strlen(middle);
  50. const size_t suffixLen = suffix != NULL ? strlen(suffix) : 0;
  51. size_t totalLen =
  52. prefixLen + middleLen + suffixLen + 1; // include space for null on end.
  53. if (takesArg) {
  54. totalLen += 1;
  55. }
  56. char buffer[totalLen];
  57. if (prefix != NULL) {
  58. memcpy(buffer, prefix, prefixLen);
  59. memcpy(buffer + prefixLen, middle, middleLen);
  60. buffer[prefixLen] = (char)toupper(buffer[prefixLen]);
  61. } else {
  62. memcpy(buffer, middle, middleLen);
  63. }
  64. if (suffix != NULL) {
  65. memcpy(buffer + prefixLen + middleLen, suffix, suffixLen);
  66. }
  67. if (takesArg) {
  68. buffer[totalLen - 2] = ':';
  69. }
  70. // Always null terminate it.
  71. buffer[totalLen - 1] = 0;
  72. SEL result = sel_getUid(buffer);
  73. return result;
  74. }
  75. static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
  76. NSArray *allMessageFields)
  77. __attribute__((ns_returns_retained));
  78. static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
  79. NSArray *allMessageFields) {
  80. NSMutableArray *result = [[NSMutableArray alloc] init];
  81. for (GPBFieldDescriptor *fieldDesc in allMessageFields) {
  82. if (fieldDesc->description_->hasIndex == hasIndex) {
  83. [result addObject:fieldDesc];
  84. }
  85. }
  86. return result;
  87. }
  88. @implementation GPBDescriptor {
  89. Class messageClass_;
  90. GPBFileDescriptor *file_;
  91. BOOL wireFormat_;
  92. }
  93. @synthesize messageClass = messageClass_;
  94. @synthesize fields = fields_;
  95. @synthesize oneofs = oneofs_;
  96. @synthesize extensionRanges = extensionRanges_;
  97. @synthesize extensionRangesCount = extensionRangesCount_;
  98. @synthesize file = file_;
  99. @synthesize wireFormat = wireFormat_;
  100. + (instancetype)
  101. allocDescriptorForClass:(Class)messageClass
  102. rootClass:(Class)rootClass
  103. file:(GPBFileDescriptor *)file
  104. fields:(void *)fieldDescriptions
  105. fieldCount:(uint32_t)fieldCount
  106. storageSize:(uint32_t)storageSize
  107. flags:(GPBDescriptorInitializationFlags)flags {
  108. // The rootClass is no longer used, but it is passed in to ensure it
  109. // was started up during initialization also.
  110. (void)rootClass;
  111. NSMutableArray *fields = nil;
  112. GPBFileSyntax syntax = file.syntax;
  113. BOOL fieldsIncludeDefault =
  114. (flags & GPBDescriptorInitializationFlag_FieldsWithDefault) != 0;
  115. void *desc;
  116. for (uint32_t i = 0; i < fieldCount; ++i) {
  117. if (fields == nil) {
  118. fields = [[NSMutableArray alloc] initWithCapacity:fieldCount];
  119. }
  120. // Need correctly typed pointer for array indexing below to work.
  121. if (fieldsIncludeDefault) {
  122. GPBMessageFieldDescriptionWithDefault *fieldDescWithDefault = fieldDescriptions;
  123. desc = &(fieldDescWithDefault[i]);
  124. } else {
  125. GPBMessageFieldDescription *fieldDesc = fieldDescriptions;
  126. desc = &(fieldDesc[i]);
  127. }
  128. GPBFieldDescriptor *fieldDescriptor =
  129. [[GPBFieldDescriptor alloc] initWithFieldDescription:desc
  130. includesDefault:fieldsIncludeDefault
  131. syntax:syntax];
  132. [fields addObject:fieldDescriptor];
  133. [fieldDescriptor release];
  134. }
  135. BOOL wireFormat = (flags & GPBDescriptorInitializationFlag_WireFormat) != 0;
  136. GPBDescriptor *descriptor = [[self alloc] initWithClass:messageClass
  137. file:file
  138. fields:fields
  139. storageSize:storageSize
  140. wireFormat:wireFormat];
  141. [fields release];
  142. return descriptor;
  143. }
  144. - (instancetype)initWithClass:(Class)messageClass
  145. file:(GPBFileDescriptor *)file
  146. fields:(NSArray *)fields
  147. storageSize:(uint32_t)storageSize
  148. wireFormat:(BOOL)wireFormat {
  149. if ((self = [super init])) {
  150. messageClass_ = messageClass;
  151. file_ = file;
  152. fields_ = [fields retain];
  153. storageSize_ = storageSize;
  154. wireFormat_ = wireFormat;
  155. }
  156. return self;
  157. }
  158. - (void)dealloc {
  159. [fields_ release];
  160. [oneofs_ release];
  161. [super dealloc];
  162. }
  163. - (void)setupOneofs:(const char **)oneofNames
  164. count:(uint32_t)count
  165. firstHasIndex:(int32_t)firstHasIndex {
  166. NSCAssert(firstHasIndex < 0, @"Should always be <0");
  167. NSMutableArray *oneofs = [[NSMutableArray alloc] initWithCapacity:count];
  168. for (uint32_t i = 0, hasIndex = firstHasIndex; i < count; ++i, --hasIndex) {
  169. const char *name = oneofNames[i];
  170. NSArray *fieldsForOneof = NewFieldsArrayForHasIndex(hasIndex, fields_);
  171. NSCAssert(fieldsForOneof.count > 0,
  172. @"No fields for this oneof? (%s:%d)", name, hasIndex);
  173. GPBOneofDescriptor *oneofDescriptor =
  174. [[GPBOneofDescriptor alloc] initWithName:name fields:fieldsForOneof];
  175. [oneofs addObject:oneofDescriptor];
  176. [oneofDescriptor release];
  177. [fieldsForOneof release];
  178. }
  179. oneofs_ = oneofs;
  180. }
  181. - (void)setupExtraTextInfo:(const char *)extraTextFormatInfo {
  182. // Extra info is a compile time option, so skip the work if not needed.
  183. if (extraTextFormatInfo) {
  184. NSValue *extraInfoValue = [NSValue valueWithPointer:extraTextFormatInfo];
  185. for (GPBFieldDescriptor *fieldDescriptor in fields_) {
  186. if (fieldDescriptor->description_->flags & GPBFieldTextFormatNameCustom) {
  187. objc_setAssociatedObject(fieldDescriptor, &kTextFormatExtraValueKey,
  188. extraInfoValue,
  189. OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  190. }
  191. }
  192. }
  193. }
  194. - (void)setupExtensionRanges:(const GPBExtensionRange *)ranges count:(int32_t)count {
  195. extensionRanges_ = ranges;
  196. extensionRangesCount_ = count;
  197. }
  198. - (NSString *)name {
  199. return NSStringFromClass(messageClass_);
  200. }
  201. - (id)copyWithZone:(NSZone *)zone {
  202. #pragma unused(zone)
  203. return [self retain];
  204. }
  205. - (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber {
  206. for (GPBFieldDescriptor *descriptor in fields_) {
  207. if (GPBFieldNumber(descriptor) == fieldNumber) {
  208. return descriptor;
  209. }
  210. }
  211. return nil;
  212. }
  213. - (GPBFieldDescriptor *)fieldWithName:(NSString *)name {
  214. for (GPBFieldDescriptor *descriptor in fields_) {
  215. if ([descriptor.name isEqual:name]) {
  216. return descriptor;
  217. }
  218. }
  219. return nil;
  220. }
  221. - (GPBOneofDescriptor *)oneofWithName:(NSString *)name {
  222. for (GPBOneofDescriptor *descriptor in oneofs_) {
  223. if ([descriptor.name isEqual:name]) {
  224. return descriptor;
  225. }
  226. }
  227. return nil;
  228. }
  229. @end
  230. @implementation GPBFileDescriptor {
  231. NSString *package_;
  232. GPBFileSyntax syntax_;
  233. }
  234. @synthesize package = package_;
  235. @synthesize syntax = syntax_;
  236. - (instancetype)initWithPackage:(NSString *)package
  237. syntax:(GPBFileSyntax)syntax {
  238. self = [super init];
  239. if (self) {
  240. package_ = [package copy];
  241. syntax_ = syntax;
  242. }
  243. return self;
  244. }
  245. - (void)dealloc {
  246. [package_ release];
  247. [super dealloc];
  248. }
  249. @end
  250. @implementation GPBOneofDescriptor
  251. @synthesize fields = fields_;
  252. - (instancetype)initWithName:(const char *)name fields:(NSArray *)fields {
  253. self = [super init];
  254. if (self) {
  255. name_ = name;
  256. fields_ = [fields retain];
  257. for (GPBFieldDescriptor *fieldDesc in fields) {
  258. fieldDesc->containingOneof_ = self;
  259. }
  260. caseSel_ = SelFromStrings(NULL, name, "OneOfCase", NO);
  261. }
  262. return self;
  263. }
  264. - (void)dealloc {
  265. [fields_ release];
  266. [super dealloc];
  267. }
  268. - (NSString *)name {
  269. return @(name_);
  270. }
  271. - (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber {
  272. for (GPBFieldDescriptor *descriptor in fields_) {
  273. if (GPBFieldNumber(descriptor) == fieldNumber) {
  274. return descriptor;
  275. }
  276. }
  277. return nil;
  278. }
  279. - (GPBFieldDescriptor *)fieldWithName:(NSString *)name {
  280. for (GPBFieldDescriptor *descriptor in fields_) {
  281. if ([descriptor.name isEqual:name]) {
  282. return descriptor;
  283. }
  284. }
  285. return nil;
  286. }
  287. @end
  288. uint32_t GPBFieldTag(GPBFieldDescriptor *self) {
  289. GPBMessageFieldDescription *description = self->description_;
  290. GPBWireFormat format;
  291. if ((description->flags & GPBFieldMapKeyMask) != 0) {
  292. // Maps are repeated messages on the wire.
  293. format = GPBWireFormatForType(GPBDataTypeMessage, NO);
  294. } else {
  295. format = GPBWireFormatForType(description->dataType,
  296. ((description->flags & GPBFieldPacked) != 0));
  297. }
  298. return GPBWireFormatMakeTag(description->number, format);
  299. }
  300. uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
  301. GPBMessageFieldDescription *description = self->description_;
  302. NSCAssert((description->flags & GPBFieldRepeated) != 0,
  303. @"Only valid on repeated fields");
  304. GPBWireFormat format =
  305. GPBWireFormatForType(description->dataType,
  306. ((description->flags & GPBFieldPacked) == 0));
  307. return GPBWireFormatMakeTag(description->number, format);
  308. }
  309. @implementation GPBFieldDescriptor {
  310. GPBGenericValue defaultValue_;
  311. // Message ivars
  312. Class msgClass_;
  313. // Enum ivars.
  314. // If protos are generated with GenerateEnumDescriptors on then it will
  315. // be a enumDescriptor, otherwise it will be a enumVerifier.
  316. union {
  317. GPBEnumDescriptor *enumDescriptor_;
  318. GPBEnumValidationFunc enumVerifier_;
  319. } enumHandling_;
  320. }
  321. @synthesize msgClass = msgClass_;
  322. @synthesize containingOneof = containingOneof_;
  323. - (instancetype)init {
  324. // Throw an exception if people attempt to not use the designated initializer.
  325. self = [super init];
  326. if (self != nil) {
  327. [self doesNotRecognizeSelector:_cmd];
  328. self = nil;
  329. }
  330. return self;
  331. }
  332. - (instancetype)initWithFieldDescription:(void *)description
  333. includesDefault:(BOOL)includesDefault
  334. syntax:(GPBFileSyntax)syntax {
  335. if ((self = [super init])) {
  336. GPBMessageFieldDescription *coreDesc;
  337. if (includesDefault) {
  338. coreDesc = &(((GPBMessageFieldDescriptionWithDefault *)description)->core);
  339. } else {
  340. coreDesc = description;
  341. }
  342. description_ = coreDesc;
  343. getSel_ = sel_getUid(coreDesc->name);
  344. setSel_ = SelFromStrings("set", coreDesc->name, NULL, YES);
  345. GPBDataType dataType = coreDesc->dataType;
  346. BOOL isMessage = GPBDataTypeIsMessage(dataType);
  347. BOOL isMapOrArray = GPBFieldIsMapOrArray(self);
  348. if (isMapOrArray) {
  349. // map<>/repeated fields get a *Count property (inplace of a has*) to
  350. // support checking if there are any entries without triggering
  351. // autocreation.
  352. hasOrCountSel_ = SelFromStrings(NULL, coreDesc->name, "_Count", NO);
  353. } else {
  354. // If there is a positive hasIndex, then:
  355. // - All fields types for proto2 messages get has* selectors.
  356. // - Only message fields for proto3 messages get has* selectors.
  357. // Note: the positive check is to handle oneOfs, we can't check
  358. // containingOneof_ because it isn't set until after initialization.
  359. if ((coreDesc->hasIndex >= 0) &&
  360. (coreDesc->hasIndex != GPBNoHasBit) &&
  361. ((syntax != GPBFileSyntaxProto3) || isMessage)) {
  362. hasOrCountSel_ = SelFromStrings("has", coreDesc->name, NULL, NO);
  363. setHasSel_ = SelFromStrings("setHas", coreDesc->name, NULL, YES);
  364. }
  365. }
  366. // Extra type specific data.
  367. if (isMessage) {
  368. const char *className = coreDesc->dataTypeSpecific.className;
  369. msgClass_ = objc_getClass(className);
  370. NSAssert(msgClass_, @"Class %s not defined", className);
  371. } else if (dataType == GPBDataTypeEnum) {
  372. if ((coreDesc->flags & GPBFieldHasEnumDescriptor) != 0) {
  373. enumHandling_.enumDescriptor_ =
  374. coreDesc->dataTypeSpecific.enumDescFunc();
  375. } else {
  376. enumHandling_.enumVerifier_ =
  377. coreDesc->dataTypeSpecific.enumVerifier;
  378. }
  379. }
  380. // Non map<>/repeated fields can have defaults in proto2 syntax.
  381. if (!isMapOrArray && includesDefault) {
  382. defaultValue_ = ((GPBMessageFieldDescriptionWithDefault *)description)->defaultValue;
  383. if (dataType == GPBDataTypeBytes) {
  384. // Data stored as a length prefixed (network byte order) c-string in
  385. // descriptor structure.
  386. const uint8_t *bytes = (const uint8_t *)defaultValue_.valueData;
  387. if (bytes) {
  388. uint32_t length = *((uint32_t *)bytes);
  389. length = ntohl(length);
  390. bytes += sizeof(length);
  391. defaultValue_.valueData =
  392. [[NSData alloc] initWithBytes:bytes length:length];
  393. }
  394. }
  395. }
  396. }
  397. return self;
  398. }
  399. - (void)dealloc {
  400. if (description_->dataType == GPBDataTypeBytes &&
  401. !(description_->flags & GPBFieldRepeated)) {
  402. [defaultValue_.valueData release];
  403. }
  404. [super dealloc];
  405. }
  406. - (GPBDataType)dataType {
  407. return description_->dataType;
  408. }
  409. - (BOOL)hasDefaultValue {
  410. return (description_->flags & GPBFieldHasDefaultValue) != 0;
  411. }
  412. - (uint32_t)number {
  413. return description_->number;
  414. }
  415. - (NSString *)name {
  416. return @(description_->name);
  417. }
  418. - (BOOL)isRequired {
  419. return (description_->flags & GPBFieldRequired) != 0;
  420. }
  421. - (BOOL)isOptional {
  422. return (description_->flags & GPBFieldOptional) != 0;
  423. }
  424. - (GPBFieldType)fieldType {
  425. GPBFieldFlags flags = description_->flags;
  426. if ((flags & GPBFieldRepeated) != 0) {
  427. return GPBFieldTypeRepeated;
  428. } else if ((flags & GPBFieldMapKeyMask) != 0) {
  429. return GPBFieldTypeMap;
  430. } else {
  431. return GPBFieldTypeSingle;
  432. }
  433. }
  434. - (GPBDataType)mapKeyDataType {
  435. switch (description_->flags & GPBFieldMapKeyMask) {
  436. case GPBFieldMapKeyInt32:
  437. return GPBDataTypeInt32;
  438. case GPBFieldMapKeyInt64:
  439. return GPBDataTypeInt64;
  440. case GPBFieldMapKeyUInt32:
  441. return GPBDataTypeUInt32;
  442. case GPBFieldMapKeyUInt64:
  443. return GPBDataTypeUInt64;
  444. case GPBFieldMapKeySInt32:
  445. return GPBDataTypeSInt32;
  446. case GPBFieldMapKeySInt64:
  447. return GPBDataTypeSInt64;
  448. case GPBFieldMapKeyFixed32:
  449. return GPBDataTypeFixed32;
  450. case GPBFieldMapKeyFixed64:
  451. return GPBDataTypeFixed64;
  452. case GPBFieldMapKeySFixed32:
  453. return GPBDataTypeSFixed32;
  454. case GPBFieldMapKeySFixed64:
  455. return GPBDataTypeSFixed64;
  456. case GPBFieldMapKeyBool:
  457. return GPBDataTypeBool;
  458. case GPBFieldMapKeyString:
  459. return GPBDataTypeString;
  460. default:
  461. NSAssert(0, @"Not a map type");
  462. return GPBDataTypeInt32; // For lack of anything better.
  463. }
  464. }
  465. - (BOOL)isPackable {
  466. return (description_->flags & GPBFieldPacked) != 0;
  467. }
  468. - (BOOL)isValidEnumValue:(int32_t)value {
  469. NSAssert(description_->dataType == GPBDataTypeEnum,
  470. @"Field Must be of type GPBDataTypeEnum");
  471. if (description_->flags & GPBFieldHasEnumDescriptor) {
  472. return enumHandling_.enumDescriptor_.enumVerifier(value);
  473. } else {
  474. return enumHandling_.enumVerifier_(value);
  475. }
  476. }
  477. - (GPBEnumDescriptor *)enumDescriptor {
  478. if (description_->flags & GPBFieldHasEnumDescriptor) {
  479. return enumHandling_.enumDescriptor_;
  480. } else {
  481. return nil;
  482. }
  483. }
  484. - (GPBGenericValue)defaultValue {
  485. // Depends on the fact that defaultValue_ is initialized either to "0/nil" or
  486. // to an actual defaultValue in our initializer.
  487. GPBGenericValue value = defaultValue_;
  488. if (!(description_->flags & GPBFieldRepeated)) {
  489. // We special handle data and strings. If they are nil, we replace them
  490. // with empty string/empty data.
  491. GPBDataType type = description_->dataType;
  492. if (type == GPBDataTypeBytes && value.valueData == nil) {
  493. value.valueData = GPBEmptyNSData();
  494. } else if (type == GPBDataTypeString && value.valueString == nil) {
  495. value.valueString = @"";
  496. }
  497. }
  498. return value;
  499. }
  500. - (NSString *)textFormatName {
  501. if ((description_->flags & GPBFieldTextFormatNameCustom) != 0) {
  502. NSValue *extraInfoValue =
  503. objc_getAssociatedObject(self, &kTextFormatExtraValueKey);
  504. // Support can be left out at generation time.
  505. if (!extraInfoValue) {
  506. return nil;
  507. }
  508. const uint8_t *extraTextFormatInfo = [extraInfoValue pointerValue];
  509. return GPBDecodeTextFormatName(extraTextFormatInfo, GPBFieldNumber(self),
  510. self.name);
  511. }
  512. // The logic here has to match SetCommonFieldVariables() from
  513. // objectivec_field.cc in the proto compiler.
  514. NSString *name = self.name;
  515. NSUInteger len = [name length];
  516. // Remove the "_p" added to reserved names.
  517. if ([name hasSuffix:@"_p"]) {
  518. name = [name substringToIndex:(len - 2)];
  519. len = [name length];
  520. }
  521. // Remove "Array" from the end for repeated fields.
  522. if (((description_->flags & GPBFieldRepeated) != 0) &&
  523. [name hasSuffix:@"Array"]) {
  524. name = [name substringToIndex:(len - 5)];
  525. len = [name length];
  526. }
  527. // Groups vs. other fields.
  528. if (description_->dataType == GPBDataTypeGroup) {
  529. // Just capitalize the first letter.
  530. unichar firstChar = [name characterAtIndex:0];
  531. if (firstChar >= 'a' && firstChar <= 'z') {
  532. NSString *firstCharString =
  533. [NSString stringWithFormat:@"%C", (unichar)(firstChar - 'a' + 'A')];
  534. NSString *result =
  535. [name stringByReplacingCharactersInRange:NSMakeRange(0, 1)
  536. withString:firstCharString];
  537. return result;
  538. }
  539. return name;
  540. } else {
  541. // Undo the CamelCase.
  542. NSMutableString *result = [NSMutableString stringWithCapacity:len];
  543. for (uint32_t i = 0; i < len; i++) {
  544. unichar c = [name characterAtIndex:i];
  545. if (c >= 'A' && c <= 'Z') {
  546. if (i > 0) {
  547. [result appendFormat:@"_%C", (unichar)(c - 'A' + 'a')];
  548. } else {
  549. [result appendFormat:@"%C", c];
  550. }
  551. } else {
  552. [result appendFormat:@"%C", c];
  553. }
  554. }
  555. return result;
  556. }
  557. }
  558. @end
  559. @implementation GPBEnumDescriptor {
  560. NSString *name_;
  561. // valueNames_ is a single c string with all of the value names appended
  562. // together, each null terminated. -calcValueNameOffsets fills in
  563. // nameOffsets_ with the offsets to allow quicker access to the individual
  564. // names.
  565. const char *valueNames_;
  566. const int32_t *values_;
  567. GPBEnumValidationFunc enumVerifier_;
  568. const uint8_t *extraTextFormatInfo_;
  569. uint32_t *nameOffsets_;
  570. uint32_t valueCount_;
  571. }
  572. @synthesize name = name_;
  573. @synthesize enumVerifier = enumVerifier_;
  574. + (instancetype)
  575. allocDescriptorForName:(NSString *)name
  576. valueNames:(const char *)valueNames
  577. values:(const int32_t *)values
  578. count:(uint32_t)valueCount
  579. enumVerifier:(GPBEnumValidationFunc)enumVerifier {
  580. GPBEnumDescriptor *descriptor = [[self alloc] initWithName:name
  581. valueNames:valueNames
  582. values:values
  583. count:valueCount
  584. enumVerifier:enumVerifier];
  585. return descriptor;
  586. }
  587. + (instancetype)
  588. allocDescriptorForName:(NSString *)name
  589. valueNames:(const char *)valueNames
  590. values:(const int32_t *)values
  591. count:(uint32_t)valueCount
  592. enumVerifier:(GPBEnumValidationFunc)enumVerifier
  593. extraTextFormatInfo:(const char *)extraTextFormatInfo {
  594. // Call the common case.
  595. GPBEnumDescriptor *descriptor = [self allocDescriptorForName:name
  596. valueNames:valueNames
  597. values:values
  598. count:valueCount
  599. enumVerifier:enumVerifier];
  600. // Set the extra info.
  601. descriptor->extraTextFormatInfo_ = (const uint8_t *)extraTextFormatInfo;
  602. return descriptor;
  603. }
  604. - (instancetype)initWithName:(NSString *)name
  605. valueNames:(const char *)valueNames
  606. values:(const int32_t *)values
  607. count:(uint32_t)valueCount
  608. enumVerifier:(GPBEnumValidationFunc)enumVerifier {
  609. if ((self = [super init])) {
  610. name_ = [name copy];
  611. valueNames_ = valueNames;
  612. values_ = values;
  613. valueCount_ = valueCount;
  614. enumVerifier_ = enumVerifier;
  615. }
  616. return self;
  617. }
  618. - (void)dealloc {
  619. [name_ release];
  620. if (nameOffsets_) free(nameOffsets_);
  621. [super dealloc];
  622. }
  623. - (void)calcValueNameOffsets {
  624. @synchronized(self) {
  625. if (nameOffsets_ != NULL) {
  626. return;
  627. }
  628. uint32_t *offsets = malloc(valueCount_ * sizeof(uint32_t));
  629. const char *scan = valueNames_;
  630. for (uint32_t i = 0; i < valueCount_; ++i) {
  631. offsets[i] = (uint32_t)(scan - valueNames_);
  632. while (*scan != '\0') ++scan;
  633. ++scan; // Step over the null.
  634. }
  635. nameOffsets_ = offsets;
  636. }
  637. }
  638. - (NSString *)enumNameForValue:(int32_t)number {
  639. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  640. for (uint32_t i = 0; i < valueCount_; ++i) {
  641. if (values_[i] == number) {
  642. const char *valueName = valueNames_ + nameOffsets_[i];
  643. NSString *fullName = [NSString stringWithFormat:@"%@_%s", name_, valueName];
  644. return fullName;
  645. }
  646. }
  647. return nil;
  648. }
  649. - (BOOL)getValue:(int32_t *)outValue forEnumName:(NSString *)name {
  650. // Must have the prefix.
  651. NSUInteger prefixLen = name_.length + 1;
  652. if ((name.length <= prefixLen) || ![name hasPrefix:name_] ||
  653. ([name characterAtIndex:prefixLen - 1] != '_')) {
  654. return NO;
  655. }
  656. // Skip over the prefix.
  657. const char *nameAsCStr = [name UTF8String];
  658. nameAsCStr += prefixLen;
  659. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  660. // Find it.
  661. for (uint32_t i = 0; i < valueCount_; ++i) {
  662. const char *valueName = valueNames_ + nameOffsets_[i];
  663. if (strcmp(nameAsCStr, valueName) == 0) {
  664. if (outValue) {
  665. *outValue = values_[i];
  666. }
  667. return YES;
  668. }
  669. }
  670. return NO;
  671. }
  672. - (BOOL)getValue:(int32_t *)outValue forEnumTextFormatName:(NSString *)textFormatName {
  673. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  674. for (uint32_t i = 0; i < valueCount_; ++i) {
  675. int32_t value = values_[i];
  676. NSString *valueTextFormatName = [self textFormatNameForValue:value];
  677. if ([valueTextFormatName isEqual:textFormatName]) {
  678. if (outValue) {
  679. *outValue = value;
  680. }
  681. return YES;
  682. }
  683. }
  684. return NO;
  685. }
  686. - (NSString *)textFormatNameForValue:(int32_t)number {
  687. if (nameOffsets_ == NULL) [self calcValueNameOffsets];
  688. // Find the EnumValue descriptor and its index.
  689. BOOL foundIt = NO;
  690. uint32_t valueDescriptorIndex;
  691. for (valueDescriptorIndex = 0; valueDescriptorIndex < valueCount_;
  692. ++valueDescriptorIndex) {
  693. if (values_[valueDescriptorIndex] == number) {
  694. foundIt = YES;
  695. break;
  696. }
  697. }
  698. if (!foundIt) {
  699. return nil;
  700. }
  701. NSString *result = nil;
  702. // Naming adds an underscore between enum name and value name, skip that also.
  703. const char *valueName = valueNames_ + nameOffsets_[valueDescriptorIndex];
  704. NSString *shortName = @(valueName);
  705. // See if it is in the map of special format handling.
  706. if (extraTextFormatInfo_) {
  707. result = GPBDecodeTextFormatName(extraTextFormatInfo_,
  708. (int32_t)valueDescriptorIndex, shortName);
  709. }
  710. // Logic here needs to match what objectivec_enum.cc does in the proto
  711. // compiler.
  712. if (result == nil) {
  713. NSUInteger len = [shortName length];
  714. NSMutableString *worker = [NSMutableString stringWithCapacity:len];
  715. for (NSUInteger i = 0; i < len; i++) {
  716. unichar c = [shortName characterAtIndex:i];
  717. if (i > 0 && c >= 'A' && c <= 'Z') {
  718. [worker appendString:@"_"];
  719. }
  720. [worker appendFormat:@"%c", toupper((char)c)];
  721. }
  722. result = worker;
  723. }
  724. return result;
  725. }
  726. @end
  727. @implementation GPBExtensionDescriptor {
  728. GPBGenericValue defaultValue_;
  729. }
  730. @synthesize containingMessageClass = containingMessageClass_;
  731. - (instancetype)initWithExtensionDescription:
  732. (GPBExtensionDescription *)description {
  733. if ((self = [super init])) {
  734. description_ = description;
  735. #if defined(DEBUG) && DEBUG
  736. const char *className = description->messageOrGroupClassName;
  737. if (className) {
  738. NSAssert(objc_lookUpClass(className) != Nil,
  739. @"Class %s not defined", className);
  740. }
  741. #endif
  742. if (description->extendedClass) {
  743. Class containingClass = objc_lookUpClass(description->extendedClass);
  744. NSAssert(containingClass, @"Class %s not defined",
  745. description->extendedClass);
  746. containingMessageClass_ = containingClass;
  747. }
  748. GPBDataType type = description_->dataType;
  749. if (type == GPBDataTypeBytes) {
  750. // Data stored as a length prefixed c-string in descriptor records.
  751. const uint8_t *bytes =
  752. (const uint8_t *)description->defaultValue.valueData;
  753. if (bytes) {
  754. uint32_t length = *((uint32_t *)bytes);
  755. // The length is stored in network byte order.
  756. length = ntohl(length);
  757. bytes += sizeof(length);
  758. defaultValue_.valueData =
  759. [[NSData alloc] initWithBytes:bytes length:length];
  760. }
  761. } else if (type == GPBDataTypeMessage || type == GPBDataTypeGroup) {
  762. // The default is looked up in -defaultValue instead since extensions
  763. // aren't common, we avoid the hit startup hit and it avoid initialization
  764. // order issues.
  765. } else {
  766. defaultValue_ = description->defaultValue;
  767. }
  768. }
  769. return self;
  770. }
  771. - (void)dealloc {
  772. if ((description_->dataType == GPBDataTypeBytes) &&
  773. !GPBExtensionIsRepeated(description_)) {
  774. [defaultValue_.valueData release];
  775. }
  776. [super dealloc];
  777. }
  778. - (instancetype)copyWithZone:(NSZone *)zone {
  779. #pragma unused(zone)
  780. // Immutable.
  781. return [self retain];
  782. }
  783. - (NSString *)singletonName {
  784. return @(description_->singletonName);
  785. }
  786. - (const char *)singletonNameC {
  787. return description_->singletonName;
  788. }
  789. - (uint32_t)fieldNumber {
  790. return description_->fieldNumber;
  791. }
  792. - (GPBDataType)dataType {
  793. return description_->dataType;
  794. }
  795. - (GPBWireFormat)wireType {
  796. return GPBWireFormatForType(description_->dataType,
  797. GPBExtensionIsPacked(description_));
  798. }
  799. - (GPBWireFormat)alternateWireType {
  800. NSAssert(GPBExtensionIsRepeated(description_),
  801. @"Only valid on repeated extensions");
  802. return GPBWireFormatForType(description_->dataType,
  803. !GPBExtensionIsPacked(description_));
  804. }
  805. - (BOOL)isRepeated {
  806. return GPBExtensionIsRepeated(description_);
  807. }
  808. - (BOOL)isMap {
  809. return (description_->options & GPBFieldMapKeyMask) != 0;
  810. }
  811. - (BOOL)isPackable {
  812. return GPBExtensionIsPacked(description_);
  813. }
  814. - (Class)msgClass {
  815. return objc_getClass(description_->messageOrGroupClassName);
  816. }
  817. - (GPBEnumDescriptor *)enumDescriptor {
  818. if (description_->dataType == GPBDataTypeEnum) {
  819. GPBEnumDescriptor *enumDescriptor = description_->enumDescriptorFunc();
  820. return enumDescriptor;
  821. }
  822. return nil;
  823. }
  824. - (id)defaultValue {
  825. if (GPBExtensionIsRepeated(description_)) {
  826. return nil;
  827. }
  828. switch (description_->dataType) {
  829. case GPBDataTypeBool:
  830. return @(defaultValue_.valueBool);
  831. case GPBDataTypeFloat:
  832. return @(defaultValue_.valueFloat);
  833. case GPBDataTypeDouble:
  834. return @(defaultValue_.valueDouble);
  835. case GPBDataTypeInt32:
  836. case GPBDataTypeSInt32:
  837. case GPBDataTypeEnum:
  838. case GPBDataTypeSFixed32:
  839. return @(defaultValue_.valueInt32);
  840. case GPBDataTypeInt64:
  841. case GPBDataTypeSInt64:
  842. case GPBDataTypeSFixed64:
  843. return @(defaultValue_.valueInt64);
  844. case GPBDataTypeUInt32:
  845. case GPBDataTypeFixed32:
  846. return @(defaultValue_.valueUInt32);
  847. case GPBDataTypeUInt64:
  848. case GPBDataTypeFixed64:
  849. return @(defaultValue_.valueUInt64);
  850. case GPBDataTypeBytes:
  851. // Like message fields, the default is zero length data.
  852. return (defaultValue_.valueData ? defaultValue_.valueData
  853. : GPBEmptyNSData());
  854. case GPBDataTypeString:
  855. // Like message fields, the default is zero length string.
  856. return (defaultValue_.valueString ? defaultValue_.valueString : @"");
  857. case GPBDataTypeGroup:
  858. case GPBDataTypeMessage:
  859. return nil;
  860. }
  861. }
  862. - (NSComparisonResult)compareByFieldNumber:(GPBExtensionDescriptor *)other {
  863. int32_t selfNumber = description_->fieldNumber;
  864. int32_t otherNumber = other->description_->fieldNumber;
  865. if (selfNumber < otherNumber) {
  866. return NSOrderedAscending;
  867. } else if (selfNumber == otherNumber) {
  868. return NSOrderedSame;
  869. } else {
  870. return NSOrderedDescending;
  871. }
  872. }
  873. @end
  874. #pragma clang diagnostic pop