GPBUnknownFieldSet.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 "GPBUnknownField_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. GPBUnknownField *field = value;
  76. GPBUnknownFieldSet *result = context;
  77. GPBUnknownField *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. - (GPBUnknownField *)getField:(int32_t)number {
  119. ssize_t key = number;
  120. GPBUnknownField *result =
  121. fields_ ? CFDictionaryGetValue(fields_, (void *)key) : nil;
  122. return result;
  123. }
  124. - (NSUInteger)countOfFields {
  125. return fields_ ? CFDictionaryGetCount(fields_) : 0;
  126. }
  127. - (NSArray *)sortedFields {
  128. if (!fields_) return nil;
  129. size_t count = CFDictionaryGetCount(fields_);
  130. ssize_t keys[count];
  131. GPBUnknownField *values[count];
  132. CFDictionaryGetKeysAndValues(fields_, (const void **)keys,
  133. (const void **)values);
  134. struct GPBFieldPair {
  135. ssize_t key;
  136. GPBUnknownField *value;
  137. } pairs[count];
  138. for (size_t i = 0; i < count; ++i) {
  139. pairs[i].key = keys[i];
  140. pairs[i].value = values[i];
  141. };
  142. qsort_b(pairs, count, sizeof(struct GPBFieldPair),
  143. ^(const void *first, const void *second) {
  144. const struct GPBFieldPair *a = first;
  145. const struct GPBFieldPair *b = second;
  146. return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1);
  147. });
  148. for (size_t i = 0; i < count; ++i) {
  149. values[i] = pairs[i].value;
  150. };
  151. return [NSArray arrayWithObjects:values count:count];
  152. }
  153. #pragma mark - Internal Methods
  154. - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output {
  155. if (!fields_) return;
  156. size_t count = CFDictionaryGetCount(fields_);
  157. ssize_t keys[count];
  158. GPBUnknownField *values[count];
  159. CFDictionaryGetKeysAndValues(fields_, (const void **)keys,
  160. (const void **)values);
  161. if (count > 1) {
  162. struct GPBFieldPair {
  163. ssize_t key;
  164. GPBUnknownField *value;
  165. } pairs[count];
  166. for (size_t i = 0; i < count; ++i) {
  167. pairs[i].key = keys[i];
  168. pairs[i].value = values[i];
  169. };
  170. qsort_b(pairs, count, sizeof(struct GPBFieldPair),
  171. ^(const void *first, const void *second) {
  172. const struct GPBFieldPair *a = first;
  173. const struct GPBFieldPair *b = second;
  174. return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1);
  175. });
  176. for (size_t i = 0; i < count; ++i) {
  177. GPBUnknownField *value = pairs[i].value;
  178. [value writeToOutput:output];
  179. }
  180. } else {
  181. [values[0] writeToOutput:output];
  182. }
  183. }
  184. - (NSString *)description {
  185. NSMutableString *description = [NSMutableString
  186. stringWithFormat:@"<%@ %p>: TextFormat: {\n", [self class], self];
  187. NSString *textFormat = GPBTextFormatForUnknownFieldSet(self, @" ");
  188. [description appendString:textFormat];
  189. [description appendString:@"}"];
  190. return description;
  191. }
  192. static void GPBUnknownFieldSetSerializedSize(const void *key, const void *value,
  193. void *context) {
  194. #pragma unused(key)
  195. GPBUnknownField *field = value;
  196. size_t *result = context;
  197. *result += [field serializedSize];
  198. }
  199. - (size_t)serializedSize {
  200. size_t result = 0;
  201. if (fields_) {
  202. CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetSerializedSize,
  203. &result);
  204. }
  205. return result;
  206. }
  207. static void GPBUnknownFieldSetWriteAsMessageSetTo(const void *key,
  208. const void *value,
  209. void *context) {
  210. #pragma unused(key)
  211. GPBUnknownField *field = value;
  212. GPBCodedOutputStream *output = context;
  213. [field writeAsMessageSetExtensionToOutput:output];
  214. }
  215. - (void)writeAsMessageSetTo:(GPBCodedOutputStream *)output {
  216. if (fields_) {
  217. CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetWriteAsMessageSetTo,
  218. output);
  219. }
  220. }
  221. static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key,
  222. const void *value,
  223. void *context) {
  224. #pragma unused(key)
  225. GPBUnknownField *field = value;
  226. size_t *result = context;
  227. *result += [field serializedSizeAsMessageSetExtension];
  228. }
  229. - (size_t)serializedSizeAsMessageSet {
  230. size_t result = 0;
  231. if (fields_) {
  232. CFDictionaryApplyFunction(
  233. fields_, GPBUnknownFieldSetSerializedSizeAsMessageSet, &result);
  234. }
  235. return result;
  236. }
  237. - (NSData *)data {
  238. NSMutableData *data = [NSMutableData dataWithLength:self.serializedSize];
  239. GPBCodedOutputStream *output =
  240. [[GPBCodedOutputStream alloc] initWithData:data];
  241. [self writeToCodedOutputStream:output];
  242. [output release];
  243. return data;
  244. }
  245. + (BOOL)isFieldTag:(int32_t)tag {
  246. return GPBWireFormatGetTagWireType(tag) != GPBWireFormatEndGroup;
  247. }
  248. - (void)addField:(GPBUnknownField *)field {
  249. int32_t number = [field number];
  250. checkNumber(number);
  251. if (!fields_) {
  252. CFDictionaryKeyCallBacks keyCallBacks = {
  253. // See description above for reason for using custom dictionary.
  254. 0, GPBUnknownFieldSetKeyRetain, GPBUnknownFieldSetKeyRelease,
  255. GPBUnknownFieldSetCopyKeyDescription, GPBUnknownFieldSetKeyEqual,
  256. GPBUnknownFieldSetKeyHash,
  257. };
  258. fields_ = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &keyCallBacks,
  259. &kCFTypeDictionaryValueCallBacks);
  260. }
  261. ssize_t key = number;
  262. CFDictionarySetValue(fields_, (const void *)key, field);
  263. }
  264. - (GPBUnknownField *)mutableFieldForNumber:(int32_t)number create:(BOOL)create {
  265. ssize_t key = number;
  266. GPBUnknownField *existing =
  267. fields_ ? CFDictionaryGetValue(fields_, (const void *)key) : nil;
  268. if (!existing && create) {
  269. existing = [[GPBUnknownField alloc] initWithNumber:number];
  270. // This retains existing.
  271. [self addField:existing];
  272. [existing release];
  273. }
  274. return existing;
  275. }
  276. static void GPBUnknownFieldSetMergeUnknownFields(const void *key,
  277. const void *value,
  278. void *context) {
  279. #pragma unused(key)
  280. GPBUnknownField *field = value;
  281. GPBUnknownFieldSet *self = context;
  282. int32_t number = [field number];
  283. checkNumber(number);
  284. GPBUnknownField *oldField = [self mutableFieldForNumber:number create:NO];
  285. if (oldField) {
  286. [oldField mergeFromField:field];
  287. } else {
  288. // Merge only comes from GPBMessage's mergeFrom:, so it means we are on
  289. // mutable message and are an mutable instance, so make sure we need
  290. // mutable fields.
  291. GPBUnknownField *fieldCopy = [field copy];
  292. [self addField:fieldCopy];
  293. [fieldCopy release];
  294. }
  295. }
  296. - (void)mergeUnknownFields:(GPBUnknownFieldSet *)other {
  297. if (other && other->fields_) {
  298. CFDictionaryApplyFunction(other->fields_,
  299. GPBUnknownFieldSetMergeUnknownFields, self);
  300. }
  301. }
  302. - (void)mergeFromData:(NSData *)data {
  303. GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data];
  304. [self mergeFromCodedInputStream:input];
  305. [input checkLastTagWas:0];
  306. [input release];
  307. }
  308. - (void)mergeVarintField:(int32_t)number value:(int32_t)value {
  309. checkNumber(number);
  310. [[self mutableFieldForNumber:number create:YES] addVarint:value];
  311. }
  312. - (BOOL)mergeFieldFrom:(int32_t)tag input:(GPBCodedInputStream *)input {
  313. int32_t number = GPBWireFormatGetTagFieldNumber(tag);
  314. GPBCodedInputStreamState *state = &input->state_;
  315. switch (GPBWireFormatGetTagWireType(tag)) {
  316. case GPBWireFormatVarint: {
  317. GPBUnknownField *field = [self mutableFieldForNumber:number create:YES];
  318. [field addVarint:GPBCodedInputStreamReadInt64(state)];
  319. return YES;
  320. }
  321. case GPBWireFormatFixed64: {
  322. GPBUnknownField *field = [self mutableFieldForNumber:number create:YES];
  323. [field addFixed64:GPBCodedInputStreamReadFixed64(state)];
  324. return YES;
  325. }
  326. case GPBWireFormatLengthDelimited: {
  327. NSData *data = GPBCodedInputStreamReadRetainedBytes(state);
  328. GPBUnknownField *field = [self mutableFieldForNumber:number create:YES];
  329. [field addLengthDelimited:data];
  330. [data release];
  331. return YES;
  332. }
  333. case GPBWireFormatStartGroup: {
  334. GPBUnknownFieldSet *unknownFieldSet = [[GPBUnknownFieldSet alloc] init];
  335. [input readUnknownGroup:number message:unknownFieldSet];
  336. GPBUnknownField *field = [self mutableFieldForNumber:number create:YES];
  337. [field addGroup:unknownFieldSet];
  338. [unknownFieldSet release];
  339. return YES;
  340. }
  341. case GPBWireFormatEndGroup:
  342. return NO;
  343. case GPBWireFormatFixed32: {
  344. GPBUnknownField *field = [self mutableFieldForNumber:number create:YES];
  345. [field addFixed32:GPBCodedInputStreamReadFixed32(state)];
  346. return YES;
  347. }
  348. }
  349. }
  350. - (void)mergeMessageSetMessage:(int32_t)number data:(NSData *)messageData {
  351. [[self mutableFieldForNumber:number create:YES]
  352. addLengthDelimited:messageData];
  353. }
  354. - (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data {
  355. GPBUnknownField *field = [self mutableFieldForNumber:fieldNum create:YES];
  356. [field addLengthDelimited:data];
  357. }
  358. - (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input {
  359. while (YES) {
  360. int32_t tag = GPBCodedInputStreamReadTag(&input->state_);
  361. if (tag == 0 || ![self mergeFieldFrom:tag input:input]) {
  362. break;
  363. }
  364. }
  365. }
  366. - (void)getTags:(int32_t *)tags {
  367. if (!fields_) return;
  368. size_t count = CFDictionaryGetCount(fields_);
  369. ssize_t keys[count];
  370. CFDictionaryGetKeysAndValues(fields_, (const void **)keys, NULL);
  371. for (size_t i = 0; i < count; ++i) {
  372. tags[i] = (int32_t)keys[i];
  373. }
  374. }
  375. @end