michael@0: /* michael@0: * Copyright 2010 Google Inc. michael@0: * michael@0: * Use of this source code is governed by a BSD-style license that can be michael@0: * found in the LICENSE file. michael@0: */ michael@0: michael@0: #ifndef GrTemplates_DEFINED michael@0: #define GrTemplates_DEFINED michael@0: michael@0: #include "SkTypes.h" michael@0: michael@0: /** michael@0: * Use to cast a ptr to a different type, and maintain strict-aliasing michael@0: */ michael@0: template Dst GrTCast(Src src) { michael@0: union { michael@0: Src src; michael@0: Dst dst; michael@0: } data; michael@0: data.src = src; michael@0: return data.dst; michael@0: } michael@0: michael@0: /** michael@0: * takes a T*, saves the value it points to, in and restores the value in the michael@0: * destructor michael@0: * e.g.: michael@0: * { michael@0: * GrAutoTRestore autoCountRestore; michael@0: * if (useExtra) { michael@0: * autoCountRestore.reset(&fCount); michael@0: * fCount += fExtraCount; michael@0: * } michael@0: * ... michael@0: * } // fCount is restored michael@0: */ michael@0: template class GrAutoTRestore : public SkNoncopyable { michael@0: public: michael@0: GrAutoTRestore() : fPtr(NULL), fVal() {} michael@0: michael@0: GrAutoTRestore(T* ptr) { michael@0: fPtr = ptr; michael@0: if (NULL != ptr) { michael@0: fVal = *ptr; michael@0: } michael@0: } michael@0: michael@0: ~GrAutoTRestore() { michael@0: if (NULL != fPtr) { michael@0: *fPtr = fVal; michael@0: } michael@0: } michael@0: michael@0: // restores previously saved value (if any) and saves value for passed T* michael@0: void reset(T* ptr) { michael@0: if (NULL != fPtr) { michael@0: *fPtr = fVal; michael@0: } michael@0: fPtr = ptr; michael@0: fVal = *ptr; michael@0: } michael@0: private: michael@0: T* fPtr; michael@0: T fVal; michael@0: }; michael@0: michael@0: #endif