blob: 63e43eed012fa90a698cf566b5521cb365f38f8b [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001
bsalomon@google.coma55847b2011-04-20 15:47:04 +00002/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00003 * 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.
bsalomon@google.coma55847b2011-04-20 15:47:04 +00007 */
8
epoger@google.comec3ed6a2011-07-28 14:26:00 +00009
bsalomon@google.coma55847b2011-04-20 15:47:04 +000010#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 */
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/**
bsalomon@google.coma55847b2011-04-20 15:47:04 +000028 * 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 */
39template <typename T> class GrAutoTPtrValueRestore : public GrNoncopyable {
40public:
41 GrAutoTPtrValueRestore() : fPtr(NULL), fVal() {}
42
43 GrAutoTPtrValueRestore(T* ptr) {
44 fPtr = ptr;
45 if (NULL != ptr) {
46 fVal = *ptr;
47 }
48 }
49
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*
57 void save(T* ptr) {
58 if (NULL != fPtr) {
59 *fPtr = fVal;
60 }
61 fPtr = ptr;
62 fVal = *ptr;
63 }
64private:
65 T* fPtr;
66 T fVal;
67};
68
agl@chromium.org83747252011-04-27 23:11:21 +000069#endif