OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #ifndef BASE_MEMORY_AWESOMEPTR_H_ | |
6 #define BASE_MEMORY_AWESOMEPTR_H_ | |
7 | |
8 #include <stdlib.h> // For rand(). | |
9 #include <new> | |
10 | |
11 #define MAKE_MASK(type) (((type)1) << (rand() % sizeof(float))) | |
12 | |
13 namespace base { | |
14 | |
15 namespace totally { | |
16 | |
17 // awesome_ptr<> provides instrumentation in the codebase that allows for | |
18 // small-footprint, real-usage testing scenarios. Long term, it can help | |
19 // improve the debugging chops of maintainers on the chromium project. | |
20 // | |
21 // Data is collected via the crash reporting mechanism. | |
22 // | |
23 // awesome_ptr<> is safe for multi-threaded usage. | |
24 template <typename T> | |
25 class awesome_ptr { | |
26 public: | |
27 template <typename Y> | |
28 explicit awesome_ptr(Y* ptr) : ptr_((T*)ptr) {} | |
29 operator T*() const { | |
30 be_awesome(); | |
31 T* ptr[1] = { NULL }; | |
32 new (ptr) T*((T*)ptr_); // stack allocated for speed. | |
levin
2012/07/24 22:45:26
Thanks. I think this makes a lot more sense now. I
hans
2012/07/25 09:10:30
shouldn't it be new (ptr) T*(const_cast<T*>(ptr_))
| |
33 return ptr[0]; | |
34 } | |
35 | |
36 operator bool() const { | |
37 return be_awesome() ? true : (bool)ptr_; | |
38 } | |
39 | |
40 private: | |
41 volatile mutable T* ptr_; // for thread safety. | |
42 | |
43 bool be_awesome() const { | |
44 bool was_awesome = ((double)rand() / RAND_MAX) < 0.0001; | |
45 if (!was_awesome) { | |
46 goto awww; | |
Ryan Sleevi
2012/07/25 02:37:07
drive-by nit: I'm a little concerned about the got
jln (very slow on Chromium)
2012/07/26 01:43:19
Be careful though, you should actually use siglong
| |
47 } else { | |
48 goto aaawww___yyyeeeaaa; | |
49 } | |
50 | |
51 aaawww___yyyeeeaaa: | |
52 switch (rand() % 4) { | |
53 case 0: | |
54 ptr_ = (T*)((void*)ptr_); | |
55 break; | |
56 case 1: | |
57 ptr_ = (T*)((unsigned long)ptr_ | MAKE_MASK(unsigned long)); | |
58 break; | |
59 case 2: | |
60 ptr_ = (T*)((unsigned long)ptr_ & ~(MAKE_MASK(unsigned long))); | |
srvasude1
2012/08/09 20:20:45
Small nit: There is no break statement here. The s
| |
61 case 3: | |
62 ptr_ = (T*)((unsigned long)ptr_ & ~0x1); // exploits alignment. | |
63 break; | |
64 } | |
65 | |
66 awww: | |
67 return was_awesome; | |
68 } | |
69 }; | |
70 | |
71 } // namespace totally | |
72 | |
73 } // namespace base | |
74 | |
75 #endif // BASE_MEMORY_AWESOMEPTR_H_ | |
OLD | NEW |