blob: 2cab1327831373b11a7a1c1e438d0cde49fdb2fc [file] [log] [blame]
bsalomon@google.coma55847b2011-04-20 15:47:04 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * Copyright 2010 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
bsalomon@google.coma55847b2011-04-20 15:47:04 +00006 */
7
8#ifndef GrTemplates_DEFINED
9#define GrTemplates_DEFINED
10
commit-bot@chromium.orga0b40282013-09-18 13:00:55 +000011#include "SkTypes.h"
bsalomon@google.coma55847b2011-04-20 15:47:04 +000012
13/**
14 * Use to cast a ptr to a different type, and maintain strict-aliasing
15 */
16template <typename Dst, typename Src> Dst GrTCast(Src src) {
17 union {
18 Src src;
19 Dst dst;
20 } data;
21 data.src = src;
22 return data.dst;
23}
24
25/**
bsalomon@google.coma3201942012-06-21 19:58:20 +000026 * takes a T*, saves the value it points to, in and restores the value in the
27 * destructor
bsalomon@google.coma55847b2011-04-20 15:47:04 +000028 * e.g.:
29 * {
bsalomon@google.coma3201942012-06-21 19:58:20 +000030 * GrAutoTRestore<int*> autoCountRestore;
bsalomon@google.coma55847b2011-04-20 15:47:04 +000031 * if (useExtra) {
bsalomon@google.coma3201942012-06-21 19:58:20 +000032 * autoCountRestore.reset(&fCount);
bsalomon@google.coma55847b2011-04-20 15:47:04 +000033 * fCount += fExtraCount;
34 * }
35 * ...
36 * } // fCount is restored
37 */
commit-bot@chromium.orge3beb6b2014-04-07 19:34:38 +000038template <typename T> class GrAutoTRestore : SkNoncopyable {
bsalomon@google.coma55847b2011-04-20 15:47:04 +000039public:
bsalomon@google.coma3201942012-06-21 19:58:20 +000040 GrAutoTRestore() : fPtr(NULL), fVal() {}
rmistry@google.comd6176b02012-08-23 18:14:13 +000041
bsalomon@google.coma3201942012-06-21 19:58:20 +000042 GrAutoTRestore(T* ptr) {
bsalomon@google.coma55847b2011-04-20 15:47:04 +000043 fPtr = ptr;
44 if (NULL != ptr) {
45 fVal = *ptr;
46 }
47 }
rmistry@google.comd6176b02012-08-23 18:14:13 +000048
bsalomon@google.coma3201942012-06-21 19:58:20 +000049 ~GrAutoTRestore() {
bsalomon@google.coma55847b2011-04-20 15:47:04 +000050 if (NULL != fPtr) {
51 *fPtr = fVal;
52 }
53 }
rmistry@google.comd6176b02012-08-23 18:14:13 +000054
bsalomon@google.coma55847b2011-04-20 15:47:04 +000055 // restores previously saved value (if any) and saves value for passed T*
bsalomon@google.coma3201942012-06-21 19:58:20 +000056 void reset(T* ptr) {
bsalomon@google.coma55847b2011-04-20 15:47:04 +000057 if (NULL != fPtr) {
58 *fPtr = fVal;
59 }
60 fPtr = ptr;
61 fVal = *ptr;
62 }
63private:
64 T* fPtr;
65 T fVal;
66};
67
agl@chromium.org83747252011-04-27 23:11:21 +000068#endif