From b2fa9805eb63d5daa1dd8fab1edf0c85fb7ebfc0 Mon Sep 17 00:00:00 2001 From: "gtm.daemon" Date: Fri, 8 Jan 2010 04:36:12 +0000 Subject: [Author: dmaclach] Added some basic casting debugging goodness to GTM. Opinions? added to help catch a bug in QSB. R=thomasvl DELTA=55 (55 added, 0 deleted, 0 changed) --- DebugUtils/GTMTypeCasting.h | 81 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 DebugUtils/GTMTypeCasting.h (limited to 'DebugUtils') diff --git a/DebugUtils/GTMTypeCasting.h b/DebugUtils/GTMTypeCasting.h new file mode 100644 index 0000000..1e9ebb9 --- /dev/null +++ b/DebugUtils/GTMTypeCasting.h @@ -0,0 +1,81 @@ +// +// GTMTypeCasting.h +// +// Copyright 2010 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy +// of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +#import +#import "GTMDefines.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// These are some basic macros for making down-casting safer in Objective C. +// They are loosely based on the same cast types with similar names in C++. +// A typical usage would look like this: +// +// Bar* b = [[Bar alloc] init]; +// Foo* a = GTM_STATIC_CAST(Foo, b); +// +// Note that it's GTM_STATIC_CAST(Foo, b) and not GTM_STATIC_CAST(Foo*, b). +// +// GTM_STATIC_CAST runs only in debug mode, and will assert if and only if: +// - object is non nil +// - [object isKindOfClass:[cls class]] returns nil +// +// otherwise it returns object. +// +// GTM_DYNAMIC_CAST runs in both debug and release and will return nil if +// - object is nil +// - [object isKindOfClass:[cls class]] returns nil +// +// otherwise it returns object. +// + +// Support functions for dealing with casting. +GTM_INLINE id GTMDynamicCastSupport(Class cls, id object) { + id value = nil; + if (object) { + _GTMDevAssert(cls, @"Nil Class"); + if ([object isKindOfClass:cls]) { + value = object; + } + } + return value; +} + +GTM_INLINE id GTMStaticCastSupport(Class cls, id object) { + id value = nil; + if (object) { + value = GTMDynamicCastSupport(cls, object); + _GTMDevAssert(value, @"Could not cast %@ to class %@", object, cls); + } + return value; +} + +#ifndef GTM_STATIC_CAST + #ifdef DEBUG + #define GTM_STATIC_CAST(type, object) GTMStaticCastSupport([type class], \ + object) + #else + #define GTM_STATIC_CAST(type, object) ((type *) (object)) + #endif +#endif + +#ifndef GTM_DYNAMIC_CAST + #define GTM_DYNAMIC_CAST(type, object) GTMDynamicCastSupport([type class], \ + object) +#endif -- cgit v1.2.3