aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/gpu/GrTemplates.h
blob: 4378d70949310c8963ce66475670edc6f4b80a01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

/*
 * Copyright 2010 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */


#ifndef GrTemplates_DEFINED
#define GrTemplates_DEFINED

#include "GrNoncopyable.h"

/**
 *  Use to cast a ptr to a different type, and maintain strict-aliasing
 */
template <typename Dst, typename Src> Dst GrTCast(Src src) {
    union {
        Src src;
        Dst dst;
    } data;
    data.src = src;
    return data.dst;
}

/**
 * takes a T*, saves the value it points to,  in and restores the value in the
 * destructor
 * e.g.:
 * {
 *      GrAutoTRestore<int*> autoCountRestore;
 *      if (useExtra) {
 *          autoCountRestore.reset(&fCount);
 *          fCount += fExtraCount;
 *      }
 *      ...
 * }  // fCount is restored
 */
template <typename T> class GrAutoTRestore : public GrNoncopyable {
public:
    GrAutoTRestore() : fPtr(NULL), fVal() {}
    
    GrAutoTRestore(T* ptr) {
        fPtr = ptr;
        if (NULL != ptr) {
            fVal = *ptr;
        }
    }
    
    ~GrAutoTRestore() {
        if (NULL != fPtr) {
            *fPtr = fVal;
        }
    }
    
    // restores previously saved value (if any) and saves value for passed T*
    void reset(T* ptr) {
        if (NULL != fPtr) {
            *fPtr = fVal;
        }
        fPtr = ptr;
        fVal = *ptr;
    }
private:
    T* fPtr;
    T  fVal;
};

#endif