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];
}
+ (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func
rawValue:(int32_t)value {
return [[[self alloc] initWithValidationFunction:func
rawValues:&value
count:1] autorelease];
+ (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func rawValue:(int32_t)value {
return [[[self alloc] initWithValidationFunction:func rawValues:&value count:1] autorelease];
}
+ (instancetype)arrayWithValueArray:(GPBEnumArray *)array {
return [[(GPBEnumArray*)[self alloc] initWithValueArray:array] autorelease];
return [[(GPBEnumArray *)[self alloc] initWithValueArray:array] autorelease];
}
+ (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func
capacity:(NSUInteger)count {
+ (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)count {
return [[[self alloc] initWithValidationFunction:func capacity:count] autorelease];
}
@ -2091,7 +2087,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
}
- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
rawValues:(const int32_t[])values
count:(NSUInteger)count {
self = [self initWithValidationFunction:func];
if (self) {
@ -2103,17 +2099,16 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
_count = count;
} else {
[self release];
[NSException raise:NSMallocException
format:@"Failed to allocate %lu bytes",
(unsigned long)(count * sizeof(int32_t))];
[NSException
raise:NSMallocException
format:@"Failed to allocate %lu bytes", (unsigned long)(count * sizeof(int32_t))];
}
}
}
return self;
}
- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func
capacity:(NSUInteger)count {
- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)count {
self = [self initWithValidationFunction:func];
if (self && count) {
[self internalResizeToCapacity:count];
@ -2122,8 +2117,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
}
- (instancetype)copyWithZone:(NSZone *)zone {
return [[GPBEnumArray allocWithZone:zone]
initWithValidationFunction:_validationFunc
return [[GPBEnumArray allocWithZone:zone] initWithValidationFunction:_validationFunc
rawValues:_values
count:_count];
}
@ -2197,7 +2191,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
// clang-format on
- (int32_t)valueAtIndex:(NSUInteger)index {
// clang-format off
// clang-format off
//%PDDM-EXPAND VALIDATE_RANGE(index, _count)
// 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];
}
//%PDDM-EXPAND-END VALIDATE_RANGE(index, _count)
// clang-format on
// clang-format on
int32_t result = _values[index];
if (!_validationFunc(result)) {
result = kGPBUnrecognizedEnumeratorValue;
@ -2216,7 +2210,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
}
- (int32_t)rawValueAtIndex:(NSUInteger)index {
// clang-format off
// clang-format off
//%PDDM-EXPAND VALIDATE_RANGE(index, _count)
// 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];
}
//%PDDM-EXPAND-END VALIDATE_RANGE(index, _count)
// clang-format on
// clang-format on
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];
}
- (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).
BOOL stop = NO;
GPBEnumValidationFunc func = _validationFunc;
@ -2472,8 +2468,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
}
- (void)dealloc {
NSAssert(!_autocreator,
@"%@: Autocreator must be cleared before release, autocreator: %@",
NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@",
[self class], _autocreator);
[_array release];
[super dealloc];

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

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

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

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

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

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

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

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

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

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

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

Loading…
Cancel
Save