blob: 9ffa51b4fb0c99585d28a14716870e9c6e152e2f [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/**
28 * Reserves memory that is aligned on double and pointer boundaries.
29 * Hopefully this is sufficient for all practical purposes.
30 */
31template <size_t N> class GrAlignedSStorage : GrNoncopyable {
32public:
33 void* get() { return fData; }
34private:
35 union {
36 void* fPtr;
37 double fDouble;
38 char fData[N];
39 };
40};
41
42/**
43 * Reserves memory that is aligned on double and pointer boundaries.
44 * Hopefully this is sufficient for all practical purposes. Otherwise,
45 * we have to do some arcane trickery to determine alignment of non-POD
46 * types. Lifetime of the memory is the lifetime of the object.
47 */
48template <int N, typename T> class GrAlignedSTStorage : GrNoncopyable {
49public:
50 /**
51 * Returns void* because this object does not initialize the
52 * memory. Use placement new for types that require a cons.
53 */
54 void* get() { return fStorage.get(); }
55private:
56 GrAlignedSStorage<sizeof(T)*N> fStorage;
57};
58
59/**
60 * saves value of T* in and restores in destructor
61 * e.g.:
62 * {
63 * GrAutoTPtrValueRestore<int*> autoCountRestore;
64 * if (useExtra) {
65 * autoCountRestore.save(&fCount);
66 * fCount += fExtraCount;
67 * }
68 * ...
69 * } // fCount is restored
70 */
71template <typename T> class GrAutoTPtrValueRestore : public GrNoncopyable {
72public:
73 GrAutoTPtrValueRestore() : fPtr(NULL), fVal() {}
74
75 GrAutoTPtrValueRestore(T* ptr) {
76 fPtr = ptr;
77 if (NULL != ptr) {
78 fVal = *ptr;
79 }
80 }
81
82 ~GrAutoTPtrValueRestore() {
83 if (NULL != fPtr) {
84 *fPtr = fVal;
85 }
86 }
87
88 // restores previously saved value (if any) and saves value for passed T*
89 void save(T* ptr) {
90 if (NULL != fPtr) {
91 *fPtr = fVal;
92 }
93 fPtr = ptr;
94 fVal = *ptr;
95 }
96private:
97 T* fPtr;
98 T fVal;
99};
100
agl@chromium.org83747252011-04-27 23:11:21 +0000101#endif