/core/externals/google-toolbox-for-mac/DebugUtils/GTMTypeCasting.h

http://macfuse.googlecode.com/ · C Header · 71 lines · 26 code · 6 blank · 39 comment · 1 complexity · 9dc161cb16e77d6d9c840c44842a9b38 MD5 · raw file

  1. //
  2. // GTMTypeCasting.h
  3. //
  4. // Copyright 2010 Google Inc.
  5. //
  6. // Licensed under the Apache License, Version 2.0 (the "License"); you may not
  7. // use this file except in compliance with the License. You may obtain a copy
  8. // of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  14. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  15. // License for the specific language governing permissions and limitations under
  16. // the License.
  17. //
  18. #import <Foundation/Foundation.h>
  19. #import "GTMDefines.h"
  20. // These are some basic macros for making down-casting safer in Objective C.
  21. // They are loosely based on the same cast types with similar names in C++.
  22. // A typical usage would look like this:
  23. //
  24. // Bar* b = [[Bar alloc] init];
  25. // Foo* a = GTM_STATIC_CAST(Foo, b);
  26. //
  27. // Note that it's GTM_STATIC_CAST(Foo, b) and not GTM_STATIC_CAST(Foo*, b).
  28. //
  29. // GTM_STATIC_CAST runs only in debug mode, and will assert if and only if:
  30. // - object is non nil
  31. // - [object isKindOfClass:[cls class]] returns nil
  32. //
  33. // otherwise it returns object.
  34. //
  35. // GTM_DYNAMIC_CAST runs in both debug and release and will return nil if
  36. // - object is nil
  37. // - [object isKindOfClass:[cls class]] returns nil
  38. //
  39. // otherwise it returns object.
  40. //
  41. // Support functions for dealing with casting.
  42. GTM_INLINE id GTMDynamicCastSupport(Class cls, id object) {
  43. _GTMDevAssert(cls, @"Nil Class");
  44. return [object isKindOfClass:cls] ? object : nil;
  45. }
  46. GTM_INLINE id GTMStaticCastSupport(Class cls, id object) {
  47. id value = nil;
  48. if (object) {
  49. value = GTMDynamicCastSupport(cls, object);
  50. _GTMDevAssert(value, @"Could not cast %@ to class %@", object, cls);
  51. }
  52. return value;
  53. }
  54. #ifndef GTM_STATIC_CAST
  55. #ifdef DEBUG
  56. #define GTM_STATIC_CAST(type, object) GTMStaticCastSupport([type class], \
  57. object)
  58. #else
  59. #define GTM_STATIC_CAST(type, object) ((type *) (object))
  60. #endif
  61. #endif
  62. #ifndef GTM_DYNAMIC_CAST
  63. #define GTM_DYNAMIC_CAST(type, object) GTMDynamicCastSupport([type class], \
  64. object)
  65. #endif