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