diff options
author | TeBoring <teboring@google.com> | 2015-07-15 16:16:08 -0700 |
---|---|---|
committer | TeBoring <teboring@google.com> | 2015-07-21 15:45:02 -0700 |
commit | 7366efd81e7f36108aa35e66fca61da8a65762c2 (patch) | |
tree | c3b05157928bf27405115aea5835055066cb7022 /objectivec/GPBWellKnownTypes.m | |
parent | fde6e89f99eda04a4f1b8677bcea07e6c2040405 (diff) | |
download | protobuf-7366efd81e7f36108aa35e66fca61da8a65762c2.tar.gz protobuf-7366efd81e7f36108aa35e66fca61da8a65762c2.tar.bz2 protobuf-7366efd81e7f36108aa35e66fca61da8a65762c2.zip |
Add packFrom, unpackTo and is in google.protobuf.Any.
The previous two methods make it easy to transform between any and normal message.
unPackeTo will throw error if the type url in any doesn't match the type of the message to be transformed to.
is checks any's type url matches the give GPBMessage type.
Diffstat (limited to 'objectivec/GPBWellKnownTypes.m')
-rw-r--r-- | objectivec/GPBWellKnownTypes.m | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/objectivec/GPBWellKnownTypes.m b/objectivec/GPBWellKnownTypes.m index fe02f5de..b48f8a53 100644 --- a/objectivec/GPBWellKnownTypes.m +++ b/objectivec/GPBWellKnownTypes.m @@ -115,3 +115,52 @@ static int32_t SecondsAndNanosFromTimeIntervalSince1970(NSTimeInterval time, } @end + +NSString *const GPBTypeGoogleApisComPrefix = @"type.googleapis.com/"; + +@implementation GPBAny (GBPWellKnownTypes) + +- (instancetype)initWithMessage:(GPBMessage*)message { + self = [super init]; + if (self) { + [self setMessage:message]; + } + return self; +} + +- (NSString*)typeName { + NSAssert([self.typeURL hasPrefix:GPBTypeGoogleApisComPrefix], + @"Invalid any type url (%@).", self.typeURL); + if (![self.typeURL hasPrefix:GPBTypeGoogleApisComPrefix]) { + return nil; + } + return [self.typeURL substringFromIndex:[GPBTypeGoogleApisComPrefix length]]; +} + +- (void)setMessage:(GPBMessage*)message { + self.typeURL = [GPBTypeGoogleApisComPrefix stringByAppendingString:message.descriptor.name]; + self.value = message.data; +} + +- (GPBMessage*)messageOfClass:(Class)messageClass { + if ([self wrapsMessageOfClass:messageClass]) { + GPBMessage* message = [messageClass message]; + [message mergeFromData:self.value extensionRegistry:nil]; + return message; + } else { + return nil; + } +} + +- (BOOL)wrapsMessageOfClass:(Class)messageClass { + NSAssert([messageClass isSubclassofClass:[GPBMessage class]], + @"Given class (%@) is not a subclass of GPBMessage", + [messageClass name]); + if (![messageClass isSubclassOfClass:[GPBMessage class]]) { + return NO; + } + return [[self typeName] isEqualToString:messageClass.descriptor.name]; +} + +@end + |