FLEXRuntimeUtility.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. //
  2. // FLEXRuntimeUtility.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 6/8/14.
  6. // Copyright (c) 2014 Flipboard. All rights reserved.
  7. //
  8. #import "FLEXRuntimeUtility.h"
  9. // See https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html#//apple_ref/doc/uid/TP40008048-CH101-SW6
  10. static NSString *const kFLEXUtilityAttributeTypeEncoding = @"T";
  11. static NSString *const kFLEXUtilityAttributeBackingIvar = @"V";
  12. static NSString *const kFLEXUtilityAttributeReadOnly = @"R";
  13. static NSString *const kFLEXUtilityAttributeCopy = @"C";
  14. static NSString *const kFLEXUtilityAttributeRetain = @"&";
  15. static NSString *const kFLEXUtilityAttributeNonAtomic = @"N";
  16. static NSString *const kFLEXUtilityAttributeCustomGetter = @"G";
  17. static NSString *const kFLEXUtilityAttributeCustomSetter = @"S";
  18. static NSString *const kFLEXUtilityAttributeDynamic = @"D";
  19. static NSString *const kFLEXUtilityAttributeWeak = @"W";
  20. static NSString *const kFLEXUtilityAttributeGarbageCollectable = @"P";
  21. static NSString *const kFLEXUtilityAttributeOldStyleTypeEncoding = @"t";
  22. static NSString *const FLEXRuntimeUtilityErrorDomain = @"FLEXRuntimeUtilityErrorDomain";
  23. typedef NS_ENUM(NSInteger, FLEXRuntimeUtilityErrorCode) {
  24. FLEXRuntimeUtilityErrorCodeDoesNotRecognizeSelector = 0,
  25. FLEXRuntimeUtilityErrorCodeInvocationFailed = 1
  26. };
  27. // Arguments 0 and 1 are self and _cmd always
  28. const unsigned int kFLEXNumberOfImplicitArgs = 2;
  29. @implementation FLEXRuntimeUtility
  30. #pragma mark - Property Helpers (Public)
  31. + (NSString *)prettyNameForProperty:(objc_property_t)property
  32. {
  33. NSString *name = @(property_getName(property));
  34. NSString *encoding = [self typeEncodingForProperty:property];
  35. NSString *readableType = [self readableTypeForEncoding:encoding];
  36. return [self appendName:name toType:readableType];
  37. }
  38. + (NSString *)typeEncodingForProperty:(objc_property_t)property
  39. {
  40. NSDictionary *attributesDictionary = [self attributesDictionaryForProperty:property];
  41. return [attributesDictionary objectForKey:kFLEXUtilityAttributeTypeEncoding];
  42. }
  43. + (BOOL)isReadonlyProperty:(objc_property_t)property
  44. {
  45. return [[self attributesDictionaryForProperty:property] objectForKey:kFLEXUtilityAttributeReadOnly] != nil;
  46. }
  47. + (SEL)setterSelectorForProperty:(objc_property_t)property
  48. {
  49. SEL setterSelector = NULL;
  50. NSString *setterSelectorString = [[self attributesDictionaryForProperty:property] objectForKey:kFLEXUtilityAttributeCustomSetter];
  51. if (!setterSelectorString) {
  52. NSString *propertyName = @(property_getName(property));
  53. setterSelectorString = [NSString stringWithFormat:@"set%@%@:", [[propertyName substringToIndex:1] uppercaseString], [propertyName substringFromIndex:1]];
  54. }
  55. if (setterSelectorString) {
  56. setterSelector = NSSelectorFromString(setterSelectorString);
  57. }
  58. return setterSelector;
  59. }
  60. + (NSString *)fullDescriptionForProperty:(objc_property_t)property
  61. {
  62. NSDictionary *attributesDictionary = [self attributesDictionaryForProperty:property];
  63. NSMutableArray *attributesStrings = [NSMutableArray array];
  64. // Atomicity
  65. if ([attributesDictionary objectForKey:kFLEXUtilityAttributeNonAtomic]) {
  66. [attributesStrings addObject:@"nonatomic"];
  67. } else {
  68. [attributesStrings addObject:@"atomic"];
  69. }
  70. // Storage
  71. if ([attributesDictionary objectForKey:kFLEXUtilityAttributeRetain]) {
  72. [attributesStrings addObject:@"strong"];
  73. } else if ([attributesDictionary objectForKey:kFLEXUtilityAttributeCopy]) {
  74. [attributesStrings addObject:@"copy"];
  75. } else if ([attributesDictionary objectForKey:kFLEXUtilityAttributeWeak]) {
  76. [attributesStrings addObject:@"weak"];
  77. } else {
  78. [attributesStrings addObject:@"assign"];
  79. }
  80. // Mutability
  81. if ([attributesDictionary objectForKey:kFLEXUtilityAttributeReadOnly]) {
  82. [attributesStrings addObject:@"readonly"];
  83. } else {
  84. [attributesStrings addObject:@"readwrite"];
  85. }
  86. // Custom getter/setter
  87. NSString *customGetter = [attributesDictionary objectForKey:kFLEXUtilityAttributeCustomGetter];
  88. NSString *customSetter = [attributesDictionary objectForKey:kFLEXUtilityAttributeCustomSetter];
  89. if (customGetter) {
  90. [attributesStrings addObject:[NSString stringWithFormat:@"getter=%@", customGetter]];
  91. }
  92. if (customSetter) {
  93. [attributesStrings addObject:[NSString stringWithFormat:@"setter=%@", customSetter]];
  94. }
  95. NSString *attributesString = [attributesStrings componentsJoinedByString:@", "];
  96. NSString *shortName = [self prettyNameForProperty:property];
  97. return [NSString stringWithFormat:@"@property (%@) %@", attributesString, shortName];
  98. }
  99. + (id)valueForProperty:(objc_property_t)property onObject:(id)object
  100. {
  101. NSString *customGetterString = nil;
  102. char *customGetterName = property_copyAttributeValue(property, "G");
  103. if (customGetterName) {
  104. customGetterString = @(customGetterName);
  105. free(customGetterName);
  106. }
  107. SEL getterSelector;
  108. if ([customGetterString length] > 0) {
  109. getterSelector = NSSelectorFromString(customGetterString);
  110. } else {
  111. NSString *propertyName = @(property_getName(property));
  112. getterSelector = NSSelectorFromString(propertyName);
  113. }
  114. return [self performSelector:getterSelector onObject:object withArguments:nil error:NULL];
  115. }
  116. + (NSString *)descriptionForIvarOrPropertyValue:(id)value
  117. {
  118. NSString *description = nil;
  119. // Special case BOOL for better readability.
  120. if ([value isKindOfClass:[NSValue class]]) {
  121. const char *type = [value objCType];
  122. if (strcmp(type, @encode(BOOL)) == 0) {
  123. BOOL boolValue = NO;
  124. [value getValue:&boolValue];
  125. description = boolValue ? @"YES" : @"NO";
  126. }
  127. }
  128. if (!description) {
  129. // Single line display - replace newlines and tabs with spaces.
  130. description = [[value description] stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
  131. description = [description stringByReplacingOccurrencesOfString:@"\t" withString:@" "];
  132. }
  133. if (!description) {
  134. description = @"nil";
  135. }
  136. return description;
  137. }
  138. #pragma mark - Ivar Helpers (Public)
  139. + (NSString *)prettyNameForIvar:(Ivar)ivar
  140. {
  141. NSString *name = @(ivar_getName(ivar));
  142. NSString *encoding = @(ivar_getTypeEncoding(ivar));
  143. NSString *readableType = [self readableTypeForEncoding:encoding];
  144. return [self appendName:name toType:readableType];
  145. }
  146. + (id)valueForIvar:(Ivar)ivar onObject:(id)object
  147. {
  148. id value = nil;
  149. const char *type = ivar_getTypeEncoding(ivar);
  150. if (type[0] == @encode(id)[0] || type[0] == @encode(Class)[0]) {
  151. value = object_getIvar(object, ivar);
  152. } else {
  153. ptrdiff_t offset = ivar_getOffset(ivar);
  154. void *pointer = (__bridge void *)object + offset;
  155. value = [self valueForPrimitivePointer:pointer objcType:type];
  156. }
  157. return value;
  158. }
  159. + (void)setIvar:(Ivar)ivar onObject:(id)object withInputString:(NSString *)inputString
  160. {
  161. const char *typeEncodingCString = ivar_getTypeEncoding(ivar);
  162. if (typeEncodingCString[0] == '@') {
  163. // Object - use NSJSONSerialization
  164. id ivarValue = [self objectValueFromEditableString:inputString];
  165. object_setIvar(object, ivar, ivarValue);
  166. } else {
  167. // Primitive - try to parse a number or struct from the string based on the type encoding
  168. NSUInteger bufferSize = 0;
  169. NSGetSizeAndAlignment(typeEncodingCString, &bufferSize, NULL);
  170. void *buffer = malloc(bufferSize);
  171. [self getPrimitiveValue:buffer withObjCType:typeEncodingCString fromInputString:inputString];
  172. ptrdiff_t offset = ivar_getOffset(ivar);
  173. void *pointer = (__bridge void *)object + offset;
  174. memcpy(pointer, buffer, bufferSize);
  175. }
  176. }
  177. #pragma mark - Method Helpers (Public)
  178. + (NSString *)prettyNameForMethod:(Method)method isClassMethod:(BOOL)isClassMethod
  179. {
  180. NSString *selectorName = NSStringFromSelector(method_getName(method));
  181. NSString *methodTypeString = isClassMethod ? @"+" : @"-";
  182. char *returnType = method_copyReturnType(method);
  183. NSString *readableReturnType = [self readableTypeForEncoding:@(returnType)];
  184. free(returnType);
  185. NSString *prettyName = [NSString stringWithFormat:@"%@ (%@)", methodTypeString, readableReturnType];
  186. NSArray *components = [self prettyArgumentComponentsForMethod:method];
  187. if ([components count] > 0) {
  188. prettyName = [prettyName stringByAppendingString:[components componentsJoinedByString:@" "]];
  189. } else {
  190. prettyName = [prettyName stringByAppendingString:selectorName];
  191. }
  192. return prettyName;
  193. }
  194. + (NSArray *)prettyArgumentComponentsForMethod:(Method)method
  195. {
  196. NSMutableArray *components = [NSMutableArray array];
  197. NSString *selectorName = NSStringFromSelector(method_getName(method));
  198. NSArray *selectorComponents = [selectorName componentsSeparatedByString:@":"];
  199. unsigned int numberOfArguments = method_getNumberOfArguments(method);
  200. for (unsigned int argIndex = kFLEXNumberOfImplicitArgs; argIndex < numberOfArguments; argIndex++) {
  201. char *argType = method_copyArgumentType(method, argIndex);
  202. NSString *readableArgType = [self readableTypeForEncoding:@(argType)];
  203. free(argType);
  204. NSString *prettyComponent = [NSString stringWithFormat:@"%@:(%@) ", [selectorComponents objectAtIndex:argIndex - kFLEXNumberOfImplicitArgs], readableArgType];
  205. [components addObject:prettyComponent];
  206. }
  207. return components;
  208. }
  209. #pragma mark - Method Calling/Field Editing (Public)
  210. + (id)performSelector:(SEL)selector onObject:(id)object withArguments:(NSArray *)arguments error:(NSError * __autoreleasing *)error
  211. {
  212. // Bail if the object won't respond to this selector.
  213. if (![object respondsToSelector:selector]) {
  214. if (error) {
  215. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"%@ does not respond to the selector %@", object, NSStringFromSelector(selector)]};
  216. *error = [NSError errorWithDomain:FLEXRuntimeUtilityErrorDomain code:FLEXRuntimeUtilityErrorCodeDoesNotRecognizeSelector userInfo:userInfo];
  217. }
  218. return nil;
  219. }
  220. // Build the invocation
  221. NSMethodSignature *methodSignature = [object methodSignatureForSelector:selector];
  222. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
  223. [invocation setSelector:selector];
  224. [invocation setTarget:object];
  225. [invocation retainArguments];
  226. // Always self and _cmd
  227. NSUInteger numberOfArguments = [methodSignature numberOfArguments];
  228. for (NSUInteger argumentIndex = kFLEXNumberOfImplicitArgs; argumentIndex < numberOfArguments; argumentIndex++) {
  229. NSUInteger argumentsArrayIndex = argumentIndex - kFLEXNumberOfImplicitArgs;
  230. NSString *argumentString = [arguments count] > argumentsArrayIndex ? [arguments objectAtIndex:argumentsArrayIndex] : nil;
  231. const char *typeEncodingCString = [methodSignature getArgumentTypeAtIndex:argumentIndex];
  232. if (typeEncodingCString[0] == @encode(id)[0] || typeEncodingCString[0] == @encode(Class)[0]) {
  233. // Object
  234. id argumentObject = [self objectValueFromEditableString:argumentString];
  235. [invocation setArgument:&argumentObject atIndex:argumentIndex];
  236. } else if (strcmp(typeEncodingCString, @encode(const char *)) == 0 || strcmp(typeEncodingCString, @encode(char *)) == 0) {
  237. // C string
  238. const char *argumentCString = [argumentString UTF8String];
  239. [invocation setArgument:&argumentCString atIndex:argumentIndex];
  240. } else {
  241. // Primitive number or struct
  242. NSUInteger bufferSize = 0;
  243. NSGetSizeAndAlignment(typeEncodingCString, &bufferSize, NULL);
  244. void *buffer = malloc(bufferSize);
  245. [self getPrimitiveValue:buffer withObjCType:typeEncodingCString fromInputString:argumentString];
  246. [invocation setArgument:buffer atIndex:argumentIndex];
  247. free(buffer);
  248. }
  249. }
  250. // Try to invoke the invocation but guard against an exception being thrown.
  251. BOOL successfullyInvoked = NO;
  252. @try {
  253. // Some methods are not fit to be called...
  254. // Looking at you -[UIResponder(UITextInputAdditions) _caretRect]
  255. [invocation invoke];
  256. successfullyInvoked = YES;
  257. } @catch (NSException *exception) {
  258. // Bummer...
  259. if (error) {
  260. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Exception thrown while performing selector %@ on object %@", object, NSStringFromSelector(selector)]};
  261. *error = [NSError errorWithDomain:FLEXRuntimeUtilityErrorDomain code:FLEXRuntimeUtilityErrorCodeInvocationFailed userInfo:userInfo];
  262. }
  263. }
  264. // Retreive the return value and box if necessary.
  265. id returnObject = nil;
  266. if (successfullyInvoked) {
  267. const char *returnType = [methodSignature methodReturnType];
  268. if (returnType[0] == @encode(id)[0] || returnType[0] == @encode(Class)[0]) {
  269. __unsafe_unretained id objectReturnedFromMethod = nil;
  270. [invocation getReturnValue:&objectReturnedFromMethod];
  271. returnObject = objectReturnedFromMethod;
  272. } else if (returnType[0] != @encode(void)[0]) {
  273. void *returnValue = malloc([methodSignature methodReturnLength]);
  274. if (returnValue) {
  275. [invocation getReturnValue:returnValue];
  276. returnObject = [self valueForPrimitivePointer:returnValue objcType:returnType];
  277. free(returnValue);
  278. }
  279. }
  280. }
  281. return returnObject;
  282. }
  283. + (NSString *)editiableDescriptionForObject:(id)object
  284. {
  285. NSString *editableDescription = nil;
  286. if ([object isKindOfClass:[NSValue class]]) {
  287. NSValue *value = (NSValue *)object;
  288. const char *typeEncoding = [value objCType];
  289. if (strcmp(typeEncoding, @encode(CGRect)) == 0) {
  290. editableDescription = NSStringFromCGRect([value CGRectValue]);
  291. } else if (strcmp(typeEncoding, @encode(CGSize)) == 0) {
  292. editableDescription = NSStringFromCGSize([value CGSizeValue]);
  293. } else if (strcmp(typeEncoding, @encode(CGPoint)) == 0) {
  294. editableDescription = NSStringFromCGPoint([value CGPointValue]);
  295. } else if (strcmp(typeEncoding, @encode(CGAffineTransform)) == 0) {
  296. editableDescription = NSStringFromCGAffineTransform([value CGAffineTransformValue]);
  297. } else if (strcmp(typeEncoding, @encode(NSRange)) == 0) {
  298. editableDescription = NSStringFromRange([value rangeValue]);
  299. } else if (strcmp(typeEncoding, @encode(UIEdgeInsets)) == 0) {
  300. editableDescription = NSStringFromUIEdgeInsets([value UIEdgeInsetsValue]);
  301. } else if (strcmp(typeEncoding, @encode(UIOffset)) == 0) {
  302. editableDescription = NSStringFromUIOffset([value UIOffsetValue]);
  303. }
  304. }
  305. if (object && !editableDescription) {
  306. // This is a hack to use JSON serialzation for our editable objects.
  307. // NSJSONSerialization doesn't allow writing fragments - the top level object must be an array or dictionary.
  308. // We always wrap the object inside an array and then strip the outter square braces off the final string.
  309. NSArray *wrappedObject = @[object];
  310. if ([NSJSONSerialization isValidJSONObject:wrappedObject]) {
  311. NSString *wrappedDescription = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:wrappedObject options:0 error:NULL] encoding:NSUTF8StringEncoding];
  312. editableDescription = [wrappedDescription substringWithRange:NSMakeRange(1, [wrappedDescription length] - 2)];
  313. }
  314. }
  315. return editableDescription;
  316. }
  317. + (id)objectValueFromEditableString:(NSString *)string
  318. {
  319. id value = nil;
  320. // nil for empty string/whitespace
  321. if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] > 0) {
  322. value = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:NULL];
  323. }
  324. return value;
  325. }
  326. #pragma mark - Internal Helpers
  327. + (NSDictionary *)attributesDictionaryForProperty:(objc_property_t)property
  328. {
  329. NSString *attributes = @(property_getAttributes(property));
  330. // Thanks to MAObjcRuntime for inspiration here.
  331. NSArray *attributePairs = [attributes componentsSeparatedByString:@","];
  332. NSMutableDictionary *attributesDictionary = [NSMutableDictionary dictionaryWithCapacity:[attributePairs count]];
  333. for (NSString *attributePair in attributePairs) {
  334. [attributesDictionary setObject:[attributePair substringFromIndex:1] forKey:[attributePair substringToIndex:1]];
  335. }
  336. return attributesDictionary;
  337. }
  338. + (NSString *)appendName:(NSString *)name toType:(NSString *)type
  339. {
  340. NSString *combined = nil;
  341. if ([type characterAtIndex:[type length] - 1] == '*') {
  342. combined = [type stringByAppendingString:name];
  343. } else {
  344. combined = [type stringByAppendingFormat:@" %@", name];
  345. }
  346. return combined;
  347. }
  348. + (NSString *)readableTypeForEncoding:(NSString *)encodingString
  349. {
  350. // See https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
  351. // class-dump has a much nicer and much more complete implementation for this task, but it is distributed under GPLv2 :/
  352. // See https://github.com/nygard/class-dump/blob/master/Source/CDType.m
  353. // Warning: this method uses multiple middle returns and macros to cut down on boilerplate.
  354. // The use of macros here was inspired by https://www.mikeash.com/pyblog/friday-qa-2013-02-08-lets-build-key-value-coding.html
  355. const char *encodingCString = [encodingString UTF8String];
  356. // Objects
  357. if (encodingCString[0] == '@') {
  358. NSString *class = [encodingString substringFromIndex:1];
  359. class = [class stringByReplacingOccurrencesOfString:@"\"" withString:@""];
  360. if ([class length] == 0) {
  361. class = @"id";
  362. } else {
  363. class = [class stringByAppendingString:@" *"];
  364. }
  365. return class;
  366. }
  367. // C Types
  368. #define TRANSLATE(ctype) \
  369. if (strcmp(encodingCString, @encode(ctype)) == 0) { \
  370. return (NSString *)CFSTR(#ctype); \
  371. }
  372. // Order matters here since some of the cocoa types are typedefed to c types.
  373. // We can't recover the exact mapping, but we choose to prefer the cocoa types.
  374. // This is not an exhaustive list, but it covers the most common types
  375. TRANSLATE(CGRect);
  376. TRANSLATE(CGPoint);
  377. TRANSLATE(CGSize);
  378. TRANSLATE(UIEdgeInsets);
  379. TRANSLATE(UIOffset);
  380. TRANSLATE(NSRange);
  381. TRANSLATE(CGAffineTransform);
  382. TRANSLATE(NSInteger);
  383. TRANSLATE(NSUInteger);
  384. TRANSLATE(CGFloat);
  385. TRANSLATE(BOOL);
  386. TRANSLATE(int);
  387. TRANSLATE(short);
  388. TRANSLATE(long);
  389. TRANSLATE(long long);
  390. TRANSLATE(unsigned char);
  391. TRANSLATE(unsigned int);
  392. TRANSLATE(unsigned short);
  393. TRANSLATE(unsigned long);
  394. TRANSLATE(unsigned long long);
  395. TRANSLATE(float);
  396. TRANSLATE(double);
  397. TRANSLATE(long double);
  398. TRANSLATE(char *);
  399. TRANSLATE(Class);
  400. TRANSLATE(objc_property_t);
  401. TRANSLATE(Ivar);
  402. TRANSLATE(Method);
  403. TRANSLATE(Category);
  404. TRANSLATE(NSZone *);
  405. TRANSLATE(SEL);
  406. TRANSLATE(void);
  407. #undef TRANSLATE
  408. // Qualifier Prefixes
  409. // Do this after the checks above since some of the direct translations (i.e. Method) contain a prefix.
  410. #define RECURSIVE_TRANSLATE(prefix, formatString) \
  411. if (encodingCString[0] == prefix) { \
  412. NSString *recursiveType = [self readableTypeForEncoding:[encodingString substringFromIndex:1]]; \
  413. return [NSString stringWithFormat:formatString, recursiveType]; \
  414. }
  415. // If there's a qualifier prefix on the encoding, translate it and then
  416. // recursively call this method with the rest of the encoding string.
  417. RECURSIVE_TRANSLATE('^', @"%@ *");
  418. RECURSIVE_TRANSLATE('r', @"const %@");
  419. RECURSIVE_TRANSLATE('n', @"in %@");
  420. RECURSIVE_TRANSLATE('N', @"inout %@");
  421. RECURSIVE_TRANSLATE('o', @"out %@");
  422. RECURSIVE_TRANSLATE('O', @"bycopy %@");
  423. RECURSIVE_TRANSLATE('R', @"byref %@");
  424. RECURSIVE_TRANSLATE('V', @"oneway %@");
  425. RECURSIVE_TRANSLATE('b', @"bitfield(%@)");
  426. #undef RECURSIVE_TRANSLATE
  427. // If we couldn't translate, just return the original encoding string
  428. return encodingString;
  429. }
  430. + (NSValue *)valueForPrimitivePointer:(void *)pointer objcType:(const char *)type
  431. {
  432. // CASE marcro inspired by https://www.mikeash.com/pyblog/friday-qa-2013-02-08-lets-build-key-value-coding.html
  433. #define CASE(ctype, selectorpart) \
  434. if(strcmp(type, @encode(ctype)) == 0) { \
  435. return [NSNumber numberWith ## selectorpart: *(ctype *)pointer]; \
  436. }
  437. CASE(BOOL, Bool);
  438. CASE(unsigned char, UnsignedChar);
  439. CASE(short, Short);
  440. CASE(unsigned short, UnsignedShort);
  441. CASE(int, Int);
  442. CASE(unsigned int, UnsignedInt);
  443. CASE(long, Long);
  444. CASE(unsigned long, UnsignedLong);
  445. CASE(long long, LongLong);
  446. CASE(unsigned long long, UnsignedLongLong);
  447. CASE(float, Float);
  448. CASE(double, Double);
  449. #undef CASE
  450. NSValue *value = nil;
  451. @try {
  452. value = [NSValue valueWithBytes:pointer objCType:type];
  453. } @catch (NSException *exception) {
  454. // Certain type encodings are not supported by valueWithBytes:objCType:. Just fail silently if an exception is thrown.
  455. }
  456. return value;
  457. }
  458. + (void)getPrimitiveValue:(void *)value withObjCType:(const char *)typeEncoding fromInputString:(NSString *)inputString
  459. {
  460. if (strcmp(typeEncoding, @encode(CGRect)) == 0) {
  461. *(CGRect *)value = CGRectFromString(inputString);
  462. } else if (strcmp(typeEncoding, @encode(CGSize)) == 0) {
  463. *(CGSize *)value = CGSizeFromString(inputString);
  464. } else if (strcmp(typeEncoding, @encode(CGPoint)) == 0) {
  465. *(CGPoint *)value = CGPointFromString(inputString);
  466. } else if (strcmp(typeEncoding, @encode(CGAffineTransform)) == 0) {
  467. *(CGAffineTransform *)value = CGAffineTransformFromString(inputString);
  468. } else if (strcmp(typeEncoding, @encode(NSRange)) == 0) {
  469. *(NSRange *)value = NSRangeFromString(inputString);
  470. } else if (strcmp(typeEncoding, @encode(UIEdgeInsets)) == 0) {
  471. *(UIEdgeInsets *)value = UIEdgeInsetsFromString(inputString);
  472. } else if (strcmp(typeEncoding, @encode(UIOffset)) == 0) {
  473. *(UIOffset *)value = UIOffsetFromString(inputString);
  474. } else {
  475. NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
  476. [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
  477. NSNumber *number = [formatter numberFromString:inputString];
  478. if (strcmp(typeEncoding, @encode(char)) == 0) {
  479. // Special case - ask for the string's BOOL value if we couldn't parse a number.
  480. // This allows us to take YES/NO/true/false input.
  481. if (number) {
  482. *(char *)value = [number charValue];
  483. } else {
  484. *(char *)value = [inputString boolValue];
  485. }
  486. } else if (strcmp(typeEncoding, @encode(int)) == 0) {
  487. *(int *)value = [number intValue];
  488. } else if (strcmp(typeEncoding, @encode(short)) == 0) {
  489. *(short *)value = [number shortValue];
  490. } else if (strcmp(typeEncoding, @encode(long)) == 0) {
  491. *(long *)value = [number longValue];
  492. } else if (strcmp(typeEncoding, @encode(long long)) == 0) {
  493. *(long long *)value = [number longLongValue];
  494. } else if (strcmp(typeEncoding, @encode(unsigned char)) == 0) {
  495. *(unsigned char *)value = [number unsignedCharValue];
  496. } else if (strcmp(typeEncoding, @encode(unsigned int)) == 0) {
  497. *(unsigned int *)value = [number unsignedIntValue];
  498. } else if (strcmp(typeEncoding, @encode(unsigned short)) == 0) {
  499. *(unsigned short *)value = [number unsignedShortValue];
  500. } else if (strcmp(typeEncoding, @encode(unsigned long)) == 0) {
  501. *(unsigned long *)value = [number unsignedLongValue];
  502. } else if (strcmp(typeEncoding, @encode(unsigned long long)) == 0) {
  503. *(unsigned long long *)value = [number unsignedLongLongValue];
  504. } else if (strcmp(typeEncoding, @encode(float)) == 0) {
  505. *(float *)value = [number floatValue];
  506. } else if (strcmp(typeEncoding, @encode(double)) == 0) {
  507. *(double *)value = [number doubleValue];
  508. } else {
  509. // If we didn't match one of the supported types, fill the buffer with zeros.
  510. NSUInteger bytes = 0;
  511. NSGetSizeAndAlignment(typeEncoding, &bytes, NULL);
  512. memset(value, 0, bytes);
  513. }
  514. }
  515. }
  516. @end