blob: 69720dc111ac4b15087d35fd773eb6f3525485cd [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.coma3201942012-06-21 19:58:20 +000028 * takes a T*, saves the value it points to, in and restores the value in the
29 * destructor
bsalomon@google.coma55847b2011-04-20 15:47:04 +000030 * e.g.:
31 * {
bsalomon@google.coma3201942012-06-21 19:58:20 +000032 * GrAutoTRestore<int*> autoCountRestore;
bsalomon@google.coma55847b2011-04-20 15:47:04 +000033 * if (useExtra) {
bsalomon@google.coma3201942012-06-21 19:58:20 +000034 * autoCountRestore.reset(&fCount);
bsalomon@google.coma55847b2011-04-20 15:47:04 +000035 * fCount += fExtraCount;
36 * }
37 * ...
38 * } // fCount is restored
39 */
bsalomon@google.coma3201942012-06-21 19:58:20 +000040template <typename T> class GrAutoTRestore : public GrNoncopyable {
bsalomon@google.coma55847b2011-04-20 15:47:04 +000041public:
bsalomon@google.coma3201942012-06-21 19:58:20 +000042 GrAutoTRestore() : fPtr(NULL), fVal() {}
rmistry@google.comd6176b02012-08-23 18:14:13 +000043
bsalomon@google.coma3201942012-06-21 19:58:20 +000044 GrAutoTRestore(T* ptr) {
bsalomon@google.coma55847b2011-04-20 15:47:04 +000045 fPtr = ptr;
46 if (NULL != ptr) {
47 fVal = *ptr;
48 }
49 }
rmistry@google.comd6176b02012-08-23 18:14:13 +000050
bsalomon@google.coma3201942012-06-21 19:58:20 +000051 ~GrAutoTRestore() {
bsalomon@google.coma55847b2011-04-20 15:47:04 +000052 if (NULL != fPtr) {
53 *fPtr = fVal;
54 }
55 }
rmistry@google.comd6176b02012-08-23 18:14:13 +000056
bsalomon@google.coma55847b2011-04-20 15:47:04 +000057 // restores previously saved value (if any) and saves value for passed T*
bsalomon@google.coma3201942012-06-21 19:58:20 +000058 void reset(T* ptr) {
bsalomon@google.coma55847b2011-04-20 15:47:04 +000059 if (NULL != fPtr) {
60 *fPtr = fVal;
61 }
62 fPtr = ptr;
63 fVal = *ptr;
64 }
65private:
66 T* fPtr;
67 T fVal;
68};
69
agl@chromium.org83747252011-04-27 23:11:21 +000070#endif