1 2 /* 3 * Copyright 2010 Google Inc. 4 * 5 * Use of this source code is governed by a BSD-style license that can be 6 * found in the LICENSE file. 7 */ 8 9 10 #ifndef GrTemplates_DEFINED 11 #define GrTemplates_DEFINED 12 13 #include "GrNoncopyable.h" 14 15 /** 16 * Use to cast a ptr to a different type, and maintain strict-aliasing 17 */ GrTCast(Src src)18template <typename Dst, typename Src> Dst GrTCast(Src src) { 19 union { 20 Src src; 21 Dst dst; 22 } data; 23 data.src = src; 24 return data.dst; 25 } 26 27 /** 28 * saves value of T* in and restores in destructor 29 * e.g.: 30 * { 31 * GrAutoTPtrValueRestore<int*> autoCountRestore; 32 * if (useExtra) { 33 * autoCountRestore.save(&fCount); 34 * fCount += fExtraCount; 35 * } 36 * ... 37 * } // fCount is restored 38 */ 39 template <typename T> class GrAutoTPtrValueRestore : public GrNoncopyable { 40 public: GrAutoTPtrValueRestore()41 GrAutoTPtrValueRestore() : fPtr(NULL), fVal() {} 42 GrAutoTPtrValueRestore(T * ptr)43 GrAutoTPtrValueRestore(T* ptr) { 44 fPtr = ptr; 45 if (NULL != ptr) { 46 fVal = *ptr; 47 } 48 } 49 ~GrAutoTPtrValueRestore()50 ~GrAutoTPtrValueRestore() { 51 if (NULL != fPtr) { 52 *fPtr = fVal; 53 } 54 } 55 56 // restores previously saved value (if any) and saves value for passed T* save(T * ptr)57 void save(T* ptr) { 58 if (NULL != fPtr) { 59 *fPtr = fVal; 60 } 61 fPtr = ptr; 62 fVal = *ptr; 63 } 64 private: 65 T* fPtr; 66 T fVal; 67 }; 68 69 #endif 70