GPBUnknownFieldSet.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 "GPBUnknownFieldSet_PackagePrivate.h"
  31. #import "GPBCodedInputStream_PackagePrivate.h"
  32. #import "GPBCodedOutputStream.h"
  33. #import "GPBField_PackagePrivate.h"
  34. #import "GPBUtilities.h"
  35. #import "GPBWireFormat.h"
  36. #pragma mark CFDictionaryKeyCallBacks
  37. // We use a custom dictionary here because our keys are numbers and
  38. // conversion back and forth from NSNumber was costing us performance.
  39. // If/when we move to C++ this could be done using a std::map and some
  40. // careful retain/release calls.
  41. static const void *GPBUnknownFieldSetKeyRetain(CFAllocatorRef allocator,
  42. const void *value) {
  43. #pragma unused(allocator)
  44. return value;
  45. }
  46. static void GPBUnknownFieldSetKeyRelease(CFAllocatorRef allocator,
  47. const void *value) {
  48. #pragma unused(allocator)
  49. #pragma unused(value)
  50. }
  51. static CFStringRef GPBUnknownFieldSetCopyKeyDescription(const void *value) {
  52. return CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%d"),
  53. (int)value);
  54. }
  55. static Boolean GPBUnknownFieldSetKeyEqual(const void *value1,
  56. const void *value2) {
  57. return value1 == value2;
  58. }
  59. static CFHashCode GPBUnknownFieldSetKeyHash(const void *value) {
  60. return (CFHashCode)value;
  61. }
  62. #pragma mark Helpers
  63. static void checkNumber(int32_t number) {
  64. if (number == 0) {
  65. [NSException raise:NSInvalidArgumentException
  66. format:@"Zero is not a valid field number."];
  67. }
  68. }
  69. @implementation GPBUnknownFieldSet {
  70. @package
  71. CFMutableDictionaryRef fields_;
  72. }
  73. static void CopyWorker(const void *key, const void *value, void *context) {
  74. #pragma unused(key)
  75. GPBField *field = value;
  76. GPBUnknownFieldSet *result = context;
  77. GPBField *copied = [field copy];
  78. [result addField:copied];
  79. [copied release];
  80. }
  81. - (id)copyWithZone:(NSZone *)zone {
  82. GPBUnknownFieldSet *result = [[GPBUnknownFieldSet allocWithZone:zone] init];
  83. if (fields_) {
  84. CFDictionaryApplyFunction(fields_, CopyWorker, result);
  85. }
  86. return result;
  87. }
  88. - (void)dealloc {
  89. if (fields_) {
  90. CFRelease(fields_);
  91. }
  92. [super dealloc];
  93. }
  94. - (BOOL)isEqual:(id)object {
  95. BOOL equal = NO;
  96. if ([object isKindOfClass:[GPBUnknownFieldSet class]]) {
  97. GPBUnknownFieldSet *set = (GPBUnknownFieldSet *)object;
  98. if ((fields_ == NULL) && (set->fields_ == NULL)) {
  99. equal = YES;
  100. } else if ((fields_ != NULL) && (set->fields_ != NULL)) {
  101. equal = CFEqual(fields_, set->fields_);
  102. }
  103. }
  104. return equal;
  105. }
  106. - (NSUInteger)hash {
  107. // Return the hash of the fields dictionary (or just some value).
  108. if (fields_) {
  109. return CFHash(fields_);
  110. }
  111. return (NSUInteger)[GPBUnknownFieldSet class];
  112. }
  113. #pragma mark - Public Methods
  114. - (BOOL)hasField:(int32_t)number {
  115. ssize_t key = number;
  116. return fields_ ? (CFDictionaryGetValue(fields_, (void *)key) != nil) : NO;
  117. }
  118. - (GPBField *)getField:(int32_t)number {
  119. ssize_t key = number;
  120. GPBField *result = fields_ ? CFDictionaryGetValue(fields_, (void *)key) : nil;
  121. return result;
  122. }
  123. - (NSUInteger)countOfFields {
  124. return fields_ ? CFDictionaryGetCount(fields_) : 0;
  125. }
  126. - (NSArray *)sortedFields {
  127. if (!fields_) return nil;
  128. size_t count = CFDictionaryGetCount(fields_);
  129. ssize_t keys[count];
  130. GPBField *values[count];
  131. CFDictionaryGetKeysAndValues(fields_, (const void **)keys,
  132. (const void **)values);
  133. struct GPBFieldPair {
  134. ssize_t key;
  135. GPBField *value;
  136. } pairs[count];
  137. for (size_t i = 0; i < count; ++i) {
  138. pairs[i].key = keys[i];
  139. pairs[i].value = values[i];
  140. };
  141. qsort_b(pairs, count, sizeof(struct GPBFieldPair),
  142. ^(const void *first, const void *second) {
  143. const struct GPBFieldPair *a = first;
  144. const struct GPBFieldPair *b = second;
  145. return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1);
  146. });
  147. for (size_t i = 0; i < count; ++i) {
  148. values[i] = pairs[i].value;
  149. };
  150. return [NSArray arrayWithObjects:values count:count];
  151. }
  152. #pragma mark - Internal Methods
  153. - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output {
  154. if (!fields_) return;
  155. size_t count = CFDictionaryGetCount(fields_);
  156. ssize_t keys[count];
  157. GPBField *values[count];
  158. CFDictionaryGetKeysAndValues(fields_, (const void **)keys,
  159. (const void **)values);
  160. if (count > 1) {
  161. struct GPBFieldPair {
  162. ssize_t key;
  163. GPBField *value;
  164. } pairs[count];
  165. for (size_t i = 0; i < count; ++i) {
  166. pairs[i].key = keys[i];
  167. pairs[i].value = values[i];
  168. };
  169. qsort_b(pairs, count, sizeof(struct GPBFieldPair),
  170. ^(const void *first, const void *second) {
  171. const struct GPBFieldPair *a = first;
  172. const struct GPBFieldPair *b = second;
  173. return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1);
  174. });
  175. for (size_t i = 0; i < count; ++i) {
  176. GPBField *value = pairs[i].value;
  177. [value writeToOutput:output];
  178. }
  179. } else {
  180. [values[0] writeToOutput:output];
  181. }
  182. }
  183. - (NSString *)description {
  184. NSMutableString *description = [NSMutableString
  185. stringWithFormat:@"<%@ %p>: TextFormat: {\n", [self class], self];
  186. NSString *textFormat = GPBTextFormatForUnknownFieldSet(self, @" ");
  187. [description appendString:textFormat];
  188. [description appendString:@"}"];
  189. return description;
  190. }
  191. static void GPBUnknownFieldSetSerializedSize(const void *key, const void *value,
  192. void *context) {
  193. #pragma unused(key)
  194. GPBField *field = value;
  195. size_t *result = context;
  196. *result += [field serializedSize];
  197. }
  198. - (size_t)serializedSize {
  199. size_t result = 0;
  200. if (fields_) {
  201. CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetSerializedSize,
  202. &result);
  203. }
  204. return result;
  205. }
  206. static void GPBUnknownFieldSetWriteAsMessageSetTo(const void *key,
  207. const void *value,
  208. void *context) {
  209. #pragma unused(key)
  210. GPBField *field = value;
  211. GPBCodedOutputStream *output = context;
  212. [field writeAsMessageSetExtensionToOutput:output];
  213. }
  214. - (void)writeAsMessageSetTo:(GPBCodedOutputStream *)output {
  215. if (fields_) {
  216. CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetWriteAsMessageSetTo,
  217. output);
  218. }
  219. }
  220. static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key,
  221. const void *value,
  222. void *context) {
  223. #pragma unused(key)
  224. GPBField *field = value;
  225. size_t *result = context;
  226. *result += [field serializedSizeAsMessageSetExtension];
  227. }
  228. - (size_t)serializedSizeAsMessageSet {
  229. size_t result = 0;
  230. if (fields_) {
  231. CFDictionaryApplyFunction(
  232. fields_, GPBUnknownFieldSetSerializedSizeAsMessageSet, &result);
  233. }
  234. return result;
  235. }
  236. - (NSData *)data {
  237. NSMutableData *data = [NSMutableData dataWithLength:self.serializedSize];
  238. GPBCodedOutputStream *output =
  239. [[GPBCodedOutputStream alloc] initWithData:data];
  240. [self writeToCodedOutputStream:output];
  241. [output release];
  242. return data;
  243. }
  244. + (BOOL)isFieldTag:(int32_t)tag {
  245. return GPBWireFormatGetTagWireType(tag) != GPBWireFormatEndGroup;
  246. }
  247. - (void)addField:(GPBField *)field {
  248. int32_t number = [field number];
  249. checkNumber(number);
  250. if (!fields_) {
  251. CFDictionaryKeyCallBacks keyCallBacks = {
  252. // See description above for reason for using custom dictionary.
  253. 0, GPBUnknownFieldSetKeyRetain, GPBUnknownFieldSetKeyRelease,
  254. GPBUnknownFieldSetCopyKeyDescription, GPBUnknownFieldSetKeyEqual,
  255. GPBUnknownFieldSetKeyHash,
  256. };
  257. fields_ = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &keyCallBacks,
  258. &kCFTypeDictionaryValueCallBacks);
  259. }
  260. ssize_t key = number;
  261. CFDictionarySetValue(fields_, (const void *)key, field);
  262. }
  263. - (GPBField *)mutableFieldForNumber:(int32_t)number create:(BOOL)create {
  264. ssize_t key = number;
  265. GPBField *existing =
  266. fields_ ? CFDictionaryGetValue(fields_, (const void *)key) : nil;
  267. if (!existing && create) {
  268. existing = [[GPBField alloc] initWithNumber:number];
  269. // This retains existing.
  270. [self addField:existing];
  271. [existing release];
  272. }
  273. return existing;
  274. }
  275. static void GPBUnknownFieldSetMergeUnknownFields(const void *key,
  276. const void *value,
  277. void *context) {
  278. #pragma unused(key)
  279. GPBField *field = value;
  280. GPBUnknownFieldSet *self = context;
  281. int32_t number = [field number];
  282. checkNumber(number);
  283. GPBField *oldField = [self mutableFieldForNumber:number create:NO];
  284. if (oldField) {
  285. [oldField mergeFromField:field];
  286. } else {
  287. // Merge only comes from GPBMessage's mergeFrom:, so it means we are on
  288. // mutable message and are an mutable instance, so make sure we need
  289. // mutable fields.
  290. GPBField *fieldCopy = [field copy];
  291. [self addField:fieldCopy];
  292. [fieldCopy release];
  293. }
  294. }
  295. - (void)mergeUnknownFields:(GPBUnknownFieldSet *)other {
  296. if (other && other->fields_) {
  297. CFDictionaryApplyFunction(other->fields_,
  298. GPBUnknownFieldSetMergeUnknownFields, self);
  299. }
  300. }
  301. - (void)mergeFromData:(NSData *)data {
  302. GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data];
  303. [self mergeFromCodedInputStream:input];
  304. [input checkLastTagWas:0];
  305. [input release];
  306. }
  307. - (void)mergeVarintField:(int32_t)number value:(int32_t)value {
  308. checkNumber(number);
  309. [[self mutableFieldForNumber:number create:YES] addVarint:value];
  310. }
  311. - (BOOL)mergeFieldFrom:(int32_t)tag input:(GPBCodedInputStream *)input {
  312. int32_t number = GPBWireFormatGetTagFieldNumber(tag);
  313. GPBCodedInputStreamState *state = &input->state_;
  314. switch (GPBWireFormatGetTagWireType(tag)) {
  315. case GPBWireFormatVarint: {
  316. GPBField *field = [self mutableFieldForNumber:number create:YES];
  317. [field addVarint:GPBCodedInputStreamReadInt64(state)];
  318. return YES;
  319. }
  320. case GPBWireFormatFixed64: {
  321. GPBField *field = [self mutableFieldForNumber:number create:YES];
  322. [field addFixed64:GPBCodedInputStreamReadFixed64(state)];
  323. return YES;
  324. }
  325. case GPBWireFormatLengthDelimited: {
  326. NSData *data = GPBCodedInputStreamReadRetainedData(state);
  327. GPBField *field = [self mutableFieldForNumber:number create:YES];
  328. [field addLengthDelimited:data];
  329. [data release];
  330. return YES;
  331. }
  332. case GPBWireFormatStartGroup: {
  333. GPBUnknownFieldSet *unknownFieldSet = [[GPBUnknownFieldSet alloc] init];
  334. [input readUnknownGroup:number message:unknownFieldSet];
  335. GPBField *field = [self mutableFieldForNumber:number create:YES];
  336. [field addGroup:unknownFieldSet];
  337. [unknownFieldSet release];
  338. return YES;
  339. }
  340. case GPBWireFormatEndGroup:
  341. return NO;
  342. case GPBWireFormatFixed32: {
  343. GPBField *field = [self mutableFieldForNumber:number create:YES];
  344. [field addFixed32:GPBCodedInputStreamReadFixed32(state)];
  345. return YES;
  346. }
  347. }
  348. }
  349. - (void)mergeMessageSetMessage:(int32_t)number data:(NSData *)messageData {
  350. [[self mutableFieldForNumber:number create:YES]
  351. addLengthDelimited:messageData];
  352. }
  353. - (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data {
  354. GPBField *field = [self mutableFieldForNumber:fieldNum create:YES];
  355. [field addLengthDelimited:data];
  356. }
  357. - (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input {
  358. while (YES) {
  359. int32_t tag = GPBCodedInputStreamReadTag(&input->state_);
  360. if (tag == 0 || ![self mergeFieldFrom:tag input:input]) {
  361. break;
  362. }
  363. }
  364. }
  365. - (void)getTags:(int32_t *)tags {
  366. if (!fields_) return;
  367. size_t count = CFDictionaryGetCount(fields_);
  368. ssize_t keys[count];
  369. CFDictionaryGetKeysAndValues(fields_, (const void **)keys, NULL);
  370. for (size_t i = 0; i < count; ++i) {
  371. tags[i] = (int32_t)keys[i];
  372. }
  373. }
  374. @end