Home | History | Annotate | Download | only in gpu
      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  */
     18 template <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  * takes a T*, saves the value it points to,  in and restores the value in the
     29  * destructor
     30  * e.g.:
     31  * {
     32  *      GrAutoTRestore<int*> autoCountRestore;
     33  *      if (useExtra) {
     34  *          autoCountRestore.reset(&fCount);
     35  *          fCount += fExtraCount;
     36  *      }
     37  *      ...
     38  * }  // fCount is restored
     39  */
     40 template <typename T> class GrAutoTRestore : public GrNoncopyable {
     41 public:
     42     GrAutoTRestore() : fPtr(NULL), fVal() {}
     43 
     44     GrAutoTRestore(T* ptr) {
     45         fPtr = ptr;
     46         if (NULL != ptr) {
     47             fVal = *ptr;
     48         }
     49     }
     50 
     51     ~GrAutoTRestore() {
     52         if (NULL != fPtr) {
     53             *fPtr = fVal;
     54         }
     55     }
     56 
     57     // restores previously saved value (if any) and saves value for passed T*
     58     void reset(T* ptr) {
     59         if (NULL != fPtr) {
     60             *fPtr = fVal;
     61         }
     62         fPtr = ptr;
     63         fVal = *ptr;
     64     }
     65 private:
     66     T* fPtr;
     67     T  fVal;
     68 };
     69 
     70 #endif
     71