GPBDescriptor.m 30 KB

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