Format the runtime sources.

pull/10650/head
Thomas Van Lenten 3 years ago
parent 5d0b2175c3
commit 189f6325d4
  1. 43
      objectivec/GPBArray.m
  2. 56
      objectivec/GPBCodedInputStream.m
  3. 105
      objectivec/GPBCodedOutputStream.m
  4. 154
      objectivec/GPBDescriptor.m
  5. 75
      objectivec/GPBDictionary.m
  6. 116
      objectivec/GPBExtensionInternals.m
  7. 24
      objectivec/GPBExtensionRegistry.m
  8. 179
      objectivec/GPBMessage.m
  9. 1
      objectivec/GPBProtocolBuffers.m
  10. 25
      objectivec/GPBRootObject.m
  11. 65
      objectivec/GPBUnknownField.m
  12. 59
      objectivec/GPBUnknownFieldSet.m
  13. 379
      objectivec/GPBUtilities.m
  14. 67
      objectivec/GPBWellKnownTypes.m

@ -2056,19 +2056,15 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
return [[[self alloc] initWithValidationFunction:func] autorelease]; return [[[self alloc] initWithValidationFunction:func] autorelease];
} }
+ (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func + (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func rawValue:(int32_t)value {
rawValue:(int32_t)value { return [[[self alloc] initWithValidationFunction:func rawValues:&value count:1] autorelease];
return [[[self alloc] initWithValidationFunction:func
rawValues:&value
count:1] autorelease];
} }
+ (instancetype)arrayWithValueArray:(GPBEnumArray *)array { + (instancetype)arrayWithValueArray:(GPBEnumArray *)array {
return [[(GPBEnumArray*)[self alloc] initWithValueArray:array] autorelease]; return [[(GPBEnumArray *)[self alloc] initWithValueArray:array] autorelease];
} }
+ (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func + (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)count {
capacity:(NSUInteger)count {
return [[[self alloc] initWithValidationFunction:func capacity:count] autorelease]; return [[[self alloc] initWithValidationFunction:func capacity:count] autorelease];
} }
@ -2091,7 +2087,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
} }
- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func
rawValues:(const int32_t [])values rawValues:(const int32_t[])values
count:(NSUInteger)count { count:(NSUInteger)count {
self = [self initWithValidationFunction:func]; self = [self initWithValidationFunction:func];
if (self) { if (self) {
@ -2103,17 +2099,16 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
_count = count; _count = count;
} else { } else {
[self release]; [self release];
[NSException raise:NSMallocException [NSException
format:@"Failed to allocate %lu bytes", raise:NSMallocException
(unsigned long)(count * sizeof(int32_t))]; format:@"Failed to allocate %lu bytes", (unsigned long)(count * sizeof(int32_t))];
} }
} }
} }
return self; return self;
} }
- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)count {
capacity:(NSUInteger)count {
self = [self initWithValidationFunction:func]; self = [self initWithValidationFunction:func];
if (self && count) { if (self && count) {
[self internalResizeToCapacity:count]; [self internalResizeToCapacity:count];
@ -2122,8 +2117,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
} }
- (instancetype)copyWithZone:(NSZone *)zone { - (instancetype)copyWithZone:(NSZone *)zone {
return [[GPBEnumArray allocWithZone:zone] return [[GPBEnumArray allocWithZone:zone] initWithValidationFunction:_validationFunc
initWithValidationFunction:_validationFunc
rawValues:_values rawValues:_values
count:_count]; count:_count];
} }
@ -2197,7 +2191,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
// clang-format on // clang-format on
- (int32_t)valueAtIndex:(NSUInteger)index { - (int32_t)valueAtIndex:(NSUInteger)index {
// clang-format off // clang-format off
//%PDDM-EXPAND VALIDATE_RANGE(index, _count) //%PDDM-EXPAND VALIDATE_RANGE(index, _count)
// This block of code is generated, do not edit it directly. // This block of code is generated, do not edit it directly.
@ -2207,7 +2201,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
(unsigned long)index, (unsigned long)_count]; (unsigned long)index, (unsigned long)_count];
} }
//%PDDM-EXPAND-END VALIDATE_RANGE(index, _count) //%PDDM-EXPAND-END VALIDATE_RANGE(index, _count)
// clang-format on // clang-format on
int32_t result = _values[index]; int32_t result = _values[index];
if (!_validationFunc(result)) { if (!_validationFunc(result)) {
result = kGPBUnrecognizedEnumeratorValue; result = kGPBUnrecognizedEnumeratorValue;
@ -2216,7 +2210,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
} }
- (int32_t)rawValueAtIndex:(NSUInteger)index { - (int32_t)rawValueAtIndex:(NSUInteger)index {
// clang-format off // clang-format off
//%PDDM-EXPAND VALIDATE_RANGE(index, _count) //%PDDM-EXPAND VALIDATE_RANGE(index, _count)
// This block of code is generated, do not edit it directly. // This block of code is generated, do not edit it directly.
@ -2226,16 +2220,18 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
(unsigned long)index, (unsigned long)_count]; (unsigned long)index, (unsigned long)_count];
} }
//%PDDM-EXPAND-END VALIDATE_RANGE(index, _count) //%PDDM-EXPAND-END VALIDATE_RANGE(index, _count)
// clang-format on // clang-format on
return _values[index]; return _values[index];
} }
- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block { - (void)enumerateValuesWithBlock:(void(NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))
block {
[self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block];
} }
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
usingBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block { usingBlock:(void(NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))
block {
// NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok).
BOOL stop = NO; BOOL stop = NO;
GPBEnumValidationFunc func = _validationFunc; GPBEnumValidationFunc func = _validationFunc;
@ -2472,8 +2468,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
} }
- (void)dealloc { - (void)dealloc {
NSAssert(!_autocreator, NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@",
@"%@: Autocreator must be cleared before release, autocreator: %@",
[self class], _autocreator); [self class], _autocreator);
[_array release]; [_array release];
[super dealloc]; [super dealloc];

@ -36,8 +36,7 @@
#import "GPBUtilities_PackagePrivate.h" #import "GPBUtilities_PackagePrivate.h"
#import "GPBWireFormat.h" #import "GPBWireFormat.h"
NSString *const GPBCodedInputStreamException = NSString *const GPBCodedInputStreamException = GPBNSStringifySymbol(GPBCodedInputStreamException);
GPBNSStringifySymbol(GPBCodedInputStreamException);
NSString *const GPBCodedInputStreamUnderlyingErrorKey = NSString *const GPBCodedInputStreamUnderlyingErrorKey =
GPBNSStringifySymbol(GPBCodedInputStreamUnderlyingErrorKey); GPBNSStringifySymbol(GPBCodedInputStreamUnderlyingErrorKey);
@ -55,16 +54,14 @@ static const NSUInteger kDefaultRecursionLimit = 100;
static void RaiseException(NSInteger code, NSString *reason) { static void RaiseException(NSInteger code, NSString *reason) {
NSDictionary *errorInfo = nil; NSDictionary *errorInfo = nil;
if ([reason length]) { if ([reason length]) {
errorInfo = @{ GPBErrorReasonKey: reason }; errorInfo = @{GPBErrorReasonKey : reason};
} }
NSError *error = [NSError errorWithDomain:GPBCodedInputStreamErrorDomain NSError *error = [NSError errorWithDomain:GPBCodedInputStreamErrorDomain
code:code code:code
userInfo:errorInfo]; userInfo:errorInfo];
NSDictionary *exceptionInfo = NSDictionary *exceptionInfo = @{GPBCodedInputStreamUnderlyingErrorKey : error};
@{ GPBCodedInputStreamUnderlyingErrorKey: error }; [[NSException exceptionWithName:GPBCodedInputStreamException reason:reason
[[NSException exceptionWithName:GPBCodedInputStreamException
reason:reason
userInfo:exceptionInfo] raise]; userInfo:exceptionInfo] raise];
} }
@ -215,8 +212,7 @@ int32_t GPBCodedInputStreamReadTag(GPBCodedInputStreamState *state) {
state->lastTag = ReadRawVarint32(state); state->lastTag = ReadRawVarint32(state);
// Tags have to include a valid wireformat. // Tags have to include a valid wireformat.
if (!GPBWireFormatIsValidTag(state->lastTag)) { if (!GPBWireFormatIsValidTag(state->lastTag)) {
RaiseException(GPBCodedInputStreamErrorInvalidTag, RaiseException(GPBCodedInputStreamErrorInvalidTag, @"Invalid wireformat in tag.");
@"Invalid wireformat in tag.");
} }
// Zero is not a valid field number. // Zero is not a valid field number.
if (GPBWireFormatGetTagFieldNumber(state->lastTag) == 0) { if (GPBWireFormatGetTagFieldNumber(state->lastTag) == 0) {
@ -226,8 +222,7 @@ int32_t GPBCodedInputStreamReadTag(GPBCodedInputStreamState *state) {
return state->lastTag; return state->lastTag;
} }
NSString *GPBCodedInputStreamReadRetainedString( NSString *GPBCodedInputStreamReadRetainedString(GPBCodedInputStreamState *state) {
GPBCodedInputStreamState *state) {
int32_t size = ReadRawVarint32(state); int32_t size = ReadRawVarint32(state);
NSString *result; NSString *result;
if (size == 0) { if (size == 0) {
@ -254,28 +249,24 @@ NSData *GPBCodedInputStreamReadRetainedBytes(GPBCodedInputStreamState *state) {
int32_t size = ReadRawVarint32(state); int32_t size = ReadRawVarint32(state);
if (size < 0) return nil; if (size < 0) return nil;
CheckSize(state, size); CheckSize(state, size);
NSData *result = [[NSData alloc] initWithBytes:state->bytes + state->bufferPos NSData *result = [[NSData alloc] initWithBytes:state->bytes + state->bufferPos length:size];
length:size];
state->bufferPos += size; state->bufferPos += size;
return result; return result;
} }
NSData *GPBCodedInputStreamReadRetainedBytesNoCopy( NSData *GPBCodedInputStreamReadRetainedBytesNoCopy(GPBCodedInputStreamState *state) {
GPBCodedInputStreamState *state) {
int32_t size = ReadRawVarint32(state); int32_t size = ReadRawVarint32(state);
if (size < 0) return nil; if (size < 0) return nil;
CheckSize(state, size); CheckSize(state, size);
// Cast is safe because freeWhenDone is NO. // Cast is safe because freeWhenDone is NO.
NSData *result = [[NSData alloc] NSData *result = [[NSData alloc] initWithBytesNoCopy:(void *)(state->bytes + state->bufferPos)
initWithBytesNoCopy:(void *)(state->bytes + state->bufferPos)
length:size length:size
freeWhenDone:NO]; freeWhenDone:NO];
state->bufferPos += size; state->bufferPos += size;
return result; return result;
} }
size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state, size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state, size_t byteLimit) {
size_t byteLimit) {
byteLimit += state->bufferPos; byteLimit += state->bufferPos;
size_t oldLimit = state->currentLimit; size_t oldLimit = state->currentLimit;
if (byteLimit > oldLimit) { if (byteLimit > oldLimit) {
@ -285,8 +276,7 @@ size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state,
return oldLimit; return oldLimit;
} }
void GPBCodedInputStreamPopLimit(GPBCodedInputStreamState *state, void GPBCodedInputStreamPopLimit(GPBCodedInputStreamState *state, size_t oldLimit) {
size_t oldLimit) {
state->currentLimit = oldLimit; state->currentLimit = oldLimit;
} }
@ -295,12 +285,10 @@ size_t GPBCodedInputStreamBytesUntilLimit(GPBCodedInputStreamState *state) {
} }
BOOL GPBCodedInputStreamIsAtEnd(GPBCodedInputStreamState *state) { BOOL GPBCodedInputStreamIsAtEnd(GPBCodedInputStreamState *state) {
return (state->bufferPos == state->bufferSize) || return (state->bufferPos == state->bufferSize) || (state->bufferPos == state->currentLimit);
(state->bufferPos == state->currentLimit);
} }
void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, int32_t value) {
int32_t value) {
if (state->lastTag != value) { if (state->lastTag != value) {
RaiseException(GPBCodedInputStreamErrorInvalidTag, @"Unexpected tag read"); RaiseException(GPBCodedInputStreamErrorInvalidTag, @"Unexpected tag read");
} }
@ -360,8 +348,8 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state,
case GPBWireFormatStartGroup: case GPBWireFormatStartGroup:
[self skipMessage]; [self skipMessage];
GPBCodedInputStreamCheckLastTagWas( GPBCodedInputStreamCheckLastTagWas(
&state_, GPBWireFormatMakeTag(GPBWireFormatGetTagFieldNumber(tag), &state_,
GPBWireFormatEndGroup)); GPBWireFormatMakeTag(GPBWireFormatGetTagFieldNumber(tag), GPBWireFormatEndGroup));
return YES; return YES;
case GPBWireFormatEndGroup: case GPBWireFormatEndGroup:
return NO; return NO;
@ -438,18 +426,17 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state,
CheckRecursionLimit(&state_); CheckRecursionLimit(&state_);
++state_.recursionDepth; ++state_.recursionDepth;
[message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry]; [message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry];
GPBCodedInputStreamCheckLastTagWas( GPBCodedInputStreamCheckLastTagWas(&state_,
&state_, GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup)); GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup));
--state_.recursionDepth; --state_.recursionDepth;
} }
- (void)readUnknownGroup:(int32_t)fieldNumber - (void)readUnknownGroup:(int32_t)fieldNumber message:(GPBUnknownFieldSet *)message {
message:(GPBUnknownFieldSet *)message {
CheckRecursionLimit(&state_); CheckRecursionLimit(&state_);
++state_.recursionDepth; ++state_.recursionDepth;
[message mergeFromCodedInputStream:self]; [message mergeFromCodedInputStream:self];
GPBCodedInputStreamCheckLastTagWas( GPBCodedInputStreamCheckLastTagWas(&state_,
&state_, GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup)); GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup));
--state_.recursionDepth; --state_.recursionDepth;
} }
@ -473,8 +460,7 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state,
int32_t length = ReadRawVarint32(&state_); int32_t length = ReadRawVarint32(&state_);
size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length); size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length);
++state_.recursionDepth; ++state_.recursionDepth;
GPBDictionaryReadEntry(mapDictionary, self, extensionRegistry, field, GPBDictionaryReadEntry(mapDictionary, self, extensionRegistry, field, parentMessage);
parentMessage);
GPBCodedInputStreamCheckLastTagWas(&state_, 0); GPBCodedInputStreamCheckLastTagWas(&state_, 0);
--state_.recursionDepth; --state_.recursionDepth;
GPBCodedInputStreamPopLimit(&state_, oldLimit); GPBCodedInputStreamPopLimit(&state_, oldLimit);

@ -67,8 +67,7 @@ static void GPBRefreshBuffer(GPBOutputBufferState *state) {
[NSException raise:GPBCodedOutputStreamException_OutOfSpace format:@""]; [NSException raise:GPBCodedOutputStreamException_OutOfSpace format:@""];
} }
if (state->position != 0) { if (state->position != 0) {
NSInteger written = NSInteger written = [state->output write:state->bytes maxLength:state->position];
[state->output write:state->bytes maxLength:state->position];
if (written != (NSInteger)state->position) { if (written != (NSInteger)state->position) {
[NSException raise:GPBCodedOutputStreamException_WriteFailed format:@""]; [NSException raise:GPBCodedOutputStreamException_WriteFailed format:@""];
} }
@ -118,27 +117,24 @@ static void GPBWriteInt32NoTag(GPBOutputBufferState *state, int32_t value) {
} }
} }
static void GPBWriteUInt32(GPBOutputBufferState *state, int32_t fieldNumber, static void GPBWriteUInt32(GPBOutputBufferState *state, int32_t fieldNumber, uint32_t value) {
uint32_t value) {
GPBWriteTagWithFormat(state, fieldNumber, GPBWireFormatVarint); GPBWriteTagWithFormat(state, fieldNumber, GPBWireFormatVarint);
GPBWriteRawVarint32(state, value); GPBWriteRawVarint32(state, value);
} }
static void GPBWriteTagWithFormat(GPBOutputBufferState *state, static void GPBWriteTagWithFormat(GPBOutputBufferState *state, uint32_t fieldNumber,
uint32_t fieldNumber, GPBWireFormat format) { GPBWireFormat format) {
GPBWriteRawVarint32(state, GPBWireFormatMakeTag(fieldNumber, format)); GPBWriteRawVarint32(state, GPBWireFormatMakeTag(fieldNumber, format));
} }
static void GPBWriteRawLittleEndian32(GPBOutputBufferState *state, static void GPBWriteRawLittleEndian32(GPBOutputBufferState *state, int32_t value) {
int32_t value) {
GPBWriteRawByte(state, (value)&0xFF); GPBWriteRawByte(state, (value)&0xFF);
GPBWriteRawByte(state, (value >> 8) & 0xFF); GPBWriteRawByte(state, (value >> 8) & 0xFF);
GPBWriteRawByte(state, (value >> 16) & 0xFF); GPBWriteRawByte(state, (value >> 16) & 0xFF);
GPBWriteRawByte(state, (value >> 24) & 0xFF); GPBWriteRawByte(state, (value >> 24) & 0xFF);
} }
static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, int64_t value) {
int64_t value) {
GPBWriteRawByte(state, (int32_t)(value)&0xFF); GPBWriteRawByte(state, (int32_t)(value)&0xFF);
GPBWriteRawByte(state, (int32_t)(value >> 8) & 0xFF); GPBWriteRawByte(state, (int32_t)(value >> 8) & 0xFF);
GPBWriteRawByte(state, (int32_t)(value >> 16) & 0xFF); GPBWriteRawByte(state, (int32_t)(value >> 16) & 0xFF);
@ -170,8 +166,7 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
// This initializer isn't exposed, but it is the designated initializer. // This initializer isn't exposed, but it is the designated initializer.
// Setting OutputStream and NSData is to control the buffering behavior/size // Setting OutputStream and NSData is to control the buffering behavior/size
// of the work, but that is more obvious via the bufferSize: version. // of the work, but that is more obvious via the bufferSize: version.
- (instancetype)initWithOutputStream:(NSOutputStream *)output - (instancetype)initWithOutputStream:(NSOutputStream *)output data:(NSMutableData *)data {
data:(NSMutableData *)data {
if ((self = [super init])) { if ((self = [super init])) {
buffer_ = [data retain]; buffer_ = [data retain];
state_.bytes = [data mutableBytes]; state_.bytes = [data mutableBytes];
@ -184,8 +179,7 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
+ (instancetype)streamWithOutputStream:(NSOutputStream *)output { + (instancetype)streamWithOutputStream:(NSOutputStream *)output {
NSMutableData *data = [NSMutableData dataWithLength:PAGE_SIZE]; NSMutableData *data = [NSMutableData dataWithLength:PAGE_SIZE];
return [[[self alloc] initWithOutputStream:output return [[[self alloc] initWithOutputStream:output data:data] autorelease];
data:data] autorelease];
} }
+ (instancetype)streamWithData:(NSMutableData *)data { + (instancetype)streamWithData:(NSMutableData *)data {
@ -277,8 +271,7 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
return; return;
} }
const char *quickString = const char *quickString = CFStringGetCStringPtr((CFStringRef)value, kCFStringEncodingUTF8);
CFStringGetCStringPtr((CFStringRef)value, kCFStringEncodingUTF8);
// Fast path: Most strings are short, if the buffer already has space, // Fast path: Most strings are short, if the buffer already has space,
// add to it directly. // add to it directly.
@ -300,9 +293,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
remainingRange:NULL]; remainingRange:NULL];
} }
if (result) { if (result) {
NSAssert2((usedBufferLength == length), NSAssert2((usedBufferLength == length), @"Our UTF8 calc was wrong? %tu vs %zd",
@"Our UTF8 calc was wrong? %tu vs %zd", usedBufferLength, usedBufferLength, length);
length);
state_.position += usedBufferLength; state_.position += usedBufferLength;
return; return;
} }
@ -311,9 +303,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
} else { } else {
// Slow path: just get it as data and write it out. // Slow path: just get it as data and write it out.
NSData *utf8Data = [value dataUsingEncoding:NSUTF8StringEncoding]; NSData *utf8Data = [value dataUsingEncoding:NSUTF8StringEncoding];
NSAssert2(([utf8Data length] == length), NSAssert2(([utf8Data length] == length), @"Strings UTF8 length was wrong? %tu vs %zd",
@"Strings UTF8 length was wrong? %tu vs %zd", [utf8Data length], [utf8Data length], length);
length);
[self writeRawData:utf8Data]; [self writeRawData:utf8Data];
} }
} }
@ -333,14 +324,12 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
[self writeGroupNoTag:fieldNumber value:value]; [self writeGroupNoTag:fieldNumber value:value];
} }
- (void)writeUnknownGroupNoTag:(int32_t)fieldNumber - (void)writeUnknownGroupNoTag:(int32_t)fieldNumber value:(const GPBUnknownFieldSet *)value {
value:(const GPBUnknownFieldSet *)value {
[value writeToCodedOutputStream:self]; [value writeToCodedOutputStream:self];
GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatEndGroup); GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatEndGroup);
} }
- (void)writeUnknownGroup:(int32_t)fieldNumber - (void)writeUnknownGroup:(int32_t)fieldNumber value:(GPBUnknownFieldSet *)value {
value:(GPBUnknownFieldSet *)value {
GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatStartGroup); GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatStartGroup);
[self writeUnknownGroupNoTag:fieldNumber value:value]; [self writeUnknownGroupNoTag:fieldNumber value:value];
} }
@ -879,23 +868,18 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
// clang-format on // clang-format on
- (void)writeMessageSetExtension:(int32_t)fieldNumber - (void)writeMessageSetExtension:(int32_t)fieldNumber value:(GPBMessage *)value {
value:(GPBMessage *)value { GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWireFormatStartGroup);
GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem,
GPBWireFormatStartGroup);
GPBWriteUInt32(&state_, GPBWireFormatMessageSetTypeId, fieldNumber); GPBWriteUInt32(&state_, GPBWireFormatMessageSetTypeId, fieldNumber);
[self writeMessage:GPBWireFormatMessageSetMessage value:value]; [self writeMessage:GPBWireFormatMessageSetMessage value:value];
GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWireFormatEndGroup);
GPBWireFormatEndGroup);
} }
- (void)writeRawMessageSetExtension:(int32_t)fieldNumber value:(NSData *)value { - (void)writeRawMessageSetExtension:(int32_t)fieldNumber value:(NSData *)value {
GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWireFormatStartGroup);
GPBWireFormatStartGroup);
GPBWriteUInt32(&state_, GPBWireFormatMessageSetTypeId, fieldNumber); GPBWriteUInt32(&state_, GPBWireFormatMessageSetTypeId, fieldNumber);
[self writeBytes:GPBWireFormatMessageSetMessage value:value]; [self writeBytes:GPBWireFormatMessageSetMessage value:value];
GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWireFormatEndGroup);
GPBWireFormatEndGroup);
} }
- (void)flush { - (void)flush {
@ -912,9 +896,7 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
[self writeRawPtr:[data bytes] offset:0 length:[data length]]; [self writeRawPtr:[data bytes] offset:0 length:[data length]];
} }
- (void)writeRawPtr:(const void *)value - (void)writeRawPtr:(const void *)value offset:(size_t)offset length:(size_t)length {
offset:(size_t)offset
length:(size_t)length {
if (value == nil || length == 0) { if (value == nil || length == 0) {
return; return;
} }
@ -929,8 +911,7 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
// Write extends past current buffer. Fill the rest of this buffer and // Write extends past current buffer. Fill the rest of this buffer and
// flush. // flush.
size_t bytesWritten = bufferBytesLeft; size_t bytesWritten = bufferBytesLeft;
memcpy(state_.bytes + state_.position, ((uint8_t *)value) + offset, memcpy(state_.bytes + state_.position, ((uint8_t *)value) + offset, bytesWritten);
bytesWritten);
offset += bytesWritten; offset += bytesWritten;
length -= bytesWritten; length -= bytesWritten;
state_.position = bufferLength; state_.position = bufferLength;
@ -993,13 +974,9 @@ size_t GPBComputeFloatSizeNoTag(Float32 value) {
return LITTLE_ENDIAN_32_SIZE; return LITTLE_ENDIAN_32_SIZE;
} }
size_t GPBComputeUInt64SizeNoTag(uint64_t value) { size_t GPBComputeUInt64SizeNoTag(uint64_t value) { return GPBComputeRawVarint64Size(value); }
return GPBComputeRawVarint64Size(value);
}
size_t GPBComputeInt64SizeNoTag(int64_t value) { size_t GPBComputeInt64SizeNoTag(int64_t value) { return GPBComputeRawVarint64Size(value); }
return GPBComputeRawVarint64Size(value);
}
size_t GPBComputeInt32SizeNoTag(int32_t value) { size_t GPBComputeInt32SizeNoTag(int32_t value) {
if (value >= 0) { if (value >= 0) {
@ -1034,13 +1011,9 @@ size_t GPBComputeStringSizeNoTag(NSString *value) {
return GPBComputeRawVarint32SizeForInteger(length) + length; return GPBComputeRawVarint32SizeForInteger(length) + length;
} }
size_t GPBComputeGroupSizeNoTag(GPBMessage *value) { size_t GPBComputeGroupSizeNoTag(GPBMessage *value) { return [value serializedSize]; }
return [value serializedSize];
}
size_t GPBComputeUnknownGroupSizeNoTag(GPBUnknownFieldSet *value) { size_t GPBComputeUnknownGroupSizeNoTag(GPBUnknownFieldSet *value) { return value.serializedSize; }
return value.serializedSize;
}
size_t GPBComputeMessageSizeNoTag(GPBMessage *value) { size_t GPBComputeMessageSizeNoTag(GPBMessage *value) {
size_t size = [value serializedSize]; size_t size = [value serializedSize];
@ -1052,13 +1025,9 @@ size_t GPBComputeBytesSizeNoTag(NSData *value) {
return GPBComputeRawVarint32SizeForInteger(valueLength) + valueLength; return GPBComputeRawVarint32SizeForInteger(valueLength) + valueLength;
} }
size_t GPBComputeUInt32SizeNoTag(int32_t value) { size_t GPBComputeUInt32SizeNoTag(int32_t value) { return GPBComputeRawVarint32Size(value); }
return GPBComputeRawVarint32Size(value);
}
size_t GPBComputeEnumSizeNoTag(int32_t value) { size_t GPBComputeEnumSizeNoTag(int32_t value) { return GPBComputeInt32SizeNoTag(value); }
return GPBComputeInt32SizeNoTag(value);
}
size_t GPBComputeSFixed32SizeNoTag(int32_t value) { size_t GPBComputeSFixed32SizeNoTag(int32_t value) {
#pragma unused(value) #pragma unused(value)
@ -1118,10 +1087,8 @@ size_t GPBComputeGroupSize(int32_t fieldNumber, GPBMessage *value) {
return GPBComputeTagSize(fieldNumber) * 2 + GPBComputeGroupSizeNoTag(value); return GPBComputeTagSize(fieldNumber) * 2 + GPBComputeGroupSizeNoTag(value);
} }
size_t GPBComputeUnknownGroupSize(int32_t fieldNumber, size_t GPBComputeUnknownGroupSize(int32_t fieldNumber, GPBUnknownFieldSet *value) {
GPBUnknownFieldSet *value) { return GPBComputeTagSize(fieldNumber) * 2 + GPBComputeUnknownGroupSizeNoTag(value);
return GPBComputeTagSize(fieldNumber) * 2 +
GPBComputeUnknownGroupSizeNoTag(value);
} }
size_t GPBComputeMessageSize(int32_t fieldNumber, GPBMessage *value) { size_t GPBComputeMessageSize(int32_t fieldNumber, GPBMessage *value) {
@ -1153,27 +1120,23 @@ size_t GPBComputeSInt32Size(int32_t fieldNumber, int32_t value) {
} }
size_t GPBComputeSInt64Size(int32_t fieldNumber, int64_t value) { size_t GPBComputeSInt64Size(int32_t fieldNumber, int64_t value) {
return GPBComputeTagSize(fieldNumber) + return GPBComputeTagSize(fieldNumber) + GPBComputeRawVarint64Size(GPBEncodeZigZag64(value));
GPBComputeRawVarint64Size(GPBEncodeZigZag64(value));
} }
size_t GPBComputeMessageSetExtensionSize(int32_t fieldNumber, size_t GPBComputeMessageSetExtensionSize(int32_t fieldNumber, GPBMessage *value) {
GPBMessage *value) {
return GPBComputeTagSize(GPBWireFormatMessageSetItem) * 2 + return GPBComputeTagSize(GPBWireFormatMessageSetItem) * 2 +
GPBComputeUInt32Size(GPBWireFormatMessageSetTypeId, fieldNumber) + GPBComputeUInt32Size(GPBWireFormatMessageSetTypeId, fieldNumber) +
GPBComputeMessageSize(GPBWireFormatMessageSetMessage, value); GPBComputeMessageSize(GPBWireFormatMessageSetMessage, value);
} }
size_t GPBComputeRawMessageSetExtensionSize(int32_t fieldNumber, size_t GPBComputeRawMessageSetExtensionSize(int32_t fieldNumber, NSData *value) {
NSData *value) {
return GPBComputeTagSize(GPBWireFormatMessageSetItem) * 2 + return GPBComputeTagSize(GPBWireFormatMessageSetItem) * 2 +
GPBComputeUInt32Size(GPBWireFormatMessageSetTypeId, fieldNumber) + GPBComputeUInt32Size(GPBWireFormatMessageSetTypeId, fieldNumber) +
GPBComputeBytesSize(GPBWireFormatMessageSetMessage, value); GPBComputeBytesSize(GPBWireFormatMessageSetMessage, value);
} }
size_t GPBComputeTagSize(int32_t fieldNumber) { size_t GPBComputeTagSize(int32_t fieldNumber) {
return GPBComputeRawVarint32Size( return GPBComputeRawVarint32Size(GPBWireFormatMakeTag(fieldNumber, GPBWireFormatVarint));
GPBWireFormatMakeTag(fieldNumber, GPBWireFormatVarint));
} }
size_t GPBComputeWireFormatTagSize(int field_number, GPBDataType dataType) { size_t GPBComputeWireFormatTagSize(int field_number, GPBDataType dataType) {

@ -32,9 +32,9 @@
#import <objc/runtime.h> #import <objc/runtime.h>
#import "GPBMessage_PackagePrivate.h"
#import "GPBUtilities_PackagePrivate.h" #import "GPBUtilities_PackagePrivate.h"
#import "GPBWireFormat.h" #import "GPBWireFormat.h"
#import "GPBMessage_PackagePrivate.h"
// Direct access is use for speed, to avoid even internally declaring things // Direct access is use for speed, to avoid even internally declaring things
// read/write, etc. The warning is enabled in the project to ensure code calling // read/write, etc. The warning is enabled in the project to ensure code calling
@ -48,16 +48,15 @@ static const char kParentClassValueKey = 0;
static const char kClassNameSuffixKey = 0; static const char kClassNameSuffixKey = 0;
// Utility function to generate selectors on the fly. // Utility function to generate selectors on the fly.
static SEL SelFromStrings(const char *prefix, const char *middle, static SEL SelFromStrings(const char *prefix, const char *middle, const char *suffix,
const char *suffix, BOOL takesArg) { BOOL takesArg) {
if (prefix == NULL && suffix == NULL && !takesArg) { if (prefix == NULL && suffix == NULL && !takesArg) {
return sel_getUid(middle); return sel_getUid(middle);
} }
const size_t prefixLen = prefix != NULL ? strlen(prefix) : 0; const size_t prefixLen = prefix != NULL ? strlen(prefix) : 0;
const size_t middleLen = strlen(middle); const size_t middleLen = strlen(middle);
const size_t suffixLen = suffix != NULL ? strlen(suffix) : 0; const size_t suffixLen = suffix != NULL ? strlen(suffix) : 0;
size_t totalLen = size_t totalLen = prefixLen + middleLen + suffixLen + 1; // include space for null on end.
prefixLen + middleLen + suffixLen + 1; // include space for null on end.
if (takesArg) { if (takesArg) {
totalLen += 1; totalLen += 1;
} }
@ -82,12 +81,10 @@ static SEL SelFromStrings(const char *prefix, const char *middle,
return result; return result;
} }
static NSArray *NewFieldsArrayForHasIndex(int hasIndex, static NSArray *NewFieldsArrayForHasIndex(int hasIndex, NSArray *allMessageFields)
NSArray *allMessageFields)
__attribute__((ns_returns_retained)); __attribute__((ns_returns_retained));
static NSArray *NewFieldsArrayForHasIndex(int hasIndex, static NSArray *NewFieldsArrayForHasIndex(int hasIndex, NSArray *allMessageFields) {
NSArray *allMessageFields) {
NSMutableArray *result = [[NSMutableArray alloc] init]; NSMutableArray *result = [[NSMutableArray alloc] init];
for (GPBFieldDescriptor *fieldDesc in allMessageFields) { for (GPBFieldDescriptor *fieldDesc in allMessageFields) {
if (fieldDesc->description_->hasIndex == hasIndex) { if (fieldDesc->description_->hasIndex == hasIndex) {
@ -111,8 +108,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
@synthesize file = file_; @synthesize file = file_;
@synthesize wireFormat = wireFormat_; @synthesize wireFormat = wireFormat_;
+ (instancetype) + (instancetype)allocDescriptorForClass:(Class)messageClass
allocDescriptorForClass:(Class)messageClass
rootClass:(Class)rootClass rootClass:(Class)rootClass
file:(GPBFileDescriptor *)file file:(GPBFileDescriptor *)file
fields:(void *)fieldDescriptions fields:(void *)fieldDescriptions
@ -124,12 +120,9 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
(void)rootClass; (void)rootClass;
NSMutableArray *fields = nil; NSMutableArray *fields = nil;
GPBFileSyntax syntax = file.syntax; GPBFileSyntax syntax = file.syntax;
BOOL fieldsIncludeDefault = BOOL fieldsIncludeDefault = (flags & GPBDescriptorInitializationFlag_FieldsWithDefault) != 0;
(flags & GPBDescriptorInitializationFlag_FieldsWithDefault) != 0; BOOL usesClassRefs = (flags & GPBDescriptorInitializationFlag_UsesClassRefs) != 0;
BOOL usesClassRefs = BOOL proto3OptionalKnown = (flags & GPBDescriptorInitializationFlag_Proto3OptionalKnown) != 0;
(flags & GPBDescriptorInitializationFlag_UsesClassRefs) != 0;
BOOL proto3OptionalKnown =
(flags & GPBDescriptorInitializationFlag_Proto3OptionalKnown) != 0;
void *desc; void *desc;
for (uint32_t i = 0; i < fieldCount; ++i) { for (uint32_t i = 0; i < fieldCount; ++i) {
@ -193,10 +186,9 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
for (uint32_t i = 0, hasIndex = firstHasIndex; i < count; ++i, --hasIndex) { for (uint32_t i = 0, hasIndex = firstHasIndex; i < count; ++i, --hasIndex) {
const char *name = oneofNames[i]; const char *name = oneofNames[i];
NSArray *fieldsForOneof = NewFieldsArrayForHasIndex(hasIndex, fields_); NSArray *fieldsForOneof = NewFieldsArrayForHasIndex(hasIndex, fields_);
NSCAssert(fieldsForOneof.count > 0, NSCAssert(fieldsForOneof.count > 0, @"No fields for this oneof? (%s:%d)", name, hasIndex);
@"No fields for this oneof? (%s:%d)", name, hasIndex); GPBOneofDescriptor *oneofDescriptor = [[GPBOneofDescriptor alloc] initWithName:name
GPBOneofDescriptor *oneofDescriptor = fields:fieldsForOneof];
[[GPBOneofDescriptor alloc] initWithName:name fields:fieldsForOneof];
[oneofs addObject:oneofDescriptor]; [oneofs addObject:oneofDescriptor];
[oneofDescriptor release]; [oneofDescriptor release];
[fieldsForOneof release]; [fieldsForOneof release];
@ -210,8 +202,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
NSValue *extraInfoValue = [NSValue valueWithPointer:extraTextFormatInfo]; NSValue *extraInfoValue = [NSValue valueWithPointer:extraTextFormatInfo];
for (GPBFieldDescriptor *fieldDescriptor in fields_) { for (GPBFieldDescriptor *fieldDescriptor in fields_) {
if (fieldDescriptor->description_->flags & GPBFieldTextFormatNameCustom) { if (fieldDescriptor->description_->flags & GPBFieldTextFormatNameCustom) {
objc_setAssociatedObject(fieldDescriptor, &kTextFormatExtraValueKey, objc_setAssociatedObject(fieldDescriptor, &kTextFormatExtraValueKey, extraInfoValue,
extraInfoValue,
OBJC_ASSOCIATION_RETAIN_NONATOMIC); OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} }
} }
@ -224,9 +215,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
} }
- (void)setupContainingMessageClass:(Class)messageClass { - (void)setupContainingMessageClass:(Class)messageClass {
objc_setAssociatedObject(self, &kParentClassValueKey, objc_setAssociatedObject(self, &kParentClassValueKey, messageClass, OBJC_ASSOCIATION_ASSIGN);
messageClass,
OBJC_ASSOCIATION_ASSIGN);
} }
- (void)setupContainingMessageClassName:(const char *)msgClassName { - (void)setupContainingMessageClassName:(const char *)msgClassName {
@ -240,9 +229,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
- (void)setupMessageClassNameSuffix:(NSString *)suffix { - (void)setupMessageClassNameSuffix:(NSString *)suffix {
if (suffix.length) { if (suffix.length) {
objc_setAssociatedObject(self, &kClassNameSuffixKey, objc_setAssociatedObject(self, &kClassNameSuffixKey, suffix, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
suffix,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} }
} }
@ -260,9 +247,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
GPBFileDescriptor *file = self.file; GPBFileDescriptor *file = self.file;
NSString *objcPrefix = file.objcPrefix; NSString *objcPrefix = file.objcPrefix;
if (objcPrefix && ![className hasPrefix:objcPrefix]) { if (objcPrefix && ![className hasPrefix:objcPrefix]) {
NSAssert(0, NSAssert(0, @"Class didn't have correct prefix? (%@ - %@)", className, objcPrefix);
@"Class didn't have correct prefix? (%@ - %@)",
className, objcPrefix);
return nil; return nil;
} }
GPBDescriptor *parent = self.containingType; GPBDescriptor *parent = self.containingType;
@ -274,19 +259,16 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
NSString *suffix = objc_getAssociatedObject(parent, &kClassNameSuffixKey); NSString *suffix = objc_getAssociatedObject(parent, &kClassNameSuffixKey);
if (suffix) { if (suffix) {
if (![parentClassName hasSuffix:suffix]) { if (![parentClassName hasSuffix:suffix]) {
NSAssert(0, NSAssert(0, @"ParentMessage class didn't have correct suffix? (%@ - %@)", className,
@"ParentMessage class didn't have correct suffix? (%@ - %@)", suffix);
className, suffix);
return nil; return nil;
} }
parentClassName = parentClassName = [parentClassName substringToIndex:(parentClassName.length - suffix.length)];
[parentClassName substringToIndex:(parentClassName.length - suffix.length)];
} }
NSString *parentPrefix = [parentClassName stringByAppendingString:@"_"]; NSString *parentPrefix = [parentClassName stringByAppendingString:@"_"];
if (![className hasPrefix:parentPrefix]) { if (![className hasPrefix:parentPrefix]) {
NSAssert(0, NSAssert(0, @"Class didn't have the correct parent name prefix? (%@ - %@)", parentPrefix,
@"Class didn't have the correct parent name prefix? (%@ - %@)", className);
parentPrefix, className);
return nil; return nil;
} }
name = [className substringFromIndex:parentPrefix.length]; name = [className substringFromIndex:parentPrefix.length];
@ -298,9 +280,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
NSString *suffix = objc_getAssociatedObject(self, &kClassNameSuffixKey); NSString *suffix = objc_getAssociatedObject(self, &kClassNameSuffixKey);
if (suffix) { if (suffix) {
if (![name hasSuffix:suffix]) { if (![name hasSuffix:suffix]) {
NSAssert(0, NSAssert(0, @"Message class didn't have correct suffix? (%@ - %@)", name, suffix);
@"Message class didn't have correct suffix? (%@ - %@)",
name, suffix);
return nil; return nil;
} }
name = [name substringToIndex:(name.length - suffix.length)]; name = [name substringToIndex:(name.length - suffix.length)];
@ -372,8 +352,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
return self; return self;
} }
- (instancetype)initWithPackage:(NSString *)package - (instancetype)initWithPackage:(NSString *)package syntax:(GPBFileSyntax)syntax {
syntax:(GPBFileSyntax)syntax {
self = [super init]; self = [super init];
if (self) { if (self) {
package_ = [package copy]; package_ = [package copy];
@ -414,7 +393,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
} }
- (NSString *)name { - (NSString *)name {
return (NSString * _Nonnull)@(name_); return (NSString *_Nonnull)@(name_);
} }
- (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber { - (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber {
@ -444,19 +423,17 @@ uint32_t GPBFieldTag(GPBFieldDescriptor *self) {
// Maps are repeated messages on the wire. // Maps are repeated messages on the wire.
format = GPBWireFormatForType(GPBDataTypeMessage, NO); format = GPBWireFormatForType(GPBDataTypeMessage, NO);
} else { } else {
format = GPBWireFormatForType(description->dataType, format =
((description->flags & GPBFieldPacked) != 0)); GPBWireFormatForType(description->dataType, ((description->flags & GPBFieldPacked) != 0));
} }
return GPBWireFormatMakeTag(description->number, format); return GPBWireFormatMakeTag(description->number, format);
} }
uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
GPBMessageFieldDescription *description = self->description_; GPBMessageFieldDescription *description = self->description_;
NSCAssert((description->flags & GPBFieldRepeated) != 0, NSCAssert((description->flags & GPBFieldRepeated) != 0, @"Only valid on repeated fields");
@"Only valid on repeated fields");
GPBWireFormat format = GPBWireFormat format =
GPBWireFormatForType(description->dataType, GPBWireFormatForType(description->dataType, ((description->flags & GPBFieldPacked) == 0));
((description->flags & GPBFieldPacked) == 0));
return GPBWireFormatMakeTag(description->number, format); return GPBWireFormatMakeTag(description->number, format);
} }
@ -516,10 +493,8 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
// - not repeated/map // - not repeated/map
// - not in a oneof (negative has index) // - not in a oneof (negative has index)
// - not a message (the flag doesn't make sense for messages) // - not a message (the flag doesn't make sense for messages)
BOOL clearOnZero = ((syntax == GPBFileSyntaxProto3) && BOOL clearOnZero = ((syntax == GPBFileSyntaxProto3) && !isMapOrArray &&
!isMapOrArray && (coreDesc->hasIndex >= 0) && !isMessage);
(coreDesc->hasIndex >= 0) &&
!isMessage);
if (clearOnZero) { if (clearOnZero) {
coreDesc->flags |= GPBFieldClearHasIvarOnZero; coreDesc->flags |= GPBFieldClearHasIvarOnZero;
} }
@ -534,8 +509,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
// It is a single field; it gets has/setHas selectors if... // It is a single field; it gets has/setHas selectors if...
// - not in a oneof (negative has index) // - not in a oneof (negative has index)
// - not clearing on zero // - not clearing on zero
if ((coreDesc->hasIndex >= 0) && if ((coreDesc->hasIndex >= 0) && ((coreDesc->flags & GPBFieldClearHasIvarOnZero) == 0)) {
((coreDesc->flags & GPBFieldClearHasIvarOnZero) == 0)) {
hasOrCountSel_ = SelFromStrings("has", coreDesc->name, NULL, NO); hasOrCountSel_ = SelFromStrings("has", coreDesc->name, NULL, NO);
setHasSel_ = SelFromStrings("setHas", coreDesc->name, NULL, YES); setHasSel_ = SelFromStrings("setHas", coreDesc->name, NULL, YES);
} }
@ -556,11 +530,9 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
} }
} else if (dataType == GPBDataTypeEnum) { } else if (dataType == GPBDataTypeEnum) {
if ((coreDesc->flags & GPBFieldHasEnumDescriptor) != 0) { if ((coreDesc->flags & GPBFieldHasEnumDescriptor) != 0) {
enumHandling_.enumDescriptor_ = enumHandling_.enumDescriptor_ = coreDesc->dataTypeSpecific.enumDescFunc();
coreDesc->dataTypeSpecific.enumDescFunc();
} else { } else {
enumHandling_.enumVerifier_ = enumHandling_.enumVerifier_ = coreDesc->dataTypeSpecific.enumVerifier;
coreDesc->dataTypeSpecific.enumVerifier;
} }
} }
@ -576,8 +548,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
memcpy(&length, bytes, sizeof(length)); memcpy(&length, bytes, sizeof(length));
length = ntohl(length); length = ntohl(length);
bytes += sizeof(length); bytes += sizeof(length);
defaultValue_.valueData = defaultValue_.valueData = [[NSData alloc] initWithBytes:bytes length:length];
[[NSData alloc] initWithBytes:bytes length:length];
} }
} }
} }
@ -586,8 +557,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
} }
- (void)dealloc { - (void)dealloc {
if (description_->dataType == GPBDataTypeBytes && if (description_->dataType == GPBDataTypeBytes && !(description_->flags & GPBFieldRepeated)) {
!(description_->flags & GPBFieldRepeated)) {
[defaultValue_.valueData release]; [defaultValue_.valueData release];
} }
[super dealloc]; [super dealloc];
@ -606,7 +576,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
} }
- (NSString *)name { - (NSString *)name {
return (NSString * _Nonnull)@(description_->name); return (NSString *_Nonnull)@(description_->name);
} }
- (BOOL)isRequired { - (BOOL)isRequired {
@ -666,8 +636,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
} }
- (BOOL)isValidEnumValue:(int32_t)value { - (BOOL)isValidEnumValue:(int32_t)value {
NSAssert(description_->dataType == GPBDataTypeEnum, NSAssert(description_->dataType == GPBDataTypeEnum, @"Field Must be of type GPBDataTypeEnum");
@"Field Must be of type GPBDataTypeEnum");
if (description_->flags & GPBFieldHasEnumDescriptor) { if (description_->flags & GPBFieldHasEnumDescriptor) {
return enumHandling_.enumDescriptor_.enumVerifier(value); return enumHandling_.enumDescriptor_.enumVerifier(value);
} else { } else {
@ -703,15 +672,13 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
- (NSString *)textFormatName { - (NSString *)textFormatName {
if ((description_->flags & GPBFieldTextFormatNameCustom) != 0) { if ((description_->flags & GPBFieldTextFormatNameCustom) != 0) {
NSValue *extraInfoValue = NSValue *extraInfoValue = objc_getAssociatedObject(self, &kTextFormatExtraValueKey);
objc_getAssociatedObject(self, &kTextFormatExtraValueKey);
// Support can be left out at generation time. // Support can be left out at generation time.
if (!extraInfoValue) { if (!extraInfoValue) {
return nil; return nil;
} }
const uint8_t *extraTextFormatInfo = [extraInfoValue pointerValue]; const uint8_t *extraTextFormatInfo = [extraInfoValue pointerValue];
return GPBDecodeTextFormatName(extraTextFormatInfo, GPBFieldNumber(self), return GPBDecodeTextFormatName(extraTextFormatInfo, GPBFieldNumber(self), self.name);
self.name);
} }
// The logic here has to match SetCommonFieldVariables() from // The logic here has to match SetCommonFieldVariables() from
@ -726,8 +693,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
} }
// Remove "Array" from the end for repeated fields. // Remove "Array" from the end for repeated fields.
if (((description_->flags & GPBFieldRepeated) != 0) && if (((description_->flags & GPBFieldRepeated) != 0) && [name hasSuffix:@"Array"]) {
[name hasSuffix:@"Array"]) {
name = [name substringToIndex:(len - 5)]; name = [name substringToIndex:(len - 5)];
len = [name length]; len = [name length];
} }
@ -739,8 +705,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
if (firstChar >= 'a' && firstChar <= 'z') { if (firstChar >= 'a' && firstChar <= 'z') {
NSString *firstCharString = NSString *firstCharString =
[NSString stringWithFormat:@"%C", (unichar)(firstChar - 'a' + 'A')]; [NSString stringWithFormat:@"%C", (unichar)(firstChar - 'a' + 'A')];
NSString *result = NSString *result = [name stringByReplacingCharactersInRange:NSMakeRange(0, 1)
[name stringByReplacingCharactersInRange:NSMakeRange(0, 1)
withString:firstCharString]; withString:firstCharString];
return result; return result;
} }
@ -784,8 +749,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
@synthesize name = name_; @synthesize name = name_;
@synthesize enumVerifier = enumVerifier_; @synthesize enumVerifier = enumVerifier_;
+ (instancetype) + (instancetype)allocDescriptorForName:(NSString *)name
allocDescriptorForName:(NSString *)name
valueNames:(const char *)valueNames valueNames:(const char *)valueNames
values:(const int32_t *)values values:(const int32_t *)values
count:(uint32_t)valueCount count:(uint32_t)valueCount
@ -798,8 +762,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
return descriptor; return descriptor;
} }
+ (instancetype) + (instancetype)allocDescriptorForName:(NSString *)name
allocDescriptorForName:(NSString *)name
valueNames:(const char *)valueNames valueNames:(const char *)valueNames
values:(const int32_t *)values values:(const int32_t *)values
count:(uint32_t)valueCount count:(uint32_t)valueCount
@ -911,8 +874,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
// Find the EnumValue descriptor and its index. // Find the EnumValue descriptor and its index.
BOOL foundIt = NO; BOOL foundIt = NO;
uint32_t valueDescriptorIndex; uint32_t valueDescriptorIndex;
for (valueDescriptorIndex = 0; valueDescriptorIndex < valueCount_; for (valueDescriptorIndex = 0; valueDescriptorIndex < valueCount_; ++valueDescriptorIndex) {
++valueDescriptorIndex) {
if (values_[valueDescriptorIndex] == number) { if (values_[valueDescriptorIndex] == number) {
foundIt = YES; foundIt = YES;
break; break;
@ -955,8 +917,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
// See if it is in the map of special format handling. // See if it is in the map of special format handling.
if (extraTextFormatInfo_) { if (extraTextFormatInfo_) {
result = GPBDecodeTextFormatName(extraTextFormatInfo_, result = GPBDecodeTextFormatName(extraTextFormatInfo_, (int32_t)index, shortName);
(int32_t)index, shortName);
} }
// Logic here needs to match what objectivec_enum.cc does in the proto // Logic here needs to match what objectivec_enum.cc does in the proto
// compiler. // compiler.
@ -1005,16 +966,14 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
GPBDataType type = description_->dataType; GPBDataType type = description_->dataType;
if (type == GPBDataTypeBytes) { if (type == GPBDataTypeBytes) {
// Data stored as a length prefixed c-string in descriptor records. // Data stored as a length prefixed c-string in descriptor records.
const uint8_t *bytes = const uint8_t *bytes = (const uint8_t *)description_->defaultValue.valueData;
(const uint8_t *)description_->defaultValue.valueData;
if (bytes) { if (bytes) {
uint32_t length; uint32_t length;
memcpy(&length, bytes, sizeof(length)); memcpy(&length, bytes, sizeof(length));
// The length is stored in network byte order. // The length is stored in network byte order.
length = ntohl(length); length = ntohl(length);
bytes += sizeof(length); bytes += sizeof(length);
defaultValue_.valueData = defaultValue_.valueData = [[NSData alloc] initWithBytes:bytes length:length];
[[NSData alloc] initWithBytes:bytes length:length];
} }
} else if (type == GPBDataTypeMessage || type == GPBDataTypeGroup) { } else if (type == GPBDataTypeMessage || type == GPBDataTypeGroup) {
// The default is looked up in -defaultValue instead since extensions // The default is looked up in -defaultValue instead since extensions
@ -1032,8 +991,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
} }
- (void)dealloc { - (void)dealloc {
if ((description_->dataType == GPBDataTypeBytes) && if ((description_->dataType == GPBDataTypeBytes) && !GPBExtensionIsRepeated(description_)) {
!GPBExtensionIsRepeated(description_)) {
[defaultValue_.valueData release]; [defaultValue_.valueData release];
} }
[super dealloc]; [super dealloc];
@ -1046,7 +1004,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
} }
- (NSString *)singletonName { - (NSString *)singletonName {
return (NSString * _Nonnull)@(description_->singletonName); return (NSString *_Nonnull)@(description_->singletonName);
} }
- (const char *)singletonNameC { - (const char *)singletonNameC {
@ -1062,15 +1020,12 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
} }
- (GPBWireFormat)wireType { - (GPBWireFormat)wireType {
return GPBWireFormatForType(description_->dataType, return GPBWireFormatForType(description_->dataType, GPBExtensionIsPacked(description_));
GPBExtensionIsPacked(description_));
} }
- (GPBWireFormat)alternateWireType { - (GPBWireFormat)alternateWireType {
NSAssert(GPBExtensionIsRepeated(description_), NSAssert(GPBExtensionIsRepeated(description_), @"Only valid on repeated extensions");
@"Only valid on repeated extensions"); return GPBWireFormatForType(description_->dataType, !GPBExtensionIsPacked(description_));
return GPBWireFormatForType(description_->dataType,
!GPBExtensionIsPacked(description_));
} }
- (BOOL)isRepeated { - (BOOL)isRepeated {
@ -1126,8 +1081,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
return @(defaultValue_.valueUInt64); return @(defaultValue_.valueUInt64);
case GPBDataTypeBytes: case GPBDataTypeBytes:
// Like message fields, the default is zero length data. // Like message fields, the default is zero length data.
return (defaultValue_.valueData ? defaultValue_.valueData return (defaultValue_.valueData ? defaultValue_.valueData : GPBEmptyNSData());
: GPBEmptyNSData());
case GPBDataTypeString: case GPBDataTypeString:
// Like message fields, the default is zero length string. // Like message fields, the default is zero length string.
return (defaultValue_.valueString ? defaultValue_.valueString : @""); return (defaultValue_.valueString ? defaultValue_.valueString : @"");

@ -59,8 +59,7 @@
// Example usage: // Example usage:
// #if GPB_STATIC_ANALYZER_ONLY(5621, 5623) ... #endif // #if GPB_STATIC_ANALYZER_ONLY(5621, 5623) ... #endif
#define GPB_STATIC_ANALYZER_ONLY(BEGIN_APPLE_BUILD_VERSION, END_APPLE_BUILD_VERSION) \ #define GPB_STATIC_ANALYZER_ONLY(BEGIN_APPLE_BUILD_VERSION, END_APPLE_BUILD_VERSION) \
(defined(__clang_analyzer__) && \ (defined(__clang_analyzer__) && (__apple_build_version__ >= BEGIN_APPLE_BUILD_VERSION && \
(__apple_build_version__ >= BEGIN_APPLE_BUILD_VERSION && \
__apple_build_version__ <= END_APPLE_BUILD_VERSION)) __apple_build_version__ <= END_APPLE_BUILD_VERSION))
enum { enum {
@ -349,8 +348,7 @@ size_t GPBDictionaryComputeSizeInternalHelper(NSDictionary *dict, GPBFieldDescri
} }
void GPBDictionaryWriteToStreamInternalHelper(GPBCodedOutputStream *outputStream, void GPBDictionaryWriteToStreamInternalHelper(GPBCodedOutputStream *outputStream,
NSDictionary *dict, NSDictionary *dict, GPBFieldDescriptor *field) {
GPBFieldDescriptor *field) {
NSCAssert(field.mapKeyDataType == GPBDataTypeString, @"Unexpected key type"); NSCAssert(field.mapKeyDataType == GPBDataTypeString, @"Unexpected key type");
GPBDataType mapValueType = GPBGetFieldDataType(field); GPBDataType mapValueType = GPBGetFieldDataType(field);
uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited);
@ -374,7 +372,7 @@ void GPBDictionaryWriteToStreamInternalHelper(GPBCodedOutputStream *outputStream
BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field) { BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field) {
NSCAssert(field.mapKeyDataType == GPBDataTypeString, @"Unexpected key type"); NSCAssert(field.mapKeyDataType == GPBDataTypeString, @"Unexpected key type");
NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeMessage, @"Unexpected value type"); NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeMessage, @"Unexpected value type");
#pragma unused(field) // For when asserts are off in release. #pragma unused(field) // For when asserts are off in release.
GPBMessage *msg; GPBMessage *msg;
NSEnumerator *objects = [dict objectEnumerator]; NSEnumerator *objects = [dict objectEnumerator];
while ((msg = [objects nextObject])) { while ((msg = [objects nextObject])) {
@ -386,11 +384,8 @@ BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, GPBFieldDescri
} }
// Note: if the type is an object, it the retain pass back to the caller. // Note: if the type is an object, it the retain pass back to the caller.
static void ReadValue(GPBCodedInputStream *stream, static void ReadValue(GPBCodedInputStream *stream, GPBGenericValue *valueToFill, GPBDataType type,
GPBGenericValue *valueToFill, id<GPBExtensionRegistry> registry, GPBFieldDescriptor *field) {
GPBDataType type,
id<GPBExtensionRegistry>registry,
GPBFieldDescriptor *field) {
switch (type) { switch (type) {
case GPBDataTypeBool: case GPBDataTypeBool:
valueToFill->valueBool = GPBCodedInputStreamReadBool(&stream->state_); valueToFill->valueBool = GPBCodedInputStreamReadBool(&stream->state_);
@ -455,10 +450,8 @@ static void ReadValue(GPBCodedInputStream *stream,
} }
} }
void GPBDictionaryReadEntry(id mapDictionary, void GPBDictionaryReadEntry(id mapDictionary, GPBCodedInputStream *stream,
GPBCodedInputStream *stream, id<GPBExtensionRegistry> registry, GPBFieldDescriptor *field,
id<GPBExtensionRegistry>registry,
GPBFieldDescriptor *field,
GPBMessage *parentMessage) { GPBMessage *parentMessage) {
GPBDataType keyDataType = field.mapKeyDataType; GPBDataType keyDataType = field.mapKeyDataType;
GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType valueDataType = GPBGetFieldDataType(field);
@ -472,8 +465,7 @@ void GPBDictionaryReadEntry(id mapDictionary,
} }
GPBCodedInputStreamState *state = &stream->state_; GPBCodedInputStreamState *state = &stream->state_;
uint32_t keyTag = uint32_t keyTag = GPBWireFormatMakeTag(kMapKeyFieldNumber, GPBWireFormatForType(keyDataType, NO));
GPBWireFormatMakeTag(kMapKeyFieldNumber, GPBWireFormatForType(keyDataType, NO));
uint32_t valueTag = uint32_t valueTag =
GPBWireFormatMakeTag(kMapValueFieldNumber, GPBWireFormatForType(valueDataType, NO)); GPBWireFormatMakeTag(kMapValueFieldNumber, GPBWireFormatForType(valueDataType, NO));
@ -488,7 +480,7 @@ void GPBDictionaryReadEntry(id mapDictionary,
// zero signals EOF / limit reached // zero signals EOF / limit reached
break; break;
} else { // Unknown } else { // Unknown
if (![stream skipField:tag]){ if (![stream skipField:tag]) {
hitError = YES; hitError = YES;
break; break;
} }
@ -542,8 +534,7 @@ void GPBDictionaryReadEntry(id mapDictionary,
} }
#endif #endif
// mapDictionary is an NSMutableDictionary // mapDictionary is an NSMutableDictionary
[(NSMutableDictionary *)mapDictionary setObject:value.valueString [(NSMutableDictionary *)mapDictionary setObject:value.valueString forKey:key.valueString];
forKey:key.valueString];
} else { } else {
if (valueDataType == GPBDataTypeEnum) { if (valueDataType == GPBDataTypeEnum) {
if (GPBHasPreservingUnknownEnumSemantics([parentMessage descriptor].file.syntax) || if (GPBHasPreservingUnknownEnumSemantics([parentMessage descriptor].file.syntax) ||
@ -11749,8 +11740,8 @@ void GPBDictionaryReadEntry(id mapDictionary,
} }
- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func
rawValues:(const int32_t [])rawValues rawValues:(const int32_t[])rawValues
forKeys:(const BOOL [])keys forKeys:(const BOOL[])keys
count:(NSUInteger)count { count:(NSUInteger)count {
self = [super init]; self = [super init];
if (self) { if (self) {
@ -11790,8 +11781,7 @@ void GPBDictionaryReadEntry(id mapDictionary,
#if !defined(NS_BLOCK_ASSERTIONS) #if !defined(NS_BLOCK_ASSERTIONS)
- (void)dealloc { - (void)dealloc {
NSAssert(!_autocreator, NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@",
@"%@: Autocreator must be cleared before release, autocreator: %@",
[self class], _autocreator); [self class], _autocreator);
[super dealloc]; [super dealloc];
} }
@ -11840,7 +11830,7 @@ void GPBDictionaryReadEntry(id mapDictionary,
return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0);
} }
- (BOOL)getEnum:(int32_t*)value forKey:(BOOL)key { - (BOOL)getEnum:(int32_t *)value forKey:(BOOL)key {
int idx = (key ? 1 : 0); int idx = (key ? 1 : 0);
if (_valueSet[idx]) { if (_valueSet[idx]) {
if (value) { if (value) {
@ -11855,7 +11845,7 @@ void GPBDictionaryReadEntry(id mapDictionary,
return NO; return NO;
} }
- (BOOL)getRawValue:(int32_t*)rawValue forKey:(BOOL)key { - (BOOL)getRawValue:(int32_t *)rawValue forKey:(BOOL)key {
int idx = (key ? 1 : 0); int idx = (key ? 1 : 0);
if (_valueSet[idx]) { if (_valueSet[idx]) {
if (rawValue) { if (rawValue) {
@ -11866,8 +11856,8 @@ void GPBDictionaryReadEntry(id mapDictionary,
return NO; return NO;
} }
- (void)enumerateKeysAndRawValuesUsingBlock: - (void)enumerateKeysAndRawValuesUsingBlock:(void(NS_NOESCAPE ^)(BOOL key, int32_t value,
(void (NS_NOESCAPE ^)(BOOL key, int32_t value, BOOL *stop))block { BOOL *stop))block {
BOOL stop = NO; BOOL stop = NO;
if (_valueSet[0]) { if (_valueSet[0]) {
block(NO, _values[0], &stop); block(NO, _values[0], &stop);
@ -11877,8 +11867,8 @@ void GPBDictionaryReadEntry(id mapDictionary,
} }
} }
- (void)enumerateKeysAndEnumsUsingBlock: - (void)enumerateKeysAndEnumsUsingBlock:(void(NS_NOESCAPE ^)(BOOL key, int32_t rawValue,
(void (NS_NOESCAPE ^)(BOOL key, int32_t rawValue, BOOL *stop))block { BOOL *stop))block {
BOOL stop = NO; BOOL stop = NO;
GPBEnumValidationFunc func = _validationFunc; GPBEnumValidationFunc func = _validationFunc;
int32_t validatedValue; int32_t validatedValue;
@ -11956,7 +11946,7 @@ void GPBDictionaryReadEntry(id mapDictionary,
} }
} }
- (void)enumerateForTextFormat:(void (NS_NOESCAPE ^)(id keyObj, id valueObj))block { - (void)enumerateForTextFormat:(void(NS_NOESCAPE ^)(id keyObj, id valueObj))block {
if (_valueSet[0]) { if (_valueSet[0]) {
block(@"false", @(_values[0])); block(@"false", @(_values[0]));
} }
@ -11965,8 +11955,7 @@ void GPBDictionaryReadEntry(id mapDictionary,
} }
} }
- (void)setGPBGenericValue:(GPBGenericValue *)value - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key {
forGPBGenericValueKey:(GPBGenericValue *)key {
int idx = (key->valueBool ? 1 : 0); int idx = (key->valueBool ? 1 : 0);
_values[idx] = value->valueInt32; _values[idx] = value->valueInt32;
_valueSet[idx] = YES; _valueSet[idx] = YES;
@ -11989,8 +11978,7 @@ void GPBDictionaryReadEntry(id mapDictionary,
- (void)setEnum:(int32_t)value forKey:(BOOL)key { - (void)setEnum:(int32_t)value forKey:(BOOL)key {
if (!_validationFunc(value)) { if (!_validationFunc(value)) {
[NSException raise:NSInvalidArgumentException [NSException raise:NSInvalidArgumentException
format:@"GPBBoolEnumDictionary: Attempt to set an unknown enum value (%d)", format:@"GPBBoolEnumDictionary: Attempt to set an unknown enum value (%d)", value];
value];
} }
int idx = (key ? 1 : 0); int idx = (key ? 1 : 0);
_values[idx] = value; _values[idx] = value;
@ -12027,8 +12015,7 @@ void GPBDictionaryReadEntry(id mapDictionary,
} }
- (void)dealloc { - (void)dealloc {
NSAssert(!_autocreator, NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@",
@"%@: Autocreator must be cleared before release, autocreator: %@",
[self class], _autocreator); [self class], _autocreator);
[_dictionary release]; [_dictionary release];
[super dealloc]; [super dealloc];
@ -12036,14 +12023,12 @@ void GPBDictionaryReadEntry(id mapDictionary,
#pragma mark Required NSDictionary overrides #pragma mark Required NSDictionary overrides
- (instancetype)initWithObjects:(const id [])objects - (instancetype)initWithObjects:(const id[])objects
forKeys:(const id<NSCopying> [])keys forKeys:(const id<NSCopying>[])keys
count:(NSUInteger)count { count:(NSUInteger)count {
self = [super init]; self = [super init];
if (self) { if (self) {
_dictionary = [[NSMutableDictionary alloc] initWithObjects:objects _dictionary = [[NSMutableDictionary alloc] initWithObjects:objects forKeys:keys count:count];
forKeys:keys
count:count];
} }
return self; return self;
} }
@ -12116,16 +12101,12 @@ void GPBDictionaryReadEntry(id mapDictionary,
} }
} }
- (void)enumerateKeysAndObjectsUsingBlock:(void (NS_NOESCAPE ^)(id key, - (void)enumerateKeysAndObjectsUsingBlock:(void(NS_NOESCAPE ^)(id key, id obj, BOOL *stop))block {
id obj,
BOOL *stop))block {
[_dictionary enumerateKeysAndObjectsUsingBlock:block]; [_dictionary enumerateKeysAndObjectsUsingBlock:block];
} }
- (void)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts - (void)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts
usingBlock:(void (NS_NOESCAPE ^)(id key, usingBlock:(void(NS_NOESCAPE ^)(id key, id obj, BOOL *stop))block {
id obj,
BOOL *stop))block {
[_dictionary enumerateKeysAndObjectsWithOptions:opts usingBlock:block]; [_dictionary enumerateKeysAndObjectsWithOptions:opts usingBlock:block];
} }

@ -40,7 +40,7 @@
static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension, static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension,
GPBCodedInputStream *input, GPBCodedInputStream *input,
id<GPBExtensionRegistry>extensionRegistry, id<GPBExtensionRegistry> extensionRegistry,
GPBMessage *existingValue) GPBMessage *existingValue)
__attribute__((ns_returns_retained)); __attribute__((ns_returns_retained));
@ -95,12 +95,11 @@ static size_t ComputePBSerializedSizeNoTagOfObject(GPBDataType dataType, id obje
#undef FIELD_CASE2 #undef FIELD_CASE2
} }
static size_t ComputeSerializedSizeIncludingTagOfObject( static size_t ComputeSerializedSizeIncludingTagOfObject(GPBExtensionDescription *description,
GPBExtensionDescription *description, id object) { id object) {
#define FIELD_CASE(TYPE, ACCESSOR) \ #define FIELD_CASE(TYPE, ACCESSOR) \
case GPBDataType##TYPE: \ case GPBDataType##TYPE: \
return GPBCompute##TYPE##Size(description->fieldNumber, \ return GPBCompute##TYPE##Size(description->fieldNumber, [(NSNumber *)object ACCESSOR]);
[(NSNumber *)object ACCESSOR]);
#define FIELD_CASE2(TYPE) \ #define FIELD_CASE2(TYPE) \
case GPBDataType##TYPE: \ case GPBDataType##TYPE: \
return GPBCompute##TYPE##Size(description->fieldNumber, object); return GPBCompute##TYPE##Size(description->fieldNumber, object);
@ -124,8 +123,7 @@ static size_t ComputeSerializedSizeIncludingTagOfObject(
FIELD_CASE2(Group) FIELD_CASE2(Group)
case GPBDataTypeMessage: case GPBDataTypeMessage:
if (GPBExtensionIsWireFormat(description)) { if (GPBExtensionIsWireFormat(description)) {
return GPBComputeMessageSetExtensionSize(description->fieldNumber, return GPBComputeMessageSetExtensionSize(description->fieldNumber, object);
object);
} else { } else {
return GPBComputeMessageSize(description->fieldNumber, object); return GPBComputeMessageSize(description->fieldNumber, object);
} }
@ -134,8 +132,8 @@ static size_t ComputeSerializedSizeIncludingTagOfObject(
#undef FIELD_CASE2 #undef FIELD_CASE2
} }
static size_t ComputeSerializedSizeIncludingTagOfArray( static size_t ComputeSerializedSizeIncludingTagOfArray(GPBExtensionDescription *description,
GPBExtensionDescription *description, NSArray *values) { NSArray *values) {
if (GPBExtensionIsPacked(description)) { if (GPBExtensionIsPacked(description)) {
size_t size = 0; size_t size = 0;
size_t typeSize = DataTypeSize(description->dataType); size_t typeSize = DataTypeSize(description->dataType);
@ -143,8 +141,7 @@ static size_t ComputeSerializedSizeIncludingTagOfArray(
size = values.count * typeSize; size = values.count * typeSize;
} else { } else {
for (id value in values) { for (id value in values) {
size += size += ComputePBSerializedSizeNoTagOfObject(description->dataType, value);
ComputePBSerializedSizeNoTagOfObject(description->dataType, value);
} }
} }
return size + GPBComputeTagSize(description->fieldNumber) + return size + GPBComputeTagSize(description->fieldNumber) +
@ -158,13 +155,12 @@ static size_t ComputeSerializedSizeIncludingTagOfArray(
} }
} }
static void WriteObjectIncludingTagToCodedOutputStream( static void WriteObjectIncludingTagToCodedOutputStream(id object,
id object, GPBExtensionDescription *description, GPBExtensionDescription *description,
GPBCodedOutputStream *output) { GPBCodedOutputStream *output) {
#define FIELD_CASE(TYPE, ACCESSOR) \ #define FIELD_CASE(TYPE, ACCESSOR) \
case GPBDataType##TYPE: \ case GPBDataType##TYPE: \
[output write##TYPE:description->fieldNumber \ [output write##TYPE:description->fieldNumber value:[(NSNumber *)object ACCESSOR]]; \
value:[(NSNumber *)object ACCESSOR]]; \
return; return;
#define FIELD_CASE2(TYPE) \ #define FIELD_CASE2(TYPE) \
case GPBDataType##TYPE: \ case GPBDataType##TYPE: \
@ -200,8 +196,7 @@ static void WriteObjectIncludingTagToCodedOutputStream(
#undef FIELD_CASE2 #undef FIELD_CASE2
} }
static void WriteObjectNoTagToCodedOutputStream( static void WriteObjectNoTagToCodedOutputStream(id object, GPBExtensionDescription *description,
id object, GPBExtensionDescription *description,
GPBCodedOutputStream *output) { GPBCodedOutputStream *output) {
#define FIELD_CASE(TYPE, ACCESSOR) \ #define FIELD_CASE(TYPE, ACCESSOR) \
case GPBDataType##TYPE: \ case GPBDataType##TYPE: \
@ -237,20 +232,18 @@ static void WriteObjectNoTagToCodedOutputStream(
#undef FIELD_CASE2 #undef FIELD_CASE2
} }
static void WriteArrayIncludingTagsToCodedOutputStream( static void WriteArrayIncludingTagsToCodedOutputStream(NSArray *values,
NSArray *values, GPBExtensionDescription *description, GPBExtensionDescription *description,
GPBCodedOutputStream *output) { GPBCodedOutputStream *output) {
if (GPBExtensionIsPacked(description)) { if (GPBExtensionIsPacked(description)) {
[output writeTag:description->fieldNumber [output writeTag:description->fieldNumber format:GPBWireFormatLengthDelimited];
format:GPBWireFormatLengthDelimited];
size_t dataSize = 0; size_t dataSize = 0;
size_t typeSize = DataTypeSize(description->dataType); size_t typeSize = DataTypeSize(description->dataType);
if (typeSize != 0) { if (typeSize != 0) {
dataSize = values.count * typeSize; dataSize = values.count * typeSize;
} else { } else {
for (id value in values) { for (id value in values) {
dataSize += dataSize += ComputePBSerializedSizeNoTagOfObject(description->dataType, value);
ComputePBSerializedSizeNoTagOfObject(description->dataType, value);
} }
} }
[output writeRawVarintSizeTAs32:dataSize]; [output writeRawVarintSizeTAs32:dataSize];
@ -270,23 +263,18 @@ static void WriteArrayIncludingTagsToCodedOutputStream(
#pragma clang diagnostic push #pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdirect-ivar-access" #pragma clang diagnostic ignored "-Wdirect-ivar-access"
void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, BOOL isPackedOnStream,
BOOL isPackedOnStream,
GPBCodedInputStream *input, GPBCodedInputStream *input,
id<GPBExtensionRegistry>extensionRegistry, id<GPBExtensionRegistry> extensionRegistry,
GPBMessage *message) { GPBMessage *message) {
GPBExtensionDescription *description = extension->description_; GPBExtensionDescription *description = extension->description_;
GPBCodedInputStreamState *state = &input->state_; GPBCodedInputStreamState *state = &input->state_;
if (isPackedOnStream) { if (isPackedOnStream) {
NSCAssert(GPBExtensionIsRepeated(description), NSCAssert(GPBExtensionIsRepeated(description), @"How was it packed if it isn't repeated?");
@"How was it packed if it isn't repeated?");
int32_t length = GPBCodedInputStreamReadInt32(state); int32_t length = GPBCodedInputStreamReadInt32(state);
size_t limit = GPBCodedInputStreamPushLimit(state, length); size_t limit = GPBCodedInputStreamPushLimit(state, length);
while (GPBCodedInputStreamBytesUntilLimit(state) > 0) { while (GPBCodedInputStreamBytesUntilLimit(state) > 0) {
id value = NewSingleValueFromInputStream(extension, id value = NewSingleValueFromInputStream(extension, input, extensionRegistry, nil);
input,
extensionRegistry,
nil);
[message addExtension:extension value:value]; [message addExtension:extension value:value];
[value release]; [value release];
} }
@ -297,10 +285,7 @@ void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension,
if (!isRepeated && GPBDataTypeIsMessage(description->dataType)) { if (!isRepeated && GPBDataTypeIsMessage(description->dataType)) {
existingValue = [message getExistingExtension:extension]; existingValue = [message getExistingExtension:extension];
} }
id value = NewSingleValueFromInputStream(extension, id value = NewSingleValueFromInputStream(extension, input, extensionRegistry, existingValue);
input,
extensionRegistry,
existingValue);
if (isRepeated) { if (isRepeated) {
[message addExtension:extension value:value]; [message addExtension:extension value:value];
} else { } else {
@ -310,8 +295,7 @@ void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension,
} }
} }
void GPBWriteExtensionValueToOutputStream(GPBExtensionDescriptor *extension, void GPBWriteExtensionValueToOutputStream(GPBExtensionDescriptor *extension, id value,
id value,
GPBCodedOutputStream *output) { GPBCodedOutputStream *output) {
GPBExtensionDescription *description = extension->description_; GPBExtensionDescription *description = extension->description_;
if (GPBExtensionIsRepeated(description)) { if (GPBExtensionIsRepeated(description)) {
@ -321,8 +305,7 @@ void GPBWriteExtensionValueToOutputStream(GPBExtensionDescriptor *extension,
} }
} }
size_t GPBComputeExtensionSerializedSizeIncludingTag( size_t GPBComputeExtensionSerializedSizeIncludingTag(GPBExtensionDescriptor *extension, id value) {
GPBExtensionDescriptor *extension, id value) {
GPBExtensionDescription *description = extension->description_; GPBExtensionDescription *description = extension->description_;
if (GPBExtensionIsRepeated(description)) { if (GPBExtensionIsRepeated(description)) {
return ComputeSerializedSizeIncludingTagOfArray(description, value); return ComputeSerializedSizeIncludingTagOfArray(description, value);
@ -334,27 +317,43 @@ size_t GPBComputeExtensionSerializedSizeIncludingTag(
// Note that this returns a retained value intentionally. // Note that this returns a retained value intentionally.
static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension, static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension,
GPBCodedInputStream *input, GPBCodedInputStream *input,
id<GPBExtensionRegistry>extensionRegistry, id<GPBExtensionRegistry> extensionRegistry,
GPBMessage *existingValue) { GPBMessage *existingValue) {
GPBExtensionDescription *description = extension->description_; GPBExtensionDescription *description = extension->description_;
GPBCodedInputStreamState *state = &input->state_; GPBCodedInputStreamState *state = &input->state_;
switch (description->dataType) { switch (description->dataType) {
case GPBDataTypeBool: return [[NSNumber alloc] initWithBool:GPBCodedInputStreamReadBool(state)]; case GPBDataTypeBool:
case GPBDataTypeFixed32: return [[NSNumber alloc] initWithUnsignedInt:GPBCodedInputStreamReadFixed32(state)]; return [[NSNumber alloc] initWithBool:GPBCodedInputStreamReadBool(state)];
case GPBDataTypeSFixed32: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadSFixed32(state)]; case GPBDataTypeFixed32:
case GPBDataTypeFloat: return [[NSNumber alloc] initWithFloat:GPBCodedInputStreamReadFloat(state)]; return [[NSNumber alloc] initWithUnsignedInt:GPBCodedInputStreamReadFixed32(state)];
case GPBDataTypeFixed64: return [[NSNumber alloc] initWithUnsignedLongLong:GPBCodedInputStreamReadFixed64(state)]; case GPBDataTypeSFixed32:
case GPBDataTypeSFixed64: return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadSFixed64(state)]; return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadSFixed32(state)];
case GPBDataTypeDouble: return [[NSNumber alloc] initWithDouble:GPBCodedInputStreamReadDouble(state)]; case GPBDataTypeFloat:
case GPBDataTypeInt32: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadInt32(state)]; return [[NSNumber alloc] initWithFloat:GPBCodedInputStreamReadFloat(state)];
case GPBDataTypeInt64: return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadInt64(state)]; case GPBDataTypeFixed64:
case GPBDataTypeSInt32: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadSInt32(state)]; return [[NSNumber alloc] initWithUnsignedLongLong:GPBCodedInputStreamReadFixed64(state)];
case GPBDataTypeSInt64: return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadSInt64(state)]; case GPBDataTypeSFixed64:
case GPBDataTypeUInt32: return [[NSNumber alloc] initWithUnsignedInt:GPBCodedInputStreamReadUInt32(state)]; return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadSFixed64(state)];
case GPBDataTypeUInt64: return [[NSNumber alloc] initWithUnsignedLongLong:GPBCodedInputStreamReadUInt64(state)]; case GPBDataTypeDouble:
case GPBDataTypeBytes: return GPBCodedInputStreamReadRetainedBytes(state); return [[NSNumber alloc] initWithDouble:GPBCodedInputStreamReadDouble(state)];
case GPBDataTypeString: return GPBCodedInputStreamReadRetainedString(state); case GPBDataTypeInt32:
case GPBDataTypeEnum: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadEnum(state)]; return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadInt32(state)];
case GPBDataTypeInt64:
return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadInt64(state)];
case GPBDataTypeSInt32:
return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadSInt32(state)];
case GPBDataTypeSInt64:
return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadSInt64(state)];
case GPBDataTypeUInt32:
return [[NSNumber alloc] initWithUnsignedInt:GPBCodedInputStreamReadUInt32(state)];
case GPBDataTypeUInt64:
return [[NSNumber alloc] initWithUnsignedLongLong:GPBCodedInputStreamReadUInt64(state)];
case GPBDataTypeBytes:
return GPBCodedInputStreamReadRetainedBytes(state);
case GPBDataTypeString:
return GPBCodedInputStreamReadRetainedString(state);
case GPBDataTypeEnum:
return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadEnum(state)];
case GPBDataTypeGroup: case GPBDataTypeGroup:
case GPBDataTypeMessage: { case GPBDataTypeMessage: {
GPBMessage *message; GPBMessage *message;
@ -374,8 +373,7 @@ static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension,
if (GPBExtensionIsWireFormat(description)) { if (GPBExtensionIsWireFormat(description)) {
// For MessageSet fields the message length will have already been // For MessageSet fields the message length will have already been
// read. // read.
[message mergeFromCodedInputStream:input [message mergeFromCodedInputStream:input extensionRegistry:extensionRegistry];
extensionRegistry:extensionRegistry];
} else { } else {
[input readMessage:message extensionRegistry:extensionRegistry]; [input readMessage:message extensionRegistry:extensionRegistry];
} }

@ -40,8 +40,8 @@
- (instancetype)init { - (instancetype)init {
if ((self = [super init])) { if ((self = [super init])) {
// The keys are ObjC classes, so straight up ptr comparisons are fine. // The keys are ObjC classes, so straight up ptr comparisons are fine.
mutableClassMap_ = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, mutableClassMap_ =
&kCFTypeDictionaryValueCallBacks); CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks);
} }
return self; return self;
} }
@ -69,13 +69,13 @@
} }
Class containingMessageClass = extension.containingMessageClass; Class containingMessageClass = extension.containingMessageClass;
CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef) CFMutableDictionaryRef extensionMap =
CFDictionaryGetValue(mutableClassMap_, containingMessageClass); (CFMutableDictionaryRef)CFDictionaryGetValue(mutableClassMap_, containingMessageClass);
if (extensionMap == nil) { if (extensionMap == nil) {
// Use a custom dictionary here because the keys are numbers and conversion // Use a custom dictionary here because the keys are numbers and conversion
// back and forth from NSNumber isn't worth the cost. // back and forth from NSNumber isn't worth the cost.
extensionMap = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, extensionMap =
&kCFTypeDictionaryValueCallBacks); CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(mutableClassMap_, containingMessageClass, extensionMap); CFDictionarySetValue(mutableClassMap_, containingMessageClass, extensionMap);
CFRelease(extensionMap); CFRelease(extensionMap);
} }
@ -87,13 +87,11 @@
- (GPBExtensionDescriptor *)extensionForDescriptor:(GPBDescriptor *)descriptor - (GPBExtensionDescriptor *)extensionForDescriptor:(GPBDescriptor *)descriptor
fieldNumber:(NSInteger)fieldNumber { fieldNumber:(NSInteger)fieldNumber {
Class messageClass = descriptor.messageClass; Class messageClass = descriptor.messageClass;
CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef) CFMutableDictionaryRef extensionMap =
CFDictionaryGetValue(mutableClassMap_, messageClass); (CFMutableDictionaryRef)CFDictionaryGetValue(mutableClassMap_, messageClass);
ssize_t key = fieldNumber; ssize_t key = fieldNumber;
GPBExtensionDescriptor *result = GPBExtensionDescriptor *result =
(extensionMap (extensionMap ? CFDictionaryGetValue(extensionMap, (const void *)key) : nil);
? CFDictionaryGetValue(extensionMap, (const void *)key)
: nil);
return result; return result;
} }
@ -107,8 +105,8 @@ static void CopySubDictionary(const void *key, const void *value, void *context)
Class containingMessageClass = key; Class containingMessageClass = key;
CFMutableDictionaryRef otherExtensionMap = (CFMutableDictionaryRef)value; CFMutableDictionaryRef otherExtensionMap = (CFMutableDictionaryRef)value;
CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef) CFMutableDictionaryRef extensionMap =
CFDictionaryGetValue(mutableClassMap, containingMessageClass); (CFMutableDictionaryRef)CFDictionaryGetValue(mutableClassMap, containingMessageClass);
if (extensionMap == nil) { if (extensionMap == nil) {
extensionMap = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, otherExtensionMap); extensionMap = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, otherExtensionMap);
CFDictionarySetValue(mutableClassMap, containingMessageClass, extensionMap); CFDictionarySetValue(mutableClassMap, containingMessageClass, extensionMap);

@ -30,8 +30,8 @@
#import "GPBMessage_PackagePrivate.h" #import "GPBMessage_PackagePrivate.h"
#import <objc/runtime.h>
#import <objc/message.h> #import <objc/message.h>
#import <objc/runtime.h>
#import <stdatomic.h> #import <stdatomic.h>
#import "GPBArray_PackagePrivate.h" #import "GPBArray_PackagePrivate.h"
@ -51,8 +51,7 @@
#pragma clang diagnostic push #pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdirect-ivar-access" #pragma clang diagnostic ignored "-Wdirect-ivar-access"
NSString *const GPBMessageErrorDomain = NSString *const GPBMessageErrorDomain = GPBNSStringifySymbol(GPBMessageErrorDomain);
GPBNSStringifySymbol(GPBMessageErrorDomain);
NSString *const GPBErrorReasonKey = @"Reason"; NSString *const GPBErrorReasonKey = @"Reason";
@ -97,27 +96,20 @@ static NSString *const kGPBDataCoderKey = @"GPBData";
} }
@end @end
static id CreateArrayForField(GPBFieldDescriptor *field, static id CreateArrayForField(GPBFieldDescriptor *field, GPBMessage *autocreator)
GPBMessage *autocreator)
__attribute__((ns_returns_retained)); __attribute__((ns_returns_retained));
static id GetOrCreateArrayIvarWithField(GPBMessage *self, static id GetOrCreateArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
GPBFieldDescriptor *field);
static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
static id CreateMapForField(GPBFieldDescriptor *field, static id CreateMapForField(GPBFieldDescriptor *field, GPBMessage *autocreator)
GPBMessage *autocreator)
__attribute__((ns_returns_retained)); __attribute__((ns_returns_retained));
static id GetOrCreateMapIvarWithField(GPBMessage *self, static id GetOrCreateMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
GPBFieldDescriptor *field);
static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, NSZone *zone)
NSZone *zone)
__attribute__((ns_returns_retained)); __attribute__((ns_returns_retained));
#ifdef DEBUG #ifdef DEBUG
static NSError *MessageError(NSInteger code, NSDictionary *userInfo) { static NSError *MessageError(NSInteger code, NSDictionary *userInfo) {
return [NSError errorWithDomain:GPBMessageErrorDomain return [NSError errorWithDomain:GPBMessageErrorDomain code:code userInfo:userInfo];
code:code
userInfo:userInfo];
} }
#endif #endif
@ -133,7 +125,7 @@ static NSError *ErrorFromException(NSException *exception) {
NSString *reason = exception.reason; NSString *reason = exception.reason;
NSDictionary *userInfo = nil; NSDictionary *userInfo = nil;
if ([reason length]) { if ([reason length]) {
userInfo = @{ GPBErrorReasonKey : reason }; userInfo = @{GPBErrorReasonKey : reason};
} }
error = [NSError errorWithDomain:GPBMessageErrorDomain error = [NSError errorWithDomain:GPBMessageErrorDomain
@ -143,24 +135,20 @@ static NSError *ErrorFromException(NSException *exception) {
return error; return error;
} }
static void CheckExtension(GPBMessage *self, static void CheckExtension(GPBMessage *self, GPBExtensionDescriptor *extension) {
GPBExtensionDescriptor *extension) {
if (![self isKindOfClass:extension.containingMessageClass]) { if (![self isKindOfClass:extension.containingMessageClass]) {
[NSException [NSException raise:NSInvalidArgumentException
raise:NSInvalidArgumentException
format:@"Extension %@ used on wrong class (%@ instead of %@)", format:@"Extension %@ used on wrong class (%@ instead of %@)",
extension.singletonName, extension.singletonName, [self class], extension.containingMessageClass];
[self class], extension.containingMessageClass];
} }
} }
static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, NSZone *zone) {
NSZone *zone) {
if (extensionMap.count == 0) { if (extensionMap.count == 0) {
return nil; return nil;
} }
NSMutableDictionary *result = [[NSMutableDictionary allocWithZone:zone] NSMutableDictionary *result =
initWithCapacity:extensionMap.count]; [[NSMutableDictionary allocWithZone:zone] initWithCapacity:extensionMap.count];
for (GPBExtensionDescriptor *extension in extensionMap) { for (GPBExtensionDescriptor *extension in extensionMap) {
id value = [extensionMap objectForKey:extension]; id value = [extensionMap objectForKey:extension];
@ -168,8 +156,7 @@ static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap,
if (extension.repeated) { if (extension.repeated) {
if (isMessageExtension) { if (isMessageExtension) {
NSMutableArray *list = NSMutableArray *list = [[NSMutableArray alloc] initWithCapacity:[value count]];
[[NSMutableArray alloc] initWithCapacity:[value count]];
for (GPBMessage *listValue in value) { for (GPBMessage *listValue in value) {
GPBMessage *copiedValue = [listValue copyWithZone:zone]; GPBMessage *copiedValue = [listValue copyWithZone:zone];
[list addObject:copiedValue]; [list addObject:copiedValue];
@ -196,8 +183,7 @@ static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap,
return result; return result;
} }
static id CreateArrayForField(GPBFieldDescriptor *field, static id CreateArrayForField(GPBFieldDescriptor *field, GPBMessage *autocreator) {
GPBMessage *autocreator) {
id result; id result;
GPBDataType fieldDataType = GPBGetFieldDataType(field); GPBDataType fieldDataType = GPBGetFieldDataType(field);
switch (fieldDataType) { switch (fieldDataType) {
@ -230,8 +216,7 @@ static id CreateArrayForField(GPBFieldDescriptor *field,
break; break;
case GPBDataTypeEnum: case GPBDataTypeEnum:
result = [[GPBEnumArray alloc] result = [[GPBEnumArray alloc] initWithValidationFunction:field.enumDescriptor.enumVerifier];
initWithValidationFunction:field.enumDescriptor.enumVerifier];
break; break;
case GPBDataTypeBytes: case GPBDataTypeBytes:
@ -259,8 +244,7 @@ static id CreateArrayForField(GPBFieldDescriptor *field,
return result; return result;
} }
static id CreateMapForField(GPBFieldDescriptor *field, static id CreateMapForField(GPBFieldDescriptor *field, GPBMessage *autocreator) {
GPBMessage *autocreator) {
id result; id result;
GPBDataType keyDataType = field.mapKeyDataType; GPBDataType keyDataType = field.mapKeyDataType;
GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType valueDataType = GPBGetFieldDataType(field);
@ -545,8 +529,7 @@ static id CreateMapForField(GPBFieldDescriptor *field,
} }
if (autocreator) { if (autocreator) {
if ((keyDataType == GPBDataTypeString) && if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) {
GPBDataTypeIsObject(valueDataType)) {
GPBAutocreatedDictionary *autoDict = result; GPBAutocreatedDictionary *autoDict = result;
autoDict->_autocreator = autocreator; autoDict->_autocreator = autocreator;
} else { } else {
@ -570,8 +553,7 @@ static id CreateMapForField(GPBFieldDescriptor *field,
// repeated/map field parsed into the autorelease pool which is both a memory // repeated/map field parsed into the autorelease pool which is both a memory
// and performance hit. // and performance hit.
static id GetOrCreateArrayIvarWithField(GPBMessage *self, static id GetOrCreateArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
GPBFieldDescriptor *field) {
id array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); id array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
if (!array) { if (!array) {
// No lock needed, this is called from places expecting to mutate // No lock needed, this is called from places expecting to mutate
@ -611,8 +593,7 @@ static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
return expected; return expected;
} }
static id GetOrCreateMapIvarWithField(GPBMessage *self, static id GetOrCreateMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
GPBFieldDescriptor *field) {
id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
if (!dict) { if (!dict) {
// No lock needed, this is called from places expecting to mutate // No lock needed, this is called from places expecting to mutate
@ -641,8 +622,7 @@ static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
} }
// Some other thread set it, release the one created and return what got set. // Some other thread set it, release the one created and return what got set.
if ((field.mapKeyDataType == GPBDataTypeString) && if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) {
GPBFieldDataTypeIsObject(field)) {
GPBAutocreatedDictionary *autoDict = autocreated; GPBAutocreatedDictionary *autoDict = autocreated;
autoDict->_autocreator = nil; autoDict->_autocreator = nil;
} else { } else {
@ -655,8 +635,7 @@ static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
#endif // !defined(__clang_analyzer__) #endif // !defined(__clang_analyzer__)
GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, GPBMessage *autocreator,
GPBMessage *autocreator,
GPBFieldDescriptor *field) { GPBFieldDescriptor *field) {
GPBMessage *message = [[msgClass alloc] init]; GPBMessage *message = [[msgClass alloc] init];
message->autocreator_ = autocreator; message->autocreator_ = autocreator;
@ -664,12 +643,11 @@ GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass,
return message; return message;
} }
static GPBMessage *CreateMessageWithAutocreatorForExtension( static GPBMessage *CreateMessageWithAutocreatorForExtension(Class msgClass, GPBMessage *autocreator,
Class msgClass, GPBMessage *autocreator, GPBExtensionDescriptor *extension) GPBExtensionDescriptor *extension)
__attribute__((ns_returns_retained)); __attribute__((ns_returns_retained));
static GPBMessage *CreateMessageWithAutocreatorForExtension( static GPBMessage *CreateMessageWithAutocreatorForExtension(Class msgClass, GPBMessage *autocreator,
Class msgClass, GPBMessage *autocreator,
GPBExtensionDescriptor *extension) { GPBExtensionDescriptor *extension) {
GPBMessage *message = [[msgClass alloc] init]; GPBMessage *message = [[msgClass alloc] init];
message->autocreator_ = autocreator; message->autocreator_ = autocreator;
@ -689,8 +667,7 @@ void GPBBecomeVisibleToAutocreator(GPBMessage *self) {
// This will recursively make all parent messages visible until it reaches a // This will recursively make all parent messages visible until it reaches a
// super-creator that's visible. // super-creator that's visible.
if (self->autocreatorField_) { if (self->autocreatorField_) {
GPBSetObjectIvarWithFieldPrivate(self->autocreator_, GPBSetObjectIvarWithFieldPrivate(self->autocreator_, self->autocreatorField_, self);
self->autocreatorField_, self);
} else { } else {
[self->autocreator_ setExtension:self->autocreatorExtension_ value:self]; [self->autocreator_ setExtension:self->autocreatorExtension_ value:self];
} }
@ -726,8 +703,7 @@ void GPBAutocreatedDictionaryModified(GPBMessage *self, id dictionary) {
if (field.fieldType == GPBFieldTypeMap) { if (field.fieldType == GPBFieldTypeMap) {
id curDict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); id curDict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
if (curDict == dictionary) { if (curDict == dictionary) {
if ((field.mapKeyDataType == GPBDataTypeString) && if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) {
GPBFieldDataTypeIsObject(field)) {
GPBAutocreatedDictionary *autoDict = dictionary; GPBAutocreatedDictionary *autoDict = dictionary;
autoDict->_autocreator = nil; autoDict->_autocreator = nil;
} else { } else {
@ -751,18 +727,15 @@ void GPBClearMessageAutocreator(GPBMessage *self) {
// Either the autocreator must have its "has" flag set to YES, or it must be // Either the autocreator must have its "has" flag set to YES, or it must be
// NO and not equal to ourselves. // NO and not equal to ourselves.
BOOL autocreatorHas = BOOL autocreatorHas =
(self->autocreatorField_ (self->autocreatorField_ ? GPBGetHasIvarField(self->autocreator_, self->autocreatorField_)
? GPBGetHasIvarField(self->autocreator_, self->autocreatorField_)
: [self->autocreator_ hasExtension:self->autocreatorExtension_]); : [self->autocreator_ hasExtension:self->autocreatorExtension_]);
GPBMessage *autocreatorFieldValue = GPBMessage *autocreatorFieldValue =
(self->autocreatorField_ (self->autocreatorField_
? GPBGetObjectIvarWithFieldNoAutocreate(self->autocreator_, ? GPBGetObjectIvarWithFieldNoAutocreate(self->autocreator_, self->autocreatorField_)
self->autocreatorField_)
: [self->autocreator_->autocreatedExtensionMap_ : [self->autocreator_->autocreatedExtensionMap_
objectForKey:self->autocreatorExtension_]); objectForKey:self->autocreatorExtension_]);
NSCAssert(autocreatorHas || autocreatorFieldValue != self, NSCAssert(autocreatorHas || autocreatorFieldValue != self,
@"Cannot clear autocreator because it still refers to self, self: %@.", @"Cannot clear autocreator because it still refers to self, self: %@.", self);
self);
#endif // DEBUG && !defined(NS_BLOCK_ASSERTIONS) #endif // DEBUG && !defined(NS_BLOCK_ASSERTIONS)
@ -791,7 +764,9 @@ void GPBPrepareReadOnlySemaphore(GPBMessage *self) {
// The Xcode 9.2 (and 9.3 beta) static analyzer thinks worker is leaked // The Xcode 9.2 (and 9.3 beta) static analyzer thinks worker is leaked
// (doesn't seem to know about atomic_compare_exchange_strong); so just // (doesn't seem to know about atomic_compare_exchange_strong); so just
// for the analyzer, let it think worker is also released in this case. // for the analyzer, let it think worker is also released in this case.
else { dispatch_release(worker); } else {
dispatch_release(worker);
}
#endif #endif
} }
@ -848,8 +823,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
if (!descriptor) { if (!descriptor) {
// Use a dummy file that marks it as proto2 syntax so when used generically // Use a dummy file that marks it as proto2 syntax so when used generically
// it supports unknowns/etc. // it supports unknowns/etc.
fileDescriptor = fileDescriptor = [[GPBFileDescriptor alloc] initWithPackage:@"internal"
[[GPBFileDescriptor alloc] initWithPackage:@"internal"
syntax:GPBFileSyntaxProto2]; syntax:GPBFileSyntaxProto2];
descriptor = [GPBDescriptor allocDescriptorForClass:[GPBMessage class] descriptor = [GPBDescriptor allocDescriptorForClass:[GPBMessage class]
@ -869,8 +843,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
- (instancetype)init { - (instancetype)init {
if ((self = [super init])) { if ((self = [super init])) {
messageStorage_ = (GPBMessage_StoragePtr)( messageStorage_ =
((uint8_t *)self) + class_getInstanceSize([self class])); (GPBMessage_StoragePtr)(((uint8_t *)self) + class_getInstanceSize([self class]));
} }
return self; return self;
@ -889,8 +863,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
if (errorPtr) { if (errorPtr) {
*errorPtr = nil; *errorPtr = nil;
} }
} } @catch (NSException *exception) {
@catch (NSException *exception) {
[self release]; [self release];
self = nil; self = nil;
if (errorPtr) { if (errorPtr) {
@ -911,8 +884,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
} }
- (instancetype)initWithCodedInputStream:(GPBCodedInputStream *)input - (instancetype)initWithCodedInputStream:(GPBCodedInputStream *)input
extensionRegistry: extensionRegistry:(id<GPBExtensionRegistry>)extensionRegistry
(id<GPBExtensionRegistry>)extensionRegistry
error:(NSError **)errorPtr { error:(NSError **)errorPtr {
if ((self = [self init])) { if ((self = [self init])) {
@try { @try {
@ -920,8 +892,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
if (errorPtr) { if (errorPtr) {
*errorPtr = nil; *errorPtr = nil;
} }
} } @catch (NSException *exception) {
@catch (NSException *exception) {
[self release]; [self release];
self = nil; self = nil;
if (errorPtr) { if (errorPtr) {
@ -979,12 +950,11 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
if (field.mapKeyDataType == GPBDataTypeString) { if (field.mapKeyDataType == GPBDataTypeString) {
// Map is an NSDictionary. // Map is an NSDictionary.
NSDictionary *existingDict = value; NSDictionary *existingDict = value;
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] NSMutableDictionary *newDict =
initWithCapacity:existingDict.count]; [[NSMutableDictionary alloc] initWithCapacity:existingDict.count];
newValue = newDict; newValue = newDict;
[existingDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, [existingDict
GPBMessage *msg, enumerateKeysAndObjectsUsingBlock:^(NSString *key, GPBMessage *msg, BOOL *stop) {
BOOL *stop) {
#pragma unused(stop) #pragma unused(stop)
GPBMessage *copiedMsg = [msg copyWithZone:zone]; GPBMessage *copiedMsg = [msg copyWithZone:zone];
[newDict setObject:copiedMsg forKey:key]; [newDict setObject:copiedMsg forKey:key];
@ -1008,8 +978,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
newValue = [value copyWithZone:zone]; newValue = [value copyWithZone:zone];
} }
} else { } else {
if ((field.mapKeyDataType == GPBDataTypeString) && if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) {
GPBFieldDataTypeIsObject(field)) {
// NSDictionary // NSDictionary
newValue = [value mutableCopyWithZone:zone]; newValue = [value mutableCopyWithZone:zone];
} else { } else {
@ -1041,8 +1010,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
id *typePtr = (id *)&storage[field->description_->offset]; id *typePtr = (id *)&storage[field->description_->offset];
*typePtr = NULL; *typePtr = NULL;
} }
} else if (GPBFieldDataTypeIsObject(field) && } else if (GPBFieldDataTypeIsObject(field) && GPBGetHasIvarField(self, field)) {
GPBGetHasIvarField(self, field)) {
// A set string/data value (message picked off above), copy it. // A set string/data value (message picked off above), copy it.
id value = GPBGetObjectIvarWithFieldNoAutocreate(self, field); id value = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
id newValue = [value copyWithZone:zone]; id newValue = [value copyWithZone:zone];
@ -1093,8 +1061,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
} }
} }
} else { } else {
if ((field.mapKeyDataType == GPBDataTypeString) && if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) {
GPBFieldDataTypeIsObject(field)) {
if ([arrayOrMap isKindOfClass:[GPBAutocreatedDictionary class]]) { if ([arrayOrMap isKindOfClass:[GPBAutocreatedDictionary class]]) {
GPBAutocreatedDictionary *autoDict = arrayOrMap; GPBAutocreatedDictionary *autoDict = arrayOrMap;
if (autoDict->_autocreator == self) { if (autoDict->_autocreator == self) {
@ -1115,8 +1082,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
GPBClearAutocreatedMessageIvarWithField(self, field); GPBClearAutocreatedMessageIvarWithField(self, field);
GPBMessage *value = GPBGetObjectIvarWithFieldNoAutocreate(self, field); GPBMessage *value = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
[value release]; [value release];
} else if (GPBFieldDataTypeIsObject(field) && } else if (GPBFieldDataTypeIsObject(field) && GPBGetHasIvarField(self, field)) {
GPBGetHasIvarField(self, field)) {
id value = GPBGetObjectIvarWithField(self, field); id value = GPBGetObjectIvarWithField(self, field);
[value release]; [value release];
} }
@ -1168,8 +1134,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
return NO; return NO;
} }
} else { } else {
NSAssert(field.isOptional, NSAssert(field.isOptional, @"%@: Single message field %@ not required or optional?",
@"%@: Single message field %@ not required or optional?",
[self class], field.name); [self class], field.name);
if (GPBGetHasIvarField(self, field)) { if (GPBGetHasIvarField(self, field)) {
GPBMessage *message = GPBGetMessageMessageField(self, field); GPBMessage *message = GPBGetMessageMessageField(self, field);
@ -1187,15 +1152,13 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
} }
} else { // fieldType == GPBFieldTypeMap } else { // fieldType == GPBFieldTypeMap
if (field.mapKeyDataType == GPBDataTypeString) { if (field.mapKeyDataType == GPBDataTypeString) {
NSDictionary *map = NSDictionary *map = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
GPBGetObjectIvarWithFieldNoAutocreate(self, field);
if (map && !GPBDictionaryIsInitializedInternalHelper(map, field)) { if (map && !GPBDictionaryIsInitializedInternalHelper(map, field)) {
return NO; return NO;
} }
} else { } else {
// Real type is GPB*ObjectDictionary, exact type doesn't matter. // Real type is GPB*ObjectDictionary, exact type doesn't matter.
GPBInt32ObjectDictionary *map = GPBInt32ObjectDictionary *map = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
GPBGetObjectIvarWithFieldNoAutocreate(self, field);
if (map && ![map isInitialized]) { if (map && ![map isInitialized]) {
return NO; return NO;
} }
@ -1206,9 +1169,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
__block BOOL result = YES; __block BOOL result = YES;
[extensionMap_ [extensionMap_
enumerateKeysAndObjectsUsingBlock:^(GPBExtensionDescriptor *extension, enumerateKeysAndObjectsUsingBlock:^(GPBExtensionDescriptor *extension, id obj, BOOL *stop) {
id obj,
BOOL *stop) {
if (GPBExtensionIsMessage(extension)) { if (GPBExtensionIsMessage(extension)) {
if (extension.isRepeated) { if (extension.isRepeated) {
for (GPBMessage *msg in obj) { for (GPBMessage *msg in obj) {
@ -1241,18 +1202,15 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
} }
#endif #endif
NSMutableData *data = [NSMutableData dataWithLength:[self serializedSize]]; NSMutableData *data = [NSMutableData dataWithLength:[self serializedSize]];
GPBCodedOutputStream *stream = GPBCodedOutputStream *stream = [[GPBCodedOutputStream alloc] initWithData:data];
[[GPBCodedOutputStream alloc] initWithData:data];
@try { @try {
[self writeToCodedOutputStream:stream]; [self writeToCodedOutputStream:stream];
} } @catch (NSException *exception) {
@catch (NSException *exception) {
// This really shouldn't happen. The only way writeToCodedOutputStream: // This really shouldn't happen. The only way writeToCodedOutputStream:
// could throw is if something in the library has a bug and the // could throw is if something in the library has a bug and the
// serializedSize was wrong. // serializedSize was wrong.
#ifdef DEBUG #ifdef DEBUG
NSLog(@"%@: Internal exception while building message data: %@", NSLog(@"%@: Internal exception while building message data: %@", [self class], exception);
[self class], exception);
#endif #endif
data = nil; data = nil;
} }
@ -1263,20 +1221,17 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
- (NSData *)delimitedData { - (NSData *)delimitedData {
size_t serializedSize = [self serializedSize]; size_t serializedSize = [self serializedSize];
size_t varintSize = GPBComputeRawVarint32SizeForInteger(serializedSize); size_t varintSize = GPBComputeRawVarint32SizeForInteger(serializedSize);
NSMutableData *data = NSMutableData *data = [NSMutableData dataWithLength:(serializedSize + varintSize)];
[NSMutableData dataWithLength:(serializedSize + varintSize)]; GPBCodedOutputStream *stream = [[GPBCodedOutputStream alloc] initWithData:data];
GPBCodedOutputStream *stream =
[[GPBCodedOutputStream alloc] initWithData:data];
@try { @try {
[self writeDelimitedToCodedOutputStream:stream]; [self writeDelimitedToCodedOutputStream:stream];
} } @catch (NSException *exception) {
@catch (NSException *exception) {
// This really shouldn't happen. The only way writeToCodedOutputStream: // This really shouldn't happen. The only way writeToCodedOutputStream:
// could throw is if something in the library has a bug and the // could throw is if something in the library has a bug and the
// serializedSize was wrong. // serializedSize was wrong.
#ifdef DEBUG #ifdef DEBUG
NSLog(@"%@: Internal exception while building message delimitedData: %@", NSLog(@"%@: Internal exception while building message delimitedData: %@", [self class],
[self class], exception); exception);
#endif #endif
// If it happens, truncate. // If it happens, truncate.
data.length = 0; data.length = 0;
@ -1286,8 +1241,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
} }
- (void)writeToOutputStream:(NSOutputStream *)output { - (void)writeToOutputStream:(NSOutputStream *)output {
GPBCodedOutputStream *stream = GPBCodedOutputStream *stream = [[GPBCodedOutputStream alloc] initWithOutputStream:output];
[[GPBCodedOutputStream alloc] initWithOutputStream:output];
[self writeToCodedOutputStream:stream]; [self writeToCodedOutputStream:stream];
[stream release]; [stream release];
} }
@ -1322,8 +1276,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
} }
- (void)writeDelimitedToOutputStream:(NSOutputStream *)output { - (void)writeDelimitedToOutputStream:(NSOutputStream *)output {
GPBCodedOutputStream *codedOutput = GPBCodedOutputStream *codedOutput = [[GPBCodedOutputStream alloc] initWithOutputStream:output];
[[GPBCodedOutputStream alloc] initWithOutputStream:output];
[self writeDelimitedToCodedOutputStream:codedOutput]; [self writeDelimitedToCodedOutputStream:codedOutput];
[codedOutput release]; [codedOutput release];
} }
@ -1333,8 +1286,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
[self writeToCodedOutputStream:output]; [self writeToCodedOutputStream:output];
} }
- (void)writeField:(GPBFieldDescriptor *)field - (void)writeField:(GPBFieldDescriptor *)field toCodedOutputStream:(GPBCodedOutputStream *)output {
toCodedOutputStream:(GPBCodedOutputStream *)output {
GPBFieldType fieldType = field.fieldType; GPBFieldType fieldType = field.fieldType;
if (fieldType == GPBFieldTypeSingle) { if (fieldType == GPBFieldTypeSingle) {
BOOL has = GPBGetHasIvarField(self, field); BOOL has = GPBGetHasIvarField(self, field);
@ -1345,8 +1297,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
uint32_t fieldNumber = GPBFieldNumber(field); uint32_t fieldNumber = GPBFieldNumber(field);
switch (GPBGetFieldDataType(field)) { switch (GPBGetFieldDataType(field)) {
// clang-format off
// clang-format off
//%PDDM-DEFINE FIELD_CASE(TYPE, REAL_TYPE) //%PDDM-DEFINE FIELD_CASE(TYPE, REAL_TYPE)
//%FIELD_CASE_FULL(TYPE, REAL_TYPE, REAL_TYPE) //%FIELD_CASE_FULL(TYPE, REAL_TYPE, REAL_TYPE)

@ -31,7 +31,6 @@
// If you want to build protocol buffers in your own project without adding the // If you want to build protocol buffers in your own project without adding the
// project dependency, you can just add this file. // project dependency, you can just add this file.
// This warning seems to treat code differently when it is #imported than when // This warning seems to treat code differently when it is #imported than when
// it is inline in the file. GPBDictionary.m compiles cleanly in other targets, // it is inline in the file. GPBDictionary.m compiles cleanly in other targets,
// but when #imported here it triggers a bunch of warnings that don't make // but when #imported here it triggers a bunch of warnings that don't make

@ -73,26 +73,22 @@ static uint32_t jenkins_one_at_a_time_hash(const char *key) {
// to worry about deallocation. All of the items are added to it at // to worry about deallocation. All of the items are added to it at
// startup, and so the keys don't need to be retained/released. // startup, and so the keys don't need to be retained/released.
// Keys are NULL terminated char *. // Keys are NULL terminated char *.
static const void *GPBRootExtensionKeyRetain(CFAllocatorRef allocator, static const void *GPBRootExtensionKeyRetain(CFAllocatorRef allocator, const void *value) {
const void *value) {
#pragma unused(allocator) #pragma unused(allocator)
return value; return value;
} }
static void GPBRootExtensionKeyRelease(CFAllocatorRef allocator, static void GPBRootExtensionKeyRelease(CFAllocatorRef allocator, const void *value) {
const void *value) {
#pragma unused(allocator) #pragma unused(allocator)
#pragma unused(value) #pragma unused(value)
} }
static CFStringRef GPBRootExtensionCopyKeyDescription(const void *value) { static CFStringRef GPBRootExtensionCopyKeyDescription(const void *value) {
const char *key = (const char *)value; const char *key = (const char *)value;
return CFStringCreateWithCString(kCFAllocatorDefault, key, return CFStringCreateWithCString(kCFAllocatorDefault, key, kCFStringEncodingUTF8);
kCFStringEncodingUTF8);
} }
static Boolean GPBRootExtensionKeyEqual(const void *value1, static Boolean GPBRootExtensionKeyEqual(const void *value1, const void *value2) {
const void *value2) {
const char *key1 = (const char *)value1; const char *key1 = (const char *)value1;
const char *key2 = (const char *)value2; const char *key2 = (const char *)value2;
return strcmp(key1, key2) == 0; return strcmp(key1, key2) == 0;
@ -125,8 +121,7 @@ static GPBExtensionRegistry *gDefaultExtensionRegistry = NULL;
GPBRootExtensionKeyEqual, GPBRootExtensionKeyEqual,
GPBRootExtensionKeyHash, GPBRootExtensionKeyHash,
}; };
gExtensionSingletonDictionary = gExtensionSingletonDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &keyCallBacks,
CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &keyCallBacks,
&kCFTypeDictionaryValueCallBacks); &kCFTypeDictionaryValueCallBacks);
gDefaultExtensionRegistry = [[GPBExtensionRegistry alloc] init]; gDefaultExtensionRegistry = [[GPBExtensionRegistry alloc] init];
} }
@ -147,8 +142,7 @@ static GPBExtensionRegistry *gDefaultExtensionRegistry = NULL;
+ (void)globallyRegisterExtension:(GPBExtensionDescriptor *)field { + (void)globallyRegisterExtension:(GPBExtensionDescriptor *)field {
const char *key = [field singletonNameC]; const char *key = [field singletonNameC];
dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore, dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore, DISPATCH_TIME_FOREVER);
DISPATCH_TIME_FOREVER);
CFDictionarySetValue(gExtensionSingletonDictionary, key, field); CFDictionarySetValue(gExtensionSingletonDictionary, key, field);
dispatch_semaphore_signal(gExtensionSingletonDictionarySemaphore); dispatch_semaphore_signal(gExtensionSingletonDictionarySemaphore);
} }
@ -189,8 +183,7 @@ static id ExtensionForName(id self, SEL _cmd) {
// initialized and Message classes ensure their Root was also initialized. // initialized and Message classes ensure their Root was also initialized.
NSAssert(gExtensionSingletonDictionary, @"Startup order broken!"); NSAssert(gExtensionSingletonDictionary, @"Startup order broken!");
dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore, dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore, DISPATCH_TIME_FOREVER);
DISPATCH_TIME_FOREVER);
id extension = (id)CFDictionaryGetValue(gExtensionSingletonDictionary, key); id extension = (id)CFDictionaryGetValue(gExtensionSingletonDictionary, key);
// We can't remove the key from the dictionary here (as an optimization), // We can't remove the key from the dictionary here (as an optimization),
// two threads could have gone into +resolveClassMethod: for the same method, // two threads could have gone into +resolveClassMethod: for the same method,
@ -212,8 +205,7 @@ BOOL GPBResolveExtensionClassMethod(Class self, SEL sel) {
// file. // file.
id extension = ExtensionForName(self, sel); id extension = ExtensionForName(self, sel);
if (extension != nil) { if (extension != nil) {
const char *encoding = const char *encoding = GPBMessageEncodingForSelector(@selector(getClassValue), NO);
GPBMessageEncodingForSelector(@selector(getClassValue), NO);
Class metaClass = objc_getMetaClass(class_getName(self)); Class metaClass = objc_getMetaClass(class_getName(self));
IMP imp = imp_implementationWithBlock(^(id obj) { IMP imp = imp_implementationWithBlock(^(id obj) {
#pragma unused(obj) #pragma unused(obj)
@ -234,7 +226,6 @@ BOOL GPBResolveExtensionClassMethod(Class self, SEL sel) {
return NO; return NO;
} }
+ (BOOL)resolveClassMethod:(SEL)sel { + (BOOL)resolveClassMethod:(SEL)sel {
if (GPBResolveExtensionClassMethod(self, sel)) { if (GPBResolveExtensionClassMethod(self, sel)) {
return YES; return YES;

@ -40,8 +40,8 @@
GPBUInt64Array *mutableVarintList_; GPBUInt64Array *mutableVarintList_;
GPBUInt32Array *mutableFixed32List_; GPBUInt32Array *mutableFixed32List_;
GPBUInt64Array *mutableFixed64List_; GPBUInt64Array *mutableFixed64List_;
NSMutableArray<NSData*> *mutableLengthDelimitedList_; NSMutableArray<NSData *> *mutableLengthDelimitedList_;
NSMutableArray<GPBUnknownFieldSet*> *mutableGroupList_; NSMutableArray<GPBUnknownFieldSet *> *mutableGroupList_;
} }
@synthesize number = number_; @synthesize number = number_;
@ -75,16 +75,14 @@
#pragma clang diagnostic ignored "-Wdirect-ivar-access" #pragma clang diagnostic ignored "-Wdirect-ivar-access"
- (id)copyWithZone:(NSZone *)zone { - (id)copyWithZone:(NSZone *)zone {
GPBUnknownField *result = GPBUnknownField *result = [[GPBUnknownField allocWithZone:zone] initWithNumber:number_];
[[GPBUnknownField allocWithZone:zone] initWithNumber:number_];
result->mutableFixed32List_ = [mutableFixed32List_ copyWithZone:zone]; result->mutableFixed32List_ = [mutableFixed32List_ copyWithZone:zone];
result->mutableFixed64List_ = [mutableFixed64List_ copyWithZone:zone]; result->mutableFixed64List_ = [mutableFixed64List_ copyWithZone:zone];
result->mutableLengthDelimitedList_ = result->mutableLengthDelimitedList_ = [mutableLengthDelimitedList_ mutableCopyWithZone:zone];
[mutableLengthDelimitedList_ mutableCopyWithZone:zone];
result->mutableVarintList_ = [mutableVarintList_ copyWithZone:zone]; result->mutableVarintList_ = [mutableVarintList_ copyWithZone:zone];
if (mutableGroupList_.count) { if (mutableGroupList_.count) {
result->mutableGroupList_ = [[NSMutableArray allocWithZone:zone] result->mutableGroupList_ =
initWithCapacity:mutableGroupList_.count]; [[NSMutableArray allocWithZone:zone] initWithCapacity:mutableGroupList_.count];
for (GPBUnknownFieldSet *group in mutableGroupList_) { for (GPBUnknownFieldSet *group in mutableGroupList_) {
GPBUnknownFieldSet *copied = [group copyWithZone:zone]; GPBUnknownFieldSet *copied = [group copyWithZone:zone];
[result->mutableGroupList_ addObject:copied]; [result->mutableGroupList_ addObject:copied];
@ -99,25 +97,20 @@
if (![object isKindOfClass:[GPBUnknownField class]]) return NO; if (![object isKindOfClass:[GPBUnknownField class]]) return NO;
GPBUnknownField *field = (GPBUnknownField *)object; GPBUnknownField *field = (GPBUnknownField *)object;
if (number_ != field->number_) return NO; if (number_ != field->number_) return NO;
BOOL equalVarint = BOOL equalVarint = (mutableVarintList_.count == 0 && field->mutableVarintList_.count == 0) ||
(mutableVarintList_.count == 0 && field->mutableVarintList_.count == 0) ||
[mutableVarintList_ isEqual:field->mutableVarintList_]; [mutableVarintList_ isEqual:field->mutableVarintList_];
if (!equalVarint) return NO; if (!equalVarint) return NO;
BOOL equalFixed32 = (mutableFixed32List_.count == 0 && BOOL equalFixed32 = (mutableFixed32List_.count == 0 && field->mutableFixed32List_.count == 0) ||
field->mutableFixed32List_.count == 0) ||
[mutableFixed32List_ isEqual:field->mutableFixed32List_]; [mutableFixed32List_ isEqual:field->mutableFixed32List_];
if (!equalFixed32) return NO; if (!equalFixed32) return NO;
BOOL equalFixed64 = (mutableFixed64List_.count == 0 && BOOL equalFixed64 = (mutableFixed64List_.count == 0 && field->mutableFixed64List_.count == 0) ||
field->mutableFixed64List_.count == 0) ||
[mutableFixed64List_ isEqual:field->mutableFixed64List_]; [mutableFixed64List_ isEqual:field->mutableFixed64List_];
if (!equalFixed64) return NO; if (!equalFixed64) return NO;
BOOL equalLDList = BOOL equalLDList =
(mutableLengthDelimitedList_.count == 0 && (mutableLengthDelimitedList_.count == 0 && field->mutableLengthDelimitedList_.count == 0) ||
field->mutableLengthDelimitedList_.count == 0) ||
[mutableLengthDelimitedList_ isEqual:field->mutableLengthDelimitedList_]; [mutableLengthDelimitedList_ isEqual:field->mutableLengthDelimitedList_];
if (!equalLDList) return NO; if (!equalLDList) return NO;
BOOL equalGroupList = BOOL equalGroupList = (mutableGroupList_.count == 0 && field->mutableGroupList_.count == 0) ||
(mutableGroupList_.count == 0 && field->mutableGroupList_.count == 0) ||
[mutableGroupList_ isEqual:field->mutableGroupList_]; [mutableGroupList_ isEqual:field->mutableGroupList_];
if (!equalGroupList) return NO; if (!equalGroupList) return NO;
return YES; return YES;
@ -160,20 +153,17 @@
- (size_t)serializedSize { - (size_t)serializedSize {
__block size_t result = 0; __block size_t result = 0;
int32_t number = number_; int32_t number = number_;
[mutableVarintList_ [mutableVarintList_ enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) {
enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) {
#pragma unused(idx, stop) #pragma unused(idx, stop)
result += GPBComputeUInt64Size(number, value); result += GPBComputeUInt64Size(number, value);
}]; }];
[mutableFixed32List_ [mutableFixed32List_ enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) {
enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) {
#pragma unused(idx, stop) #pragma unused(idx, stop)
result += GPBComputeFixed32Size(number, value); result += GPBComputeFixed32Size(number, value);
}]; }];
[mutableFixed64List_ [mutableFixed64List_ enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) {
enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) {
#pragma unused(idx, stop) #pragma unused(idx, stop)
result += GPBComputeFixed64Size(number, value); result += GPBComputeFixed64Size(number, value);
}]; }];
@ -205,22 +195,18 @@
- (NSString *)description { - (NSString *)description {
NSMutableString *description = NSMutableString *description =
[NSMutableString stringWithFormat:@"<%@ %p>: Field: %d {\n", [NSMutableString stringWithFormat:@"<%@ %p>: Field: %d {\n", [self class], self, number_];
[self class], self, number_]; [mutableVarintList_ enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) {
[mutableVarintList_
enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) {
#pragma unused(idx, stop) #pragma unused(idx, stop)
[description appendFormat:@"\t%llu\n", value]; [description appendFormat:@"\t%llu\n", value];
}]; }];
[mutableFixed32List_ [mutableFixed32List_ enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) {
enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) {
#pragma unused(idx, stop) #pragma unused(idx, stop)
[description appendFormat:@"\t%u\n", value]; [description appendFormat:@"\t%u\n", value];
}]; }];
[mutableFixed64List_ [mutableFixed64List_ enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) {
enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) {
#pragma unused(idx, stop) #pragma unused(idx, stop)
[description appendFormat:@"\t%llu\n", value]; [description appendFormat:@"\t%llu\n", value];
}]; }];
@ -269,16 +255,14 @@
if (mutableLengthDelimitedList_ == nil) { if (mutableLengthDelimitedList_ == nil) {
mutableLengthDelimitedList_ = [otherLengthDelimitedList mutableCopy]; mutableLengthDelimitedList_ = [otherLengthDelimitedList mutableCopy];
} else { } else {
[mutableLengthDelimitedList_ [mutableLengthDelimitedList_ addObjectsFromArray:otherLengthDelimitedList];
addObjectsFromArray:otherLengthDelimitedList];
} }
} }
NSArray *otherGroupList = other.groupList; NSArray *otherGroupList = other.groupList;
if (otherGroupList.count > 0) { if (otherGroupList.count > 0) {
if (mutableGroupList_ == nil) { if (mutableGroupList_ == nil) {
mutableGroupList_ = mutableGroupList_ = [[NSMutableArray alloc] initWithCapacity:otherGroupList.count];
[[NSMutableArray alloc] initWithCapacity:otherGroupList.count];
} }
// Make our own mutable copies. // Make our own mutable copies.
for (GPBUnknownFieldSet *group in otherGroupList) { for (GPBUnknownFieldSet *group in otherGroupList) {
@ -299,8 +283,7 @@
- (void)addFixed32:(uint32_t)value { - (void)addFixed32:(uint32_t)value {
if (mutableFixed32List_ == nil) { if (mutableFixed32List_ == nil) {
mutableFixed32List_ = mutableFixed32List_ = [[GPBUInt32Array alloc] initWithValues:&value count:1];
[[GPBUInt32Array alloc] initWithValues:&value count:1];
} else { } else {
[mutableFixed32List_ addValue:value]; [mutableFixed32List_ addValue:value];
} }
@ -308,8 +291,7 @@
- (void)addFixed64:(uint64_t)value { - (void)addFixed64:(uint64_t)value {
if (mutableFixed64List_ == nil) { if (mutableFixed64List_ == nil) {
mutableFixed64List_ = mutableFixed64List_ = [[GPBUInt64Array alloc] initWithValues:&value count:1];
[[GPBUInt64Array alloc] initWithValues:&value count:1];
} else { } else {
[mutableFixed64List_ addValue:value]; [mutableFixed64List_ addValue:value];
} }
@ -317,8 +299,7 @@
- (void)addLengthDelimited:(NSData *)value { - (void)addLengthDelimited:(NSData *)value {
if (mutableLengthDelimitedList_ == nil) { if (mutableLengthDelimitedList_ == nil) {
mutableLengthDelimitedList_ = mutableLengthDelimitedList_ = [[NSMutableArray alloc] initWithObjects:&value count:1];
[[NSMutableArray alloc] initWithObjects:&value count:1];
} else { } else {
[mutableLengthDelimitedList_ addObject:value]; [mutableLengthDelimitedList_ addObject:value];
} }

@ -40,8 +40,7 @@
static void checkNumber(int32_t number) { static void checkNumber(int32_t number) {
if (number == 0) { if (number == 0) {
[NSException raise:NSInvalidArgumentException [NSException raise:NSInvalidArgumentException format:@"Zero is not a valid field number."];
format:@"Zero is not a valid field number."];
} }
} }
@ -111,8 +110,7 @@ static void CopyWorker(const void *key, const void *value, void *context) {
- (GPBUnknownField *)getField:(int32_t)number { - (GPBUnknownField *)getField:(int32_t)number {
ssize_t key = number; ssize_t key = number;
GPBUnknownField *result = GPBUnknownField *result = fields_ ? CFDictionaryGetValue(fields_, (void *)key) : nil;
fields_ ? CFDictionaryGetValue(fields_, (void *)key) : nil;
return result; return result;
} }
@ -125,8 +123,7 @@ static void CopyWorker(const void *key, const void *value, void *context) {
size_t count = CFDictionaryGetCount(fields_); size_t count = CFDictionaryGetCount(fields_);
ssize_t keys[count]; ssize_t keys[count];
GPBUnknownField *values[count]; GPBUnknownField *values[count];
CFDictionaryGetKeysAndValues(fields_, (const void **)keys, CFDictionaryGetKeysAndValues(fields_, (const void **)keys, (const void **)values);
(const void **)values);
struct GPBFieldPair { struct GPBFieldPair {
ssize_t key; ssize_t key;
GPBUnknownField *value; GPBUnknownField *value;
@ -135,8 +132,7 @@ static void CopyWorker(const void *key, const void *value, void *context) {
pairs[i].key = keys[i]; pairs[i].key = keys[i];
pairs[i].value = values[i]; pairs[i].value = values[i];
}; };
qsort_b(pairs, count, sizeof(struct GPBFieldPair), qsort_b(pairs, count, sizeof(struct GPBFieldPair), ^(const void *first, const void *second) {
^(const void *first, const void *second) {
const struct GPBFieldPair *a = first; const struct GPBFieldPair *a = first;
const struct GPBFieldPair *b = second; const struct GPBFieldPair *b = second;
return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1); return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1);
@ -154,8 +150,7 @@ static void CopyWorker(const void *key, const void *value, void *context) {
size_t count = CFDictionaryGetCount(fields_); size_t count = CFDictionaryGetCount(fields_);
ssize_t keys[count]; ssize_t keys[count];
GPBUnknownField *values[count]; GPBUnknownField *values[count];
CFDictionaryGetKeysAndValues(fields_, (const void **)keys, CFDictionaryGetKeysAndValues(fields_, (const void **)keys, (const void **)values);
(const void **)values);
if (count > 1) { if (count > 1) {
struct GPBFieldPair { struct GPBFieldPair {
ssize_t key; ssize_t key;
@ -166,8 +161,7 @@ static void CopyWorker(const void *key, const void *value, void *context) {
pairs[i].key = keys[i]; pairs[i].key = keys[i];
pairs[i].value = values[i]; pairs[i].value = values[i];
}; };
qsort_b(pairs, count, sizeof(struct GPBFieldPair), qsort_b(pairs, count, sizeof(struct GPBFieldPair), ^(const void *first, const void *second) {
^(const void *first, const void *second) {
const struct GPBFieldPair *a = first; const struct GPBFieldPair *a = first;
const struct GPBFieldPair *b = second; const struct GPBFieldPair *b = second;
return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1); return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1);
@ -182,16 +176,15 @@ static void CopyWorker(const void *key, const void *value, void *context) {
} }
- (NSString *)description { - (NSString *)description {
NSMutableString *description = [NSMutableString NSMutableString *description =
stringWithFormat:@"<%@ %p>: TextFormat: {\n", [self class], self]; [NSMutableString stringWithFormat:@"<%@ %p>: TextFormat: {\n", [self class], self];
NSString *textFormat = GPBTextFormatForUnknownFieldSet(self, @" "); NSString *textFormat = GPBTextFormatForUnknownFieldSet(self, @" ");
[description appendString:textFormat]; [description appendString:textFormat];
[description appendString:@"}"]; [description appendString:@"}"];
return description; return description;
} }
static void GPBUnknownFieldSetSerializedSize(const void *key, const void *value, static void GPBUnknownFieldSetSerializedSize(const void *key, const void *value, void *context) {
void *context) {
#pragma unused(key) #pragma unused(key)
GPBUnknownField *field = value; GPBUnknownField *field = value;
size_t *result = context; size_t *result = context;
@ -201,14 +194,12 @@ static void GPBUnknownFieldSetSerializedSize(const void *key, const void *value,
- (size_t)serializedSize { - (size_t)serializedSize {
size_t result = 0; size_t result = 0;
if (fields_) { if (fields_) {
CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetSerializedSize, CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetSerializedSize, &result);
&result);
} }
return result; return result;
} }
static void GPBUnknownFieldSetWriteAsMessageSetTo(const void *key, static void GPBUnknownFieldSetWriteAsMessageSetTo(const void *key, const void *value,
const void *value,
void *context) { void *context) {
#pragma unused(key) #pragma unused(key)
GPBUnknownField *field = value; GPBUnknownField *field = value;
@ -218,13 +209,11 @@ static void GPBUnknownFieldSetWriteAsMessageSetTo(const void *key,
- (void)writeAsMessageSetTo:(GPBCodedOutputStream *)output { - (void)writeAsMessageSetTo:(GPBCodedOutputStream *)output {
if (fields_) { if (fields_) {
CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetWriteAsMessageSetTo, CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetWriteAsMessageSetTo, output);
output);
} }
} }
static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key, static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key, const void *value,
const void *value,
void *context) { void *context) {
#pragma unused(key) #pragma unused(key)
GPBUnknownField *field = value; GPBUnknownField *field = value;
@ -235,16 +224,14 @@ static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key,
- (size_t)serializedSizeAsMessageSet { - (size_t)serializedSizeAsMessageSet {
size_t result = 0; size_t result = 0;
if (fields_) { if (fields_) {
CFDictionaryApplyFunction( CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetSerializedSizeAsMessageSet, &result);
fields_, GPBUnknownFieldSetSerializedSizeAsMessageSet, &result);
} }
return result; return result;
} }
- (NSData *)data { - (NSData *)data {
NSMutableData *data = [NSMutableData dataWithLength:self.serializedSize]; NSMutableData *data = [NSMutableData dataWithLength:self.serializedSize];
GPBCodedOutputStream *output = GPBCodedOutputStream *output = [[GPBCodedOutputStream alloc] initWithData:data];
[[GPBCodedOutputStream alloc] initWithData:data];
[self writeToCodedOutputStream:output]; [self writeToCodedOutputStream:output];
[output release]; [output release];
return data; return data;
@ -260,8 +247,8 @@ static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key,
if (!fields_) { if (!fields_) {
// Use a custom dictionary here because the keys are numbers and conversion // Use a custom dictionary here because the keys are numbers and conversion
// back and forth from NSNumber isn't worth the cost. // back and forth from NSNumber isn't worth the cost.
fields_ = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, fields_ =
&kCFTypeDictionaryValueCallBacks); CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks);
} }
ssize_t key = number; ssize_t key = number;
CFDictionarySetValue(fields_, (const void *)key, field); CFDictionarySetValue(fields_, (const void *)key, field);
@ -269,8 +256,7 @@ static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key,
- (GPBUnknownField *)mutableFieldForNumber:(int32_t)number create:(BOOL)create { - (GPBUnknownField *)mutableFieldForNumber:(int32_t)number create:(BOOL)create {
ssize_t key = number; ssize_t key = number;
GPBUnknownField *existing = GPBUnknownField *existing = fields_ ? CFDictionaryGetValue(fields_, (const void *)key) : nil;
fields_ ? CFDictionaryGetValue(fields_, (const void *)key) : nil;
if (!existing && create) { if (!existing && create) {
existing = [[GPBUnknownField alloc] initWithNumber:number]; existing = [[GPBUnknownField alloc] initWithNumber:number];
// This retains existing. // This retains existing.
@ -280,8 +266,7 @@ static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key,
return existing; return existing;
} }
static void GPBUnknownFieldSetMergeUnknownFields(const void *key, static void GPBUnknownFieldSetMergeUnknownFields(const void *key, const void *value,
const void *value,
void *context) { void *context) {
#pragma unused(key) #pragma unused(key)
GPBUnknownField *field = value; GPBUnknownField *field = value;
@ -304,8 +289,7 @@ static void GPBUnknownFieldSetMergeUnknownFields(const void *key,
- (void)mergeUnknownFields:(GPBUnknownFieldSet *)other { - (void)mergeUnknownFields:(GPBUnknownFieldSet *)other {
if (other && other->fields_) { if (other && other->fields_) {
CFDictionaryApplyFunction(other->fields_, CFDictionaryApplyFunction(other->fields_, GPBUnknownFieldSetMergeUnknownFields, self);
GPBUnknownFieldSetMergeUnknownFields, self);
} }
} }
@ -362,8 +346,7 @@ static void GPBUnknownFieldSetMergeUnknownFields(const void *key,
} }
- (void)mergeMessageSetMessage:(int32_t)number data:(NSData *)messageData { - (void)mergeMessageSetMessage:(int32_t)number data:(NSData *)messageData {
[[self mutableFieldForNumber:number create:YES] [[self mutableFieldForNumber:number create:YES] addLengthDelimited:messageData];
addLengthDelimited:messageData];
} }
- (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data { - (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data {

@ -45,28 +45,24 @@
#pragma clang diagnostic push #pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdirect-ivar-access" #pragma clang diagnostic ignored "-Wdirect-ivar-access"
static void AppendTextFormatForMessage(GPBMessage *message, static void AppendTextFormatForMessage(GPBMessage *message, NSMutableString *toStr,
NSMutableString *toStr,
NSString *lineIndent); NSString *lineIndent);
// Are two datatypes the same basic type representation (ex Int32 and SInt32). // Are two datatypes the same basic type representation (ex Int32 and SInt32).
// Marked unused because currently only called from asserts/debug. // Marked unused because currently only called from asserts/debug.
static BOOL DataTypesEquivalent(GPBDataType type1, static BOOL DataTypesEquivalent(GPBDataType type1, GPBDataType type2) __attribute__((unused));
GPBDataType type2) __attribute__ ((unused));
// Basic type representation for a type (ex: for SInt32 it is Int32). // Basic type representation for a type (ex: for SInt32 it is Int32).
// Marked unused because currently only called from asserts/debug. // Marked unused because currently only called from asserts/debug.
static GPBDataType BaseDataType(GPBDataType type) __attribute__ ((unused)); static GPBDataType BaseDataType(GPBDataType type) __attribute__((unused));
// String name for a data type. // String name for a data type.
// Marked unused because currently only called from asserts/debug. // Marked unused because currently only called from asserts/debug.
static NSString *TypeToString(GPBDataType dataType) __attribute__ ((unused)); static NSString *TypeToString(GPBDataType dataType) __attribute__((unused));
// Helper for clearing oneofs. // Helper for clearing oneofs.
static void GPBMaybeClearOneofPrivate(GPBMessage *self, static void GPBMaybeClearOneofPrivate(GPBMessage *self, GPBOneofDescriptor *oneof,
GPBOneofDescriptor *oneof, int32_t oneofHasIndex, uint32_t fieldNumberNotToClear);
int32_t oneofHasIndex,
uint32_t fieldNumberNotToClear);
NSData *GPBEmptyNSData(void) { NSData *GPBEmptyNSData(void) {
static dispatch_once_t onceToken; static dispatch_once_t onceToken;
@ -118,50 +114,56 @@ void GPBMessageDropUnknownFieldsRecursively(GPBMessage *initialMessage) {
id rawFieldMap = GPBGetObjectIvarWithFieldNoAutocreate(msg, field); id rawFieldMap = GPBGetObjectIvarWithFieldNoAutocreate(msg, field);
switch (field.mapKeyDataType) { switch (field.mapKeyDataType) {
case GPBDataTypeBool: case GPBDataTypeBool:
[(GPBBoolObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( [(GPBBoolObjectDictionary *)rawFieldMap
BOOL key, id _Nonnull object, BOOL * _Nonnull stop) { enumerateKeysAndObjectsUsingBlock:^(BOOL key, id _Nonnull object,
#pragma unused(key, stop) BOOL *_Nonnull stop) {
#pragma unused(key, stop)
[todo addObject:object]; [todo addObject:object];
}]; }];
break; break;
case GPBDataTypeFixed32: case GPBDataTypeFixed32:
case GPBDataTypeUInt32: case GPBDataTypeUInt32:
[(GPBUInt32ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( [(GPBUInt32ObjectDictionary *)rawFieldMap
uint32_t key, id _Nonnull object, BOOL * _Nonnull stop) { enumerateKeysAndObjectsUsingBlock:^(uint32_t key, id _Nonnull object,
#pragma unused(key, stop) BOOL *_Nonnull stop) {
#pragma unused(key, stop)
[todo addObject:object]; [todo addObject:object];
}]; }];
break; break;
case GPBDataTypeInt32: case GPBDataTypeInt32:
case GPBDataTypeSFixed32: case GPBDataTypeSFixed32:
case GPBDataTypeSInt32: case GPBDataTypeSInt32:
[(GPBInt32ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( [(GPBInt32ObjectDictionary *)rawFieldMap
int32_t key, id _Nonnull object, BOOL * _Nonnull stop) { enumerateKeysAndObjectsUsingBlock:^(int32_t key, id _Nonnull object,
#pragma unused(key, stop) BOOL *_Nonnull stop) {
#pragma unused(key, stop)
[todo addObject:object]; [todo addObject:object];
}]; }];
break; break;
case GPBDataTypeFixed64: case GPBDataTypeFixed64:
case GPBDataTypeUInt64: case GPBDataTypeUInt64:
[(GPBUInt64ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( [(GPBUInt64ObjectDictionary *)rawFieldMap
uint64_t key, id _Nonnull object, BOOL * _Nonnull stop) { enumerateKeysAndObjectsUsingBlock:^(uint64_t key, id _Nonnull object,
#pragma unused(key, stop) BOOL *_Nonnull stop) {
#pragma unused(key, stop)
[todo addObject:object]; [todo addObject:object];
}]; }];
break; break;
case GPBDataTypeInt64: case GPBDataTypeInt64:
case GPBDataTypeSFixed64: case GPBDataTypeSFixed64:
case GPBDataTypeSInt64: case GPBDataTypeSInt64:
[(GPBInt64ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( [(GPBInt64ObjectDictionary *)rawFieldMap
int64_t key, id _Nonnull object, BOOL * _Nonnull stop) { enumerateKeysAndObjectsUsingBlock:^(int64_t key, id _Nonnull object,
#pragma unused(key, stop) BOOL *_Nonnull stop) {
#pragma unused(key, stop)
[todo addObject:object]; [todo addObject:object];
}]; }];
break; break;
case GPBDataTypeString: case GPBDataTypeString:
[(NSDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( [(NSDictionary *)rawFieldMap
NSString * _Nonnull key, GPBMessage * _Nonnull obj, BOOL * _Nonnull stop) { enumerateKeysAndObjectsUsingBlock:^(
#pragma unused(key, stop) NSString *_Nonnull key, GPBMessage *_Nonnull obj, BOOL *_Nonnull stop) {
#pragma unused(key, stop)
[todo addObject:obj]; [todo addObject:obj];
}]; }];
break; break;
@ -195,7 +197,6 @@ void GPBMessageDropUnknownFieldsRecursively(GPBMessage *initialMessage) {
} // while(todo.count) } // while(todo.count)
} }
// -- About Version Checks -- // -- About Version Checks --
// There's actually 3 places these checks all come into play: // There's actually 3 places these checks all come into play:
// 1. When the generated source is compile into .o files, the header check // 1. When the generated source is compile into .o files, the header check
@ -228,8 +229,7 @@ void GPBCheckRuntimeVersionSupport(int32_t objcRuntimeVersion) {
format:@"Proto generation source compiled against runtime" format:@"Proto generation source compiled against runtime"
@" version %d, but this version of the runtime only" @" version %d, but this version of the runtime only"
@" supports back to %d!", @" supports back to %d!",
objcRuntimeVersion, objcRuntimeVersion, GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION];
GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION];
} }
} }
@ -288,18 +288,16 @@ void GPBClearMessageField(GPBMessage *self, GPBFieldDescriptor *field) {
} }
void GPBClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof) { void GPBClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof) {
#if defined(DEBUG) && DEBUG #if defined(DEBUG) && DEBUG
NSCAssert([[self descriptor] oneofWithName:oneof.name] == oneof, NSCAssert([[self descriptor] oneofWithName:oneof.name] == oneof,
@"OneofDescriptor %@ doesn't appear to be for %@ messages.", @"OneofDescriptor %@ doesn't appear to be for %@ messages.", oneof.name, [self class]);
oneof.name, [self class]); #endif
#endif
GPBFieldDescriptor *firstField = oneof->fields_[0]; GPBFieldDescriptor *firstField = oneof->fields_[0];
GPBMaybeClearOneofPrivate(self, oneof, firstField->description_->hasIndex, 0); GPBMaybeClearOneofPrivate(self, oneof, firstField->description_->hasIndex, 0);
} }
BOOL GPBGetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber) { BOOL GPBGetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber) {
NSCAssert(self->messageStorage_ != NULL, NSCAssert(self->messageStorage_ != NULL, @"%@: All messages should have storage (from init)",
@"%@: All messages should have storage (from init)",
[self class]); [self class]);
if (idx < 0) { if (idx < 0) {
NSCAssert(fieldNumber != 0, @"Invalid field number."); NSCAssert(fieldNumber != 0, @"Invalid field number.");
@ -309,21 +307,18 @@ BOOL GPBGetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber) {
NSCAssert(idx != GPBNoHasBit, @"Invalid has bit."); NSCAssert(idx != GPBNoHasBit, @"Invalid has bit.");
uint32_t byteIndex = idx / 32; uint32_t byteIndex = idx / 32;
uint32_t bitMask = (1U << (idx % 32)); uint32_t bitMask = (1U << (idx % 32));
BOOL hasIvar = BOOL hasIvar = (self->messageStorage_->_has_storage_[byteIndex] & bitMask) ? YES : NO;
(self->messageStorage_->_has_storage_[byteIndex] & bitMask) ? YES : NO;
return hasIvar; return hasIvar;
} }
} }
uint32_t GPBGetHasOneof(GPBMessage *self, int32_t idx) { uint32_t GPBGetHasOneof(GPBMessage *self, int32_t idx) {
NSCAssert(idx < 0, @"%@: invalid index (%d) for oneof.", NSCAssert(idx < 0, @"%@: invalid index (%d) for oneof.", [self class], idx);
[self class], idx);
uint32_t result = self->messageStorage_->_has_storage_[-idx]; uint32_t result = self->messageStorage_->_has_storage_[-idx];
return result; return result;
} }
void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber, void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber, BOOL value) {
BOOL value) {
if (idx < 0) { if (idx < 0) {
NSCAssert(fieldNumber != 0, @"Invalid field number."); NSCAssert(fieldNumber != 0, @"Invalid field number.");
uint32_t *has_storage = self->messageStorage_->_has_storage_; uint32_t *has_storage = self->messageStorage_->_has_storage_;
@ -341,10 +336,8 @@ void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber,
} }
} }
static void GPBMaybeClearOneofPrivate(GPBMessage *self, static void GPBMaybeClearOneofPrivate(GPBMessage *self, GPBOneofDescriptor *oneof,
GPBOneofDescriptor *oneof, int32_t oneofHasIndex, uint32_t fieldNumberNotToClear) {
int32_t oneofHasIndex,
uint32_t fieldNumberNotToClear) {
uint32_t fieldNumberSet = GPBGetHasOneof(self, oneofHasIndex); uint32_t fieldNumberSet = GPBGetHasOneof(self, oneofHasIndex);
if ((fieldNumberSet == fieldNumberNotToClear) || (fieldNumberSet == 0)) { if ((fieldNumberSet == fieldNumberNotToClear) || (fieldNumberSet == 0)) {
// Do nothing/nothing set in the oneof. // Do nothing/nothing set in the oneof.
@ -354,9 +347,8 @@ static void GPBMaybeClearOneofPrivate(GPBMessage *self,
// Like GPBClearMessageField(), free the memory if an objecttype is set, // Like GPBClearMessageField(), free the memory if an objecttype is set,
// pod types don't need to do anything. // pod types don't need to do anything.
GPBFieldDescriptor *fieldSet = [oneof fieldWithNumber:fieldNumberSet]; GPBFieldDescriptor *fieldSet = [oneof fieldWithNumber:fieldNumberSet];
NSCAssert(fieldSet, NSCAssert(fieldSet, @"%@: oneof set to something (%u) not in the oneof?", [self class],
@"%@: oneof set to something (%u) not in the oneof?", fieldNumberSet);
[self class], fieldNumberSet);
if (fieldSet && GPBFieldStoresObject(fieldSet)) { if (fieldSet && GPBFieldStoresObject(fieldSet)) {
uint8_t *storage = (uint8_t *)self->messageStorage_; uint8_t *storage = (uint8_t *)self->messageStorage_;
id *typePtr = (id *)&storage[fieldSet->description_->offset]; id *typePtr = (id *)&storage[fieldSet->description_->offset];
@ -508,8 +500,7 @@ static void GPBMaybeClearOneofPrivate(GPBMessage *self,
// Object types are handled slightly differently, they need to be released // Object types are handled slightly differently, they need to be released
// and retained. // and retained.
void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self, void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
GPBFieldDescriptor *field) {
if (GPBGetHasIvarField(self, field)) { if (GPBGetHasIvarField(self, field)) {
return; return;
} }
@ -522,14 +513,12 @@ void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self,
} }
// This exists only for bridging some aliased types, nothing else should use it. // This exists only for bridging some aliased types, nothing else should use it.
static void GPBSetObjectIvarWithField(GPBMessage *self, static void GPBSetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field, id value) {
GPBFieldDescriptor *field, id value) {
if (self == nil || field == nil) return; if (self == nil || field == nil) return;
GPBSetRetainedObjectIvarWithFieldPrivate(self, field, [value retain]); GPBSetRetainedObjectIvarWithFieldPrivate(self, field, [value retain]);
} }
static void GPBSetCopyObjectIvarWithField(GPBMessage *self, static void GPBSetCopyObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field, id value);
GPBFieldDescriptor *field, id value);
// GPBSetCopyObjectIvarWithField is blocked from the analyzer because it flags // GPBSetCopyObjectIvarWithField is blocked from the analyzer because it flags
// a leak for the -copy even though GPBSetRetainedObjectIvarWithFieldPrivate // a leak for the -copy even though GPBSetRetainedObjectIvarWithFieldPrivate
@ -537,23 +526,19 @@ static void GPBSetCopyObjectIvarWithField(GPBMessage *self,
// with the -retain in GPBSetObjectIvarWithField. // with the -retain in GPBSetObjectIvarWithField.
#if !defined(__clang_analyzer__) #if !defined(__clang_analyzer__)
// This exists only for bridging some aliased types, nothing else should use it. // This exists only for bridging some aliased types, nothing else should use it.
static void GPBSetCopyObjectIvarWithField(GPBMessage *self, static void GPBSetCopyObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field, id value) {
GPBFieldDescriptor *field, id value) {
if (self == nil || field == nil) return; if (self == nil || field == nil) return;
GPBSetRetainedObjectIvarWithFieldPrivate(self, field, [value copy]); GPBSetRetainedObjectIvarWithFieldPrivate(self, field, [value copy]);
} }
#endif // !defined(__clang_analyzer__) #endif // !defined(__clang_analyzer__)
void GPBSetObjectIvarWithFieldPrivate(GPBMessage *self, void GPBSetObjectIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, id value) {
GPBFieldDescriptor *field, id value) {
GPBSetRetainedObjectIvarWithFieldPrivate(self, field, [value retain]); GPBSetRetainedObjectIvarWithFieldPrivate(self, field, [value retain]);
} }
void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self, void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field,
GPBFieldDescriptor *field,
id value) { id value) {
NSCAssert(self->messageStorage_ != NULL, NSCAssert(self->messageStorage_ != NULL, @"%@: All messages should have storage (from init)",
@"%@: All messages should have storage (from init)",
[self class]); [self class]);
#if defined(__clang_analyzer__) #if defined(__clang_analyzer__)
if (self->messageStorage_ == NULL) return; if (self->messageStorage_ == NULL) return;
@ -562,8 +547,7 @@ void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self,
BOOL isMapOrArray = GPBFieldIsMapOrArray(field); BOOL isMapOrArray = GPBFieldIsMapOrArray(field);
BOOL fieldIsMessage = GPBDataTypeIsMessage(fieldType); BOOL fieldIsMessage = GPBDataTypeIsMessage(fieldType);
#if defined(DEBUG) && DEBUG #if defined(DEBUG) && DEBUG
if (value == nil && !isMapOrArray && !fieldIsMessage && if (value == nil && !isMapOrArray && !fieldIsMessage && field.hasDefaultValue) {
field.hasDefaultValue) {
// Setting a message to nil is an obvious way to "clear" the value // Setting a message to nil is an obvious way to "clear" the value
// as there is no way to set a non-empty default value for messages. // as there is no way to set a non-empty default value for messages.
// //
@ -584,8 +568,8 @@ void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self,
@"empty, or call '%@.%@ = NO' to reset it to it's default value of " @"empty, or call '%@.%@ = NO' to reset it to it's default value of "
@"'%@'. Defaulting to resetting default value.", @"'%@'. Defaulting to resetting default value.",
className, propName, className, propName, className, propName, className, propName,
(fieldType == GPBDataTypeString) ? @"@\"\"" : @"GPBEmptyNSData()", (fieldType == GPBDataTypeString) ? @"@\"\"" : @"GPBEmptyNSData()", className, hasSel,
className, hasSel, field.defaultValue.valueString); field.defaultValue.valueString);
// Note: valueString, depending on the type, it could easily be // Note: valueString, depending on the type, it could easily be
// valueData/valueMessage. // valueData/valueMessage.
} }
@ -602,8 +586,7 @@ void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self,
BOOL setHasValue = (value != nil); BOOL setHasValue = (value != nil);
// If the field should clear on a "zero" value, then check if the string/data // If the field should clear on a "zero" value, then check if the string/data
// was zero length, and clear instead. // was zero length, and clear instead.
if (((fieldDesc->flags & GPBFieldClearHasIvarOnZero) != 0) && if (((fieldDesc->flags & GPBFieldClearHasIvarOnZero) != 0) && ([value length] == 0)) {
([value length] == 0)) {
setHasValue = NO; setHasValue = NO;
// The value passed in was retained, it must be released since we // The value passed in was retained, it must be released since we
// aren't saving anything in the field. // aren't saving anything in the field.
@ -639,8 +622,7 @@ void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self,
} }
} else { // GPBFieldTypeMap } else { // GPBFieldTypeMap
// If the old map was autocreated by us, then clear it. // If the old map was autocreated by us, then clear it.
if ((field.mapKeyDataType == GPBDataTypeString) && if ((field.mapKeyDataType == GPBDataTypeString) && GPBDataTypeIsObject(fieldType)) {
GPBDataTypeIsObject(fieldType)) {
if ([oldValue isKindOfClass:[GPBAutocreatedDictionary class]]) { if ([oldValue isKindOfClass:[GPBAutocreatedDictionary class]]) {
GPBAutocreatedDictionary *autoDict = oldValue; GPBAutocreatedDictionary *autoDict = oldValue;
if (autoDict->_autocreator == self) { if (autoDict->_autocreator == self) {
@ -668,8 +650,7 @@ void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self,
GPBBecomeVisibleToAutocreator(self); GPBBecomeVisibleToAutocreator(self);
} }
id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self, id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self, GPBFieldDescriptor *field) {
GPBFieldDescriptor *field) {
if (self->messageStorage_ == nil) { if (self->messageStorage_ == nil) {
return nil; return nil;
} }
@ -680,80 +661,68 @@ id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self,
// Only exists for public api, no core code should use this. // Only exists for public api, no core code should use this.
int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field) { int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field) {
#if defined(DEBUG) && DEBUG #if defined(DEBUG) && DEBUG
NSCAssert([[self descriptor] fieldWithNumber:field.number] == field, NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
@"FieldDescriptor %@ doesn't appear to be for %@ messages.", @"FieldDescriptor %@ doesn't appear to be for %@ messages.", field.name, [self class]);
field.name, [self class]);
NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum, NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum,
@"Attempting to get value of type Enum from field %@ " @"Attempting to get value of type Enum from field %@ "
@"of %@ which is of type %@.", @"of %@ which is of type %@.",
[self class], field.name, [self class], field.name, TypeToString(GPBGetFieldDataType(field)));
TypeToString(GPBGetFieldDataType(field))); #endif
#endif
int32_t result = GPBGetMessageInt32Field(self, field); int32_t result = GPBGetMessageInt32Field(self, field);
// If this is presevering unknown enums, make sure the value is valid before // If this is presevering unknown enums, make sure the value is valid before
// returning it. // returning it.
GPBFileSyntax syntax = [self descriptor].file.syntax; GPBFileSyntax syntax = [self descriptor].file.syntax;
if (GPBHasPreservingUnknownEnumSemantics(syntax) && if (GPBHasPreservingUnknownEnumSemantics(syntax) && ![field isValidEnumValue:result]) {
![field isValidEnumValue:result]) {
result = kGPBUnrecognizedEnumeratorValue; result = kGPBUnrecognizedEnumeratorValue;
} }
return result; return result;
} }
// Only exists for public api, no core code should use this. // Only exists for public api, no core code should use this.
void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field, void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field, int32_t value) {
int32_t value) { #if defined(DEBUG) && DEBUG
#if defined(DEBUG) && DEBUG
NSCAssert([[self descriptor] fieldWithNumber:field.number] == field, NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
@"FieldDescriptor %@ doesn't appear to be for %@ messages.", @"FieldDescriptor %@ doesn't appear to be for %@ messages.", field.name, [self class]);
field.name, [self class]);
NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum, NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum,
@"Attempting to set field %@ of %@ which is of type %@ with " @"Attempting to set field %@ of %@ which is of type %@ with "
@"value of type Enum.", @"value of type Enum.",
[self class], field.name, [self class], field.name, TypeToString(GPBGetFieldDataType(field)));
TypeToString(GPBGetFieldDataType(field))); #endif
#endif
GPBSetEnumIvarWithFieldPrivate(self, field, value); GPBSetEnumIvarWithFieldPrivate(self, field, value);
} }
void GPBSetEnumIvarWithFieldPrivate(GPBMessage *self, void GPBSetEnumIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, int32_t value) {
GPBFieldDescriptor *field, int32_t value) {
// Don't allow in unknown values. Proto3 can use the Raw method. // Don't allow in unknown values. Proto3 can use the Raw method.
if (![field isValidEnumValue:value]) { if (![field isValidEnumValue:value]) {
[NSException raise:NSInvalidArgumentException [NSException raise:NSInvalidArgumentException
format:@"%@.%@: Attempt to set an unknown enum value (%d)", format:@"%@.%@: Attempt to set an unknown enum value (%d)", [self class],
[self class], field.name, value]; field.name, value];
} }
GPBSetInt32IvarWithFieldPrivate(self, field, value); GPBSetInt32IvarWithFieldPrivate(self, field, value);
} }
// Only exists for public api, no core code should use this. // Only exists for public api, no core code should use this.
int32_t GPBGetMessageRawEnumField(GPBMessage *self, int32_t GPBGetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field) {
GPBFieldDescriptor *field) {
int32_t result = GPBGetMessageInt32Field(self, field); int32_t result = GPBGetMessageInt32Field(self, field);
return result; return result;
} }
// Only exists for public api, no core code should use this. // Only exists for public api, no core code should use this.
void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field, void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field, int32_t value) {
int32_t value) {
GPBSetInt32IvarWithFieldPrivate(self, field, value); GPBSetInt32IvarWithFieldPrivate(self, field, value);
} }
BOOL GPBGetMessageBoolField(GPBMessage *self, BOOL GPBGetMessageBoolField(GPBMessage *self, GPBFieldDescriptor *field) {
GPBFieldDescriptor *field) {
#if defined(DEBUG) && DEBUG #if defined(DEBUG) && DEBUG
NSCAssert([[self descriptor] fieldWithNumber:field.number] == field, NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
@"FieldDescriptor %@ doesn't appear to be for %@ messages.", @"FieldDescriptor %@ doesn't appear to be for %@ messages.", field.name, [self class]);
field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool), NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool),
@"Attempting to get value of type bool from field %@ " @"Attempting to get value of type bool from field %@ "
@"of %@ which is of type %@.", @"of %@ which is of type %@.",
[self class], field.name, [self class], field.name, TypeToString(GPBGetFieldDataType(field)));
TypeToString(GPBGetFieldDataType(field)));
#endif #endif
if (GPBGetHasIvarField(self, field)) { if (GPBGetHasIvarField(self, field)) {
// Bools are stored in the has bits to avoid needing explicit space in the // Bools are stored in the has bits to avoid needing explicit space in the
@ -768,26 +737,20 @@ BOOL GPBGetMessageBoolField(GPBMessage *self,
} }
// Only exists for public api, no core code should use this. // Only exists for public api, no core code should use this.
void GPBSetMessageBoolField(GPBMessage *self, void GPBSetMessageBoolField(GPBMessage *self, GPBFieldDescriptor *field, BOOL value) {
GPBFieldDescriptor *field,
BOOL value) {
if (self == nil || field == nil) return; if (self == nil || field == nil) return;
#if defined(DEBUG) && DEBUG #if defined(DEBUG) && DEBUG
NSCAssert([[self descriptor] fieldWithNumber:field.number] == field, NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
@"FieldDescriptor %@ doesn't appear to be for %@ messages.", @"FieldDescriptor %@ doesn't appear to be for %@ messages.", field.name, [self class]);
field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool), NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool),
@"Attempting to set field %@ of %@ which is of type %@ with " @"Attempting to set field %@ of %@ which is of type %@ with "
@"value of type bool.", @"value of type bool.",
[self class], field.name, [self class], field.name, TypeToString(GPBGetFieldDataType(field)));
TypeToString(GPBGetFieldDataType(field))); #endif
#endif
GPBSetBoolIvarWithFieldPrivate(self, field, value); GPBSetBoolIvarWithFieldPrivate(self, field, value);
} }
void GPBSetBoolIvarWithFieldPrivate(GPBMessage *self, void GPBSetBoolIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, BOOL value) {
GPBFieldDescriptor *field,
BOOL value) {
GPBMessageFieldDescription *fieldDesc = field->description_; GPBMessageFieldDescription *fieldDesc = field->description_;
GPBOneofDescriptor *oneof = field->containingOneof_; GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) { if (oneof) {
@ -802,8 +765,7 @@ void GPBSetBoolIvarWithFieldPrivate(GPBMessage *self,
// If the value is zero, then we only count the field as "set" if the field // If the value is zero, then we only count the field as "set" if the field
// shouldn't auto clear on zero. // shouldn't auto clear on zero.
BOOL hasValue = ((value != (BOOL)0) BOOL hasValue = ((value != (BOOL)0) || ((fieldDesc->flags & GPBFieldClearHasIvarOnZero) == 0));
|| ((fieldDesc->flags & GPBFieldClearHasIvarOnZero) == 0));
GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, hasValue); GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, hasValue);
GPBBecomeVisibleToAutocreator(self); GPBBecomeVisibleToAutocreator(self);
} }
@ -1379,8 +1341,7 @@ void GPBSetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field, id
#if defined(DEBUG) && DEBUG #if defined(DEBUG) && DEBUG
if (field.fieldType != GPBFieldTypeRepeated) { if (field.fieldType != GPBFieldTypeRepeated) {
[NSException raise:NSInvalidArgumentException [NSException raise:NSInvalidArgumentException
format:@"%@.%@ is not a repeated field.", format:@"%@.%@ is not a repeated field.", [self class], field.name];
[self class], field.name];
} }
Class expectedClass = Nil; Class expectedClass = Nil;
switch (GPBGetFieldDataType(field)) { switch (GPBGetFieldDataType(field)) {
@ -1423,8 +1384,8 @@ void GPBSetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field, id
} }
if (array && ![array isKindOfClass:expectedClass]) { if (array && ![array isKindOfClass:expectedClass]) {
[NSException raise:NSInvalidArgumentException [NSException raise:NSInvalidArgumentException
format:@"%@.%@: Expected %@ object, got %@.", format:@"%@.%@: Expected %@ object, got %@.", [self class], field.name,
[self class], field.name, expectedClass, [array class]]; expectedClass, [array class]];
} }
#endif #endif
GPBSetObjectIvarWithField(self, field, array); GPBSetObjectIvarWithField(self, field, array);
@ -1498,13 +1459,11 @@ static NSString *TypeToString(GPBDataType dataType) {
// GPBGetMessageMapField is defined in GPBMessage.m // GPBGetMessageMapField is defined in GPBMessage.m
// Only exists for public api, no core code should use this. // Only exists for public api, no core code should use this.
void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field, void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field, id dictionary) {
id dictionary) {
#if defined(DEBUG) && DEBUG #if defined(DEBUG) && DEBUG
if (field.fieldType != GPBFieldTypeMap) { if (field.fieldType != GPBFieldTypeMap) {
[NSException raise:NSInvalidArgumentException [NSException raise:NSInvalidArgumentException
format:@"%@.%@ is not a map<> field.", format:@"%@.%@ is not a map<> field.", [self class], field.name];
[self class], field.name];
} }
if (dictionary) { if (dictionary) {
GPBDataType keyDataType = field.mapKeyDataType; GPBDataType keyDataType = field.mapKeyDataType;
@ -1515,20 +1474,17 @@ void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field,
keyStr = @"String"; keyStr = @"String";
} }
Class expectedClass = Nil; Class expectedClass = Nil;
if ((keyDataType == GPBDataTypeString) && if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) {
GPBDataTypeIsObject(valueDataType)) {
expectedClass = [NSMutableDictionary class]; expectedClass = [NSMutableDictionary class];
} else { } else {
NSString *className = NSString *className = [NSString stringWithFormat:@"GPB%@%@Dictionary", keyStr, valueStr];
[NSString stringWithFormat:@"GPB%@%@Dictionary", keyStr, valueStr];
expectedClass = NSClassFromString(className); expectedClass = NSClassFromString(className);
NSCAssert(expectedClass, @"Missing a class (%@)?", expectedClass); NSCAssert(expectedClass, @"Missing a class (%@)?", expectedClass);
} }
if (![dictionary isKindOfClass:expectedClass]) { if (![dictionary isKindOfClass:expectedClass]) {
[NSException raise:NSInvalidArgumentException [NSException raise:NSInvalidArgumentException
format:@"%@.%@: Expected %@ object, got %@.", format:@"%@.%@: Expected %@ object, got %@.", [self class], field.name,
[self class], field.name, expectedClass, expectedClass, [dictionary class]];
[dictionary class]];
} }
} }
#endif #endif
@ -1538,13 +1494,12 @@ void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field,
#pragma mark - Misc Dynamic Runtime Utils #pragma mark - Misc Dynamic Runtime Utils
const char *GPBMessageEncodingForSelector(SEL selector, BOOL instanceSel) { const char *GPBMessageEncodingForSelector(SEL selector, BOOL instanceSel) {
Protocol *protocol = Protocol *protocol = objc_getProtocol(GPBStringifySymbol(GPBMessageSignatureProtocol));
objc_getProtocol(GPBStringifySymbol(GPBMessageSignatureProtocol));
NSCAssert(protocol, @"Missing GPBMessageSignatureProtocol"); NSCAssert(protocol, @"Missing GPBMessageSignatureProtocol");
struct objc_method_description description = struct objc_method_description description =
protocol_getMethodDescription(protocol, selector, NO, instanceSel); protocol_getMethodDescription(protocol, selector, NO, instanceSel);
NSCAssert(description.name != Nil && description.types != nil, NSCAssert(description.name != Nil && description.types != nil, @"Missing method for selector %@",
@"Missing method for selector %@", NSStringFromSelector(selector)); NSStringFromSelector(selector));
return description.types; return description.types;
} }
@ -1556,19 +1511,30 @@ static void AppendStringEscaped(NSString *toPrint, NSMutableString *destStr) {
for (NSUInteger i = 0; i < len; ++i) { for (NSUInteger i = 0; i < len; ++i) {
unichar aChar = [toPrint characterAtIndex:i]; unichar aChar = [toPrint characterAtIndex:i];
switch (aChar) { switch (aChar) {
case '\n': [destStr appendString:@"\\n"]; break; case '\n':
case '\r': [destStr appendString:@"\\r"]; break; [destStr appendString:@"\\n"];
case '\t': [destStr appendString:@"\\t"]; break; break;
case '\"': [destStr appendString:@"\\\""]; break; case '\r':
case '\'': [destStr appendString:@"\\\'"]; break; [destStr appendString:@"\\r"];
case '\\': [destStr appendString:@"\\\\"]; break; break;
case '\t':
[destStr appendString:@"\\t"];
break;
case '\"':
[destStr appendString:@"\\\""];
break;
case '\'':
[destStr appendString:@"\\\'"];
break;
case '\\':
[destStr appendString:@"\\\\"];
break;
default: default:
// This differs slightly from the C++ code in that the C++ doesn't // This differs slightly from the C++ code in that the C++ doesn't
// generate UTF8; it looks at the string in UTF8, but escapes every // generate UTF8; it looks at the string in UTF8, but escapes every
// byte > 0x7E. // byte > 0x7E.
if (aChar < 0x20) { if (aChar < 0x20) {
[destStr appendFormat:@"\\%d%d%d", [destStr appendFormat:@"\\%d%d%d", (aChar / 64), ((aChar % 64) / 8), (aChar % 8)];
(aChar / 64), ((aChar % 64) / 8), (aChar % 8)];
} else { } else {
[destStr appendFormat:@"%C", aChar]; [destStr appendFormat:@"%C", aChar];
} }
@ -1584,12 +1550,24 @@ static void AppendBufferAsString(NSData *buffer, NSMutableString *destStr) {
[destStr appendString:@"\""]; [destStr appendString:@"\""];
for (const char *srcEnd = src + srcLen; src < srcEnd; src++) { for (const char *srcEnd = src + srcLen; src < srcEnd; src++) {
switch (*src) { switch (*src) {
case '\n': [destStr appendString:@"\\n"]; break; case '\n':
case '\r': [destStr appendString:@"\\r"]; break; [destStr appendString:@"\\n"];
case '\t': [destStr appendString:@"\\t"]; break; break;
case '\"': [destStr appendString:@"\\\""]; break; case '\r':
case '\'': [destStr appendString:@"\\\'"]; break; [destStr appendString:@"\\r"];
case '\\': [destStr appendString:@"\\\\"]; break; break;
case '\t':
[destStr appendString:@"\\t"];
break;
case '\"':
[destStr appendString:@"\\\""];
break;
case '\'':
[destStr appendString:@"\\\'"];
break;
case '\\':
[destStr appendString:@"\\\\"];
break;
default: default:
if (isprint(*src)) { if (isprint(*src)) {
[destStr appendFormat:@"%c", *src]; [destStr appendFormat:@"%c", *src];
@ -1605,31 +1583,29 @@ static void AppendBufferAsString(NSData *buffer, NSMutableString *destStr) {
[destStr appendString:@"\""]; [destStr appendString:@"\""];
} }
static void AppendTextFormatForMapMessageField( static void AppendTextFormatForMapMessageField(id map, GPBFieldDescriptor *field,
id map, GPBFieldDescriptor *field, NSMutableString *toStr, NSMutableString *toStr, NSString *lineIndent,
NSString *lineIndent, NSString *fieldName, NSString *lineEnding) { NSString *fieldName, NSString *lineEnding) {
GPBDataType keyDataType = field.mapKeyDataType; GPBDataType keyDataType = field.mapKeyDataType;
GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType valueDataType = GPBGetFieldDataType(field);
BOOL isMessageValue = GPBDataTypeIsMessage(valueDataType); BOOL isMessageValue = GPBDataTypeIsMessage(valueDataType);
NSString *msgStartFirst = NSString *msgStartFirst =
[NSString stringWithFormat:@"%@%@ {%@\n", lineIndent, fieldName, lineEnding]; [NSString stringWithFormat:@"%@%@ {%@\n", lineIndent, fieldName, lineEnding];
NSString *msgStart = NSString *msgStart = [NSString stringWithFormat:@"%@%@ {\n", lineIndent, fieldName];
[NSString stringWithFormat:@"%@%@ {\n", lineIndent, fieldName];
NSString *msgEnd = [NSString stringWithFormat:@"%@}\n", lineIndent]; NSString *msgEnd = [NSString stringWithFormat:@"%@}\n", lineIndent];
NSString *keyLine = [NSString stringWithFormat:@"%@ key: ", lineIndent]; NSString *keyLine = [NSString stringWithFormat:@"%@ key: ", lineIndent];
NSString *valueLine = [NSString stringWithFormat:@"%@ value%s ", lineIndent, NSString *valueLine =
(isMessageValue ? "" : ":")]; [NSString stringWithFormat:@"%@ value%s ", lineIndent, (isMessageValue ? "" : ":")];
__block BOOL isFirst = YES; __block BOOL isFirst = YES;
if ((keyDataType == GPBDataTypeString) && if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) {
GPBDataTypeIsObject(valueDataType)) {
// map is an NSDictionary. // map is an NSDictionary.
NSDictionary *dict = map; NSDictionary *dict = map;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) { [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
#pragma unused(stop) #pragma unused(stop)
[toStr appendString:(isFirst ? msgStartFirst : msgStart)]; [toStr appendString:(isFirst ? msgStartFirst : msgStart)];
isFirst = NO; isFirst = NO;
@ -1729,10 +1705,8 @@ static void AppendTextFormatForMapMessageField(
} }
} }
static void AppendTextFormatForMessageField(GPBMessage *message, static void AppendTextFormatForMessageField(GPBMessage *message, GPBFieldDescriptor *field,
GPBFieldDescriptor *field, NSMutableString *toStr, NSString *lineIndent) {
NSMutableString *toStr,
NSString *lineIndent) {
id arrayOrMap; id arrayOrMap;
NSUInteger count; NSUInteger count;
GPBFieldType fieldType = field.fieldType; GPBFieldType fieldType = field.fieldType;
@ -1780,8 +1754,7 @@ static void AppendTextFormatForMessageField(GPBMessage *message,
} }
if (fieldType == GPBFieldTypeMap) { if (fieldType == GPBFieldTypeMap) {
AppendTextFormatForMapMessageField(arrayOrMap, field, toStr, lineIndent, AppendTextFormatForMapMessageField(arrayOrMap, field, toStr, lineIndent, fieldName, lineEnding);
fieldName, lineEnding);
return; return;
} }
@ -1792,8 +1765,7 @@ static void AppendTextFormatForMessageField(GPBMessage *message,
BOOL isMessageField = GPBDataTypeIsMessage(fieldDataType); BOOL isMessageField = GPBDataTypeIsMessage(fieldDataType);
for (NSUInteger j = 0; j < count; ++j) { for (NSUInteger j = 0; j < count; ++j) {
// Start the line. // Start the line.
[toStr appendFormat:@"%@%@%s ", lineIndent, fieldName, [toStr appendFormat:@"%@%@%s ", lineIndent, fieldName, (isMessageField ? "" : ":")];
(isMessageField ? "" : ":")];
// The value. // The value.
switch (fieldDataType) { switch (fieldDataType) {
@ -1859,8 +1831,7 @@ static void AppendTextFormatForMessageField(GPBMessage *message,
case GPBDataTypeGroup: case GPBDataTypeGroup:
case GPBDataTypeMessage: { case GPBDataTypeMessage: {
GPBMessage *v = GPBMessage *v = (isRepeated ? [(NSArray *)array objectAtIndex:j]
(isRepeated ? [(NSArray *)array objectAtIndex:j]
: GPBGetObjectIvarWithField(message, field)); : GPBGetObjectIvarWithField(message, field));
[toStr appendFormat:@"{%@\n", lineEnding]; [toStr appendFormat:@"{%@\n", lineEnding];
NSString *subIndent = [lineIndent stringByAppendingString:@" "]; NSString *subIndent = [lineIndent stringByAppendingString:@" "];
@ -1878,11 +1849,9 @@ static void AppendTextFormatForMessageField(GPBMessage *message,
} // for(count) } // for(count)
} }
static void AppendTextFormatForMessageExtensionRange(GPBMessage *message, static void AppendTextFormatForMessageExtensionRange(GPBMessage *message, NSArray *activeExtensions,
NSArray *activeExtensions,
GPBExtensionRange range, GPBExtensionRange range,
NSMutableString *toStr, NSMutableString *toStr, NSString *lineIndent) {
NSString *lineIndent) {
uint32_t start = range.start; uint32_t start = range.start;
uint32_t end = range.end; uint32_t end = range.end;
for (GPBExtensionDescriptor *extension in activeExtensions) { for (GPBExtensionDescriptor *extension in activeExtensions) {
@ -1951,8 +1920,7 @@ static void AppendTextFormatForMessageExtensionRange(GPBMessage *message,
#undef FIELD_CASE #undef FIELD_CASE
case GPBDataTypeBool: case GPBDataTypeBool:
[toStr appendString:([(NSNumber *)curValue boolValue] ? @"true" [toStr appendString:([(NSNumber *)curValue boolValue] ? @"true" : @"false")];
: @"false")];
break; break;
case GPBDataTypeString: case GPBDataTypeString:
@ -1983,32 +1951,29 @@ static void AppendTextFormatForMessageExtensionRange(GPBMessage *message,
} // for..in(activeExtensions) } // for..in(activeExtensions)
} }
static void AppendTextFormatForMessage(GPBMessage *message, static void AppendTextFormatForMessage(GPBMessage *message, NSMutableString *toStr,
NSMutableString *toStr,
NSString *lineIndent) { NSString *lineIndent) {
GPBDescriptor *descriptor = [message descriptor]; GPBDescriptor *descriptor = [message descriptor];
NSArray *fieldsArray = descriptor->fields_; NSArray *fieldsArray = descriptor->fields_;
NSUInteger fieldCount = fieldsArray.count; NSUInteger fieldCount = fieldsArray.count;
const GPBExtensionRange *extensionRanges = descriptor.extensionRanges; const GPBExtensionRange *extensionRanges = descriptor.extensionRanges;
NSUInteger extensionRangesCount = descriptor.extensionRangesCount; NSUInteger extensionRangesCount = descriptor.extensionRangesCount;
NSArray *activeExtensions = [[message extensionsCurrentlySet] NSArray *activeExtensions =
sortedArrayUsingSelector:@selector(compareByFieldNumber:)]; [[message extensionsCurrentlySet] sortedArrayUsingSelector:@selector(compareByFieldNumber:)];
for (NSUInteger i = 0, j = 0; i < fieldCount || j < extensionRangesCount;) { for (NSUInteger i = 0, j = 0; i < fieldCount || j < extensionRangesCount;) {
if (i == fieldCount) { if (i == fieldCount) {
AppendTextFormatForMessageExtensionRange( AppendTextFormatForMessageExtensionRange(message, activeExtensions, extensionRanges[j++],
message, activeExtensions, extensionRanges[j++], toStr, lineIndent); toStr, lineIndent);
} else if (j == extensionRangesCount || } else if (j == extensionRangesCount ||
GPBFieldNumber(fieldsArray[i]) < extensionRanges[j].start) { GPBFieldNumber(fieldsArray[i]) < extensionRanges[j].start) {
AppendTextFormatForMessageField(message, fieldsArray[i++], toStr, AppendTextFormatForMessageField(message, fieldsArray[i++], toStr, lineIndent);
lineIndent);
} else { } else {
AppendTextFormatForMessageExtensionRange( AppendTextFormatForMessageExtensionRange(message, activeExtensions, extensionRanges[j++],
message, activeExtensions, extensionRanges[j++], toStr, lineIndent); toStr, lineIndent);
} }
} }
NSString *unknownFieldsStr = NSString *unknownFieldsStr = GPBTextFormatForUnknownFieldSet(message.unknownFields, lineIndent);
GPBTextFormatForUnknownFieldSet(message.unknownFields, lineIndent);
if ([unknownFieldsStr length] > 0) { if ([unknownFieldsStr length] > 0) {
[toStr appendFormat:@"%@# --- Unknown fields ---\n", lineIndent]; [toStr appendFormat:@"%@# --- Unknown fields ---\n", lineIndent];
[toStr appendString:unknownFieldsStr]; [toStr appendString:unknownFieldsStr];
@ -2024,8 +1989,7 @@ NSString *GPBTextFormatForMessage(GPBMessage *message, NSString *lineIndent) {
return buildString; return buildString;
} }
NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *unknownSet, NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *unknownSet, NSString *lineIndent) {
NSString *lineIndent) {
if (unknownSet == nil) return @""; if (unknownSet == nil) return @"";
if (lineIndent == nil) lineIndent = @""; if (lineIndent == nil) lineIndent = @"";
@ -2034,11 +1998,9 @@ NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *unknownSet,
int32_t fieldNumber = [field number]; int32_t fieldNumber = [field number];
#define PRINT_LOOP(PROPNAME, CTYPE, FORMAT) \ #define PRINT_LOOP(PROPNAME, CTYPE, FORMAT) \
[field.PROPNAME \ [field.PROPNAME enumerateValuesWithBlock:^(CTYPE value, NSUInteger idx, BOOL * stop) { \
enumerateValuesWithBlock:^(CTYPE value, NSUInteger idx, BOOL * stop) { \
_Pragma("unused(idx, stop)"); \ _Pragma("unused(idx, stop)"); \
[result \ [result appendFormat:@"%@%d: " FORMAT "\n", lineIndent, fieldNumber, value]; \
appendFormat:@"%@%d: " FORMAT "\n", lineIndent, fieldNumber, value]; \
}]; }];
PRINT_LOOP(varintList, uint64_t, "%llu"); PRINT_LOOP(varintList, uint64_t, "%llu");
@ -2058,8 +2020,7 @@ NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *unknownSet,
for (GPBUnknownFieldSet *subUnknownSet in field.groupList) { for (GPBUnknownFieldSet *subUnknownSet in field.groupList) {
[result appendFormat:@"%@%d: {\n", lineIndent, fieldNumber]; [result appendFormat:@"%@%d: {\n", lineIndent, fieldNumber];
NSString *subIndent = [lineIndent stringByAppendingString:@" "]; NSString *subIndent = [lineIndent stringByAppendingString:@" "];
NSString *subUnknownSetStr = NSString *subUnknownSetStr = GPBTextFormatForUnknownFieldSet(subUnknownSet, subIndent);
GPBTextFormatForUnknownFieldSet(subUnknownSet, subIndent);
[result appendString:subUnknownSetStr]; [result appendString:subUnknownSetStr];
[result appendFormat:@"%@}\n", lineIndent]; [result appendFormat:@"%@}\n", lineIndent];
} }
@ -2102,8 +2063,7 @@ static int32_t ReadRawVarint32FromData(const uint8_t **data) {
return result; return result;
} }
} }
[NSException raise:NSParseErrorException [NSException raise:NSParseErrorException format:@"Unable to read varint32"];
format:@"Unable to read varint32"];
} }
} }
} }
@ -2111,8 +2071,7 @@ static int32_t ReadRawVarint32FromData(const uint8_t **data) {
return result; return result;
} }
NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key, NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key, NSString *inputStr) {
NSString *inputStr) {
// decodData form: // decodData form:
// varint32: num entries // varint32: num entries
// for each entry: // for each entry:
@ -2170,8 +2129,7 @@ NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key,
return result; return result;
} }
NSMutableString *result = NSMutableString *result = [NSMutableString stringWithCapacity:[inputStr length]];
[NSMutableString stringWithCapacity:[inputStr length]];
const uint8_t kAddUnderscore = 0b10000000; const uint8_t kAddUnderscore = 0b10000000;
const uint8_t kOpMask = 0b01100000; const uint8_t kOpMask = 0b01100000;
@ -2221,26 +2179,23 @@ NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key,
#pragma mark Legacy methods old generated code calls #pragma mark Legacy methods old generated code calls
// Shim from the older generated code into the runtime. // Shim from the older generated code into the runtime.
void GPBSetInt32IvarWithFieldInternal(GPBMessage *self, void GPBSetInt32IvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, int32_t value,
GPBFieldDescriptor *field,
int32_t value,
GPBFileSyntax syntax) { GPBFileSyntax syntax) {
#pragma unused(syntax) #pragma unused(syntax)
GPBSetMessageInt32Field(self, field, value); GPBSetMessageInt32Field(self, field, value);
} }
void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof, void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof, int32_t oneofHasIndex,
int32_t oneofHasIndex, uint32_t fieldNumberNotToClear) { uint32_t fieldNumberNotToClear) {
#pragma unused(fieldNumberNotToClear) #pragma unused(fieldNumberNotToClear)
#if defined(DEBUG) && DEBUG #if defined(DEBUG) && DEBUG
NSCAssert([[self descriptor] oneofWithName:oneof.name] == oneof, NSCAssert([[self descriptor] oneofWithName:oneof.name] == oneof,
@"OneofDescriptor %@ doesn't appear to be for %@ messages.", @"OneofDescriptor %@ doesn't appear to be for %@ messages.", oneof.name, [self class]);
oneof.name, [self class]);
GPBFieldDescriptor *firstField __unused = oneof->fields_[0]; GPBFieldDescriptor *firstField __unused = oneof->fields_[0];
NSCAssert(firstField->description_->hasIndex == oneofHasIndex, NSCAssert(firstField->description_->hasIndex == oneofHasIndex,
@"Internal error, oneofHasIndex (%d) doesn't match (%d).", @"Internal error, oneofHasIndex (%d) doesn't match (%d).",
firstField->description_->hasIndex, oneofHasIndex); firstField->description_->hasIndex, oneofHasIndex);
#endif #endif
GPBMaybeClearOneofPrivate(self, oneof, oneofHasIndex, 0); GPBMaybeClearOneofPrivate(self, oneof, oneofHasIndex, 0);
} }

@ -36,18 +36,15 @@
#import "GPBUtilities_PackagePrivate.h" #import "GPBUtilities_PackagePrivate.h"
NSString *const GPBWellKnownTypesErrorDomain = NSString *const GPBWellKnownTypesErrorDomain = GPBNSStringifySymbol(GPBWellKnownTypesErrorDomain);
GPBNSStringifySymbol(GPBWellKnownTypesErrorDomain);
static NSString *kTypePrefixGoogleApisCom = @"type.googleapis.com/"; static NSString *kTypePrefixGoogleApisCom = @"type.googleapis.com/";
static NSTimeInterval TimeIntervalFromSecondsAndNanos(int64_t seconds, static NSTimeInterval TimeIntervalFromSecondsAndNanos(int64_t seconds, int32_t nanos) {
int32_t nanos) {
return seconds + (NSTimeInterval)nanos / 1e9; return seconds + (NSTimeInterval)nanos / 1e9;
} }
static int32_t SecondsAndNanosFromTimeInterval(NSTimeInterval time, static int32_t SecondsAndNanosFromTimeInterval(NSTimeInterval time, int64_t *outSeconds,
int64_t *outSeconds,
BOOL nanosMustBePositive) { BOOL nanosMustBePositive) {
NSTimeInterval seconds; NSTimeInterval seconds;
NSTimeInterval nanos = modf(time, &seconds); NSTimeInterval nanos = modf(time, &seconds);
@ -79,8 +76,7 @@ static NSString *BuildTypeURL(NSString *typeURLPrefix, NSString *fullName) {
static NSString *ParseTypeFromURL(NSString *typeURLString) { static NSString *ParseTypeFromURL(NSString *typeURLString) {
NSRange range = [typeURLString rangeOfString:@"/" options:NSBackwardsSearch]; NSRange range = [typeURLString rangeOfString:@"/" options:NSBackwardsSearch];
if ((range.location == NSNotFound) || if ((range.location == NSNotFound) || (NSMaxRange(range) == typeURLString.length)) {
(NSMaxRange(range) == typeURLString.length)) {
return nil; return nil;
} }
NSString *result = [typeURLString substringFromIndex:range.location + 1]; NSString *result = [typeURLString substringFromIndex:range.location + 1];
@ -98,8 +94,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 { - (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 {
if ((self = [super init])) { if ((self = [super init])) {
int64_t seconds; int64_t seconds;
int32_t nanos = SecondsAndNanosFromTimeInterval( int32_t nanos = SecondsAndNanosFromTimeInterval(timeIntervalSince1970, &seconds, YES);
timeIntervalSince1970, &seconds, YES);
self.seconds = seconds; self.seconds = seconds;
self.nanos = nanos; self.nanos = nanos;
} }
@ -120,8 +115,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
- (void)setTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 { - (void)setTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 {
int64_t seconds; int64_t seconds;
int32_t nanos = int32_t nanos = SecondsAndNanosFromTimeInterval(timeIntervalSince1970, &seconds, YES);
SecondsAndNanosFromTimeInterval(timeIntervalSince1970, &seconds, YES);
self.seconds = seconds; self.seconds = seconds;
self.nanos = nanos; self.nanos = nanos;
} }
@ -135,8 +129,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
- (instancetype)initWithTimeInterval:(NSTimeInterval)timeInterval { - (instancetype)initWithTimeInterval:(NSTimeInterval)timeInterval {
if ((self = [super init])) { if ((self = [super init])) {
int64_t seconds; int64_t seconds;
int32_t nanos = SecondsAndNanosFromTimeInterval( int32_t nanos = SecondsAndNanosFromTimeInterval(timeInterval, &seconds, NO);
timeInterval, &seconds, NO);
self.seconds = seconds; self.seconds = seconds;
self.nanos = nanos; self.nanos = nanos;
} }
@ -153,8 +146,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
- (void)setTimeInterval:(NSTimeInterval)timeInterval { - (void)setTimeInterval:(NSTimeInterval)timeInterval {
int64_t seconds; int64_t seconds;
int32_t nanos = int32_t nanos = SecondsAndNanosFromTimeInterval(timeInterval, &seconds, NO);
SecondsAndNanosFromTimeInterval(timeInterval, &seconds, NO);
self.seconds = seconds; self.seconds = seconds;
self.nanos = nanos; self.nanos = nanos;
} }
@ -173,26 +165,19 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
@implementation GPBAny (GBPWellKnownTypes) @implementation GPBAny (GBPWellKnownTypes)
+ (instancetype)anyWithMessage:(GPBMessage *)message + (instancetype)anyWithMessage:(GPBMessage *)message error:(NSError **)errorPtr {
error:(NSError **)errorPtr { return [self anyWithMessage:message typeURLPrefix:kTypePrefixGoogleApisCom error:errorPtr];
return [self anyWithMessage:message
typeURLPrefix:kTypePrefixGoogleApisCom
error:errorPtr];
} }
+ (instancetype)anyWithMessage:(GPBMessage *)message + (instancetype)anyWithMessage:(GPBMessage *)message
typeURLPrefix:(NSString *)typeURLPrefix typeURLPrefix:(NSString *)typeURLPrefix
error:(NSError **)errorPtr { error:(NSError **)errorPtr {
return [[[self alloc] initWithMessage:message return [[[self alloc] initWithMessage:message typeURLPrefix:typeURLPrefix
typeURLPrefix:typeURLPrefix
error:errorPtr] autorelease]; error:errorPtr] autorelease];
} }
- (instancetype)initWithMessage:(GPBMessage *)message - (instancetype)initWithMessage:(GPBMessage *)message error:(NSError **)errorPtr {
error:(NSError **)errorPtr { return [self initWithMessage:message typeURLPrefix:kTypePrefixGoogleApisCom error:errorPtr];
return [self initWithMessage:message
typeURLPrefix:kTypePrefixGoogleApisCom
error:errorPtr];
} }
- (instancetype)initWithMessage:(GPBMessage *)message - (instancetype)initWithMessage:(GPBMessage *)message
@ -200,9 +185,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
error:(NSError **)errorPtr { error:(NSError **)errorPtr {
self = [self init]; self = [self init];
if (self) { if (self) {
if (![self packWithMessage:message if (![self packWithMessage:message typeURLPrefix:typeURLPrefix error:errorPtr]) {
typeURLPrefix:typeURLPrefix
error:errorPtr]) {
[self release]; [self release];
self = nil; self = nil;
} }
@ -210,11 +193,8 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
return self; return self;
} }
- (BOOL)packWithMessage:(GPBMessage *)message - (BOOL)packWithMessage:(GPBMessage *)message error:(NSError **)errorPtr {
error:(NSError **)errorPtr { return [self packWithMessage:message typeURLPrefix:kTypePrefixGoogleApisCom error:errorPtr];
return [self packWithMessage:message
typeURLPrefix:kTypePrefixGoogleApisCom
error:errorPtr];
} }
- (BOOL)packWithMessage:(GPBMessage *)message - (BOOL)packWithMessage:(GPBMessage *)message
@ -223,8 +203,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
NSString *fullName = [message descriptor].fullName; NSString *fullName = [message descriptor].fullName;
if (fullName.length == 0) { if (fullName.length == 0) {
if (errorPtr) { if (errorPtr) {
*errorPtr = *errorPtr = [NSError errorWithDomain:GPBWellKnownTypesErrorDomain
[NSError errorWithDomain:GPBWellKnownTypesErrorDomain
code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL
userInfo:nil]; userInfo:nil];
} }
@ -238,13 +217,11 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
return YES; return YES;
} }
- (GPBMessage *)unpackMessageClass:(Class)messageClass - (GPBMessage *)unpackMessageClass:(Class)messageClass error:(NSError **)errorPtr {
error:(NSError **)errorPtr {
NSString *fullName = [messageClass descriptor].fullName; NSString *fullName = [messageClass descriptor].fullName;
if (fullName.length == 0) { if (fullName.length == 0) {
if (errorPtr) { if (errorPtr) {
*errorPtr = *errorPtr = [NSError errorWithDomain:GPBWellKnownTypesErrorDomain
[NSError errorWithDomain:GPBWellKnownTypesErrorDomain
code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL
userInfo:nil]; userInfo:nil];
} }
@ -254,8 +231,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
NSString *expectedFullName = ParseTypeFromURL(self.typeURL); NSString *expectedFullName = ParseTypeFromURL(self.typeURL);
if ((expectedFullName == nil) || ![expectedFullName isEqual:fullName]) { if ((expectedFullName == nil) || ![expectedFullName isEqual:fullName]) {
if (errorPtr) { if (errorPtr) {
*errorPtr = *errorPtr = [NSError errorWithDomain:GPBWellKnownTypesErrorDomain
[NSError errorWithDomain:GPBWellKnownTypesErrorDomain
code:GPBWellKnownTypesErrorCodeTypeURLMismatch code:GPBWellKnownTypesErrorCodeTypeURLMismatch
userInfo:nil]; userInfo:nil];
} }
@ -265,8 +241,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) {
// Any is proto3, which means no extensions, so this assumes anything put // Any is proto3, which means no extensions, so this assumes anything put
// within an any also won't need extensions. A second helper could be added // within an any also won't need extensions. A second helper could be added
// if needed. // if needed.
return [messageClass parseFromData:self.value return [messageClass parseFromData:self.value error:errorPtr];
error:errorPtr];
} }
@end @end

Loading…
Cancel
Save