OCMBoxedReturnValueProvider.m 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright (c) 2009-2015 Erik Doernenburg and contributors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. * not use these files except in compliance with the License. You may obtain
  6. * a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations
  14. * under the License.
  15. */
  16. #import "OCMBoxedReturnValueProvider.h"
  17. #import "OCMFunctions.h"
  18. #import "NSValue+OCMAdditions.h"
  19. @implementation OCMBoxedReturnValueProvider
  20. - (void)handleInvocation:(NSInvocation *)anInvocation
  21. {
  22. const char *returnType = [[anInvocation methodSignature] methodReturnType];
  23. NSUInteger returnTypeSize = [[anInvocation methodSignature] methodReturnLength];
  24. char valueBuffer[returnTypeSize];
  25. NSValue *returnValueAsNSValue = (NSValue *)returnValue;
  26. if([self isMethodReturnType:returnType compatibleWithValueType:[returnValueAsNSValue objCType]])
  27. {
  28. [returnValueAsNSValue getValue:valueBuffer];
  29. [anInvocation setReturnValue:valueBuffer];
  30. }
  31. else if([returnValueAsNSValue getBytes:valueBuffer objCType:returnType])
  32. {
  33. [anInvocation setReturnValue:valueBuffer];
  34. }
  35. else
  36. {
  37. [NSException raise:NSInvalidArgumentException
  38. format:@"Return value cannot be used for method; method signature declares '%s' but value is '%s'.", returnType, [returnValueAsNSValue objCType]];
  39. }
  40. }
  41. - (BOOL)isMethodReturnType:(const char *)returnType compatibleWithValueType:(const char *)valueType
  42. {
  43. /* Same types are obviously compatible */
  44. if(strcmp(returnType, valueType) == 0)
  45. return YES;
  46. /* Allow void* for methods that return id, mainly to be able to handle nil */
  47. if(strcmp(returnType, @encode(id)) == 0 && strcmp(valueType, @encode(void *)) == 0)
  48. return YES;
  49. return OCMEqualTypesAllowingOpaqueStructs(returnType, valueType);
  50. }
  51. @end