1 | /* |
2 | * Copyright (C) 2011 Google Inc. All rights reserved. |
3 | * Copyright (C) 2016 Apple Inc. All rights reserved. |
4 | * |
5 | * Redistribution and use in source and binary forms, with or without |
6 | * modification, are permitted provided that the following conditions |
7 | * are met: |
8 | * |
9 | * 1. Redistributions of source code must retain the above copyright |
10 | * notice, this list of conditions and the following disclaimer. |
11 | * 2. Redistributions in binary form must reproduce the above copyright |
12 | * notice, this list of conditions and the following disclaimer in the |
13 | * documentation and/or other materials provided with the distribution. |
14 | * |
15 | * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY |
16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
17 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
18 | * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY |
19 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
20 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
21 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND |
22 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
23 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF |
24 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
25 | */ |
26 | |
27 | #pragma once |
28 | |
29 | #include <wtf/Noncopyable.h> |
30 | #include <wtf/StdLibExtras.h> |
31 | |
32 | namespace WTF { |
33 | |
34 | // SetForScope<> is useful for setting a variable to a new value only within a |
35 | // particular scope. An SetForScope<> object changes a variable to its original |
36 | // value upon destruction, making it an alternative to writing "var = false;" |
37 | // or "var = oldVal;" at all of a block's exit points. |
38 | // |
39 | // This should be obvious, but note that an SetForScope<> instance should have a |
40 | // shorter lifetime than its scopedVariable, to prevent invalid memory writes |
41 | // when the SetForScope<> object is destroyed. |
42 | |
43 | template<typename T> |
44 | class SetForScope { |
45 | WTF_MAKE_NONCOPYABLE(SetForScope); |
46 | public: |
47 | SetForScope(T& scopedVariable) |
48 | : m_scopedVariable(scopedVariable) |
49 | , m_originalValue(scopedVariable) |
50 | { |
51 | } |
52 | template<typename U> |
53 | SetForScope(T& scopedVariable, U&& newValue) |
54 | : SetForScope(scopedVariable) |
55 | { |
56 | m_scopedVariable = std::forward<U>(newValue); |
57 | } |
58 | |
59 | ~SetForScope() |
60 | { |
61 | m_scopedVariable = WTFMove(m_originalValue); |
62 | } |
63 | |
64 | private: |
65 | T& m_scopedVariable; |
66 | T m_originalValue; |
67 | }; |
68 | |
69 | } |
70 | |
71 | using WTF::SetForScope; |
72 | |