PageRenderTime 30ms CodeModel.GetById 26ms app.highlight 1ms RepoModel.GetById 1ms app.codeStats 0ms

/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
19#import <Foundation/Foundation.h>
20#import "GTMDefines.h"
21
22// These are some basic macros for making down-casting safer in Objective C.
23// They are loosely based on the same cast types with similar names in C++.
24// A typical usage would look like this:
25//
26// Bar* b = [[Bar alloc] init];
27// Foo* a = GTM_STATIC_CAST(Foo, b);
28//
29// Note that it's GTM_STATIC_CAST(Foo, b) and not GTM_STATIC_CAST(Foo*, b).
30//
31// GTM_STATIC_CAST runs only in debug mode, and will assert if and only if:
32//   - object is non nil
33//   - [object isKindOfClass:[cls class]] returns nil
34//
35// otherwise it returns object.
36//
37// GTM_DYNAMIC_CAST runs in both debug and release and will return nil if
38//   - object is nil
39//   - [object isKindOfClass:[cls class]] returns nil
40//
41// otherwise it returns object.
42//
43
44// Support functions for dealing with casting.
45GTM_INLINE id GTMDynamicCastSupport(Class cls, id object) {
46  _GTMDevAssert(cls, @"Nil Class");
47  return [object isKindOfClass:cls] ? object : nil;
48}
49
50GTM_INLINE id GTMStaticCastSupport(Class cls, id object) {
51  id value = nil;
52  if (object) {
53    value = GTMDynamicCastSupport(cls, object);
54    _GTMDevAssert(value, @"Could not cast %@ to class %@", object, cls);
55  }
56  return value;
57}
58
59#ifndef GTM_STATIC_CAST
60  #ifdef DEBUG
61    #define GTM_STATIC_CAST(type, object) GTMStaticCastSupport([type class], \
62                                                               object)
63  #else
64    #define GTM_STATIC_CAST(type, object) ((type *) (object))
65  #endif
66#endif
67
68#ifndef GTM_DYNAMIC_CAST
69  #define GTM_DYNAMIC_CAST(type, object) GTMDynamicCastSupport([type class], \
70                                                               object)
71#endif