• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2013 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_MAC_SCOPED_BLOCK_H_
6 #define BASE_MAC_SCOPED_BLOCK_H_
7 
8 #include <Block.h>
9 
10 #include "base/basictypes.h"
11 #include "base/compiler_specific.h"
12 #include "base/memory/scoped_policy.h"
13 
14 namespace base {
15 namespace mac {
16 
17 // ScopedBlock<> is patterned after ScopedCFTypeRef<>, but uses Block_copy() and
18 // Block_release() instead of CFRetain() and CFRelease().
19 
20 template<typename B>
21 class ScopedBlock {
22  public:
23   explicit ScopedBlock(
24       B block = NULL,
25       base::scoped_policy::OwnershipPolicy policy = base::scoped_policy::ASSUME)
block_(block)26       : block_(block) {
27     if (block_ && policy == base::scoped_policy::RETAIN)
28       block_ = Block_copy(block);
29   }
30 
ScopedBlock(const ScopedBlock<B> & that)31   ScopedBlock(const ScopedBlock<B>& that)
32       : block_(that.block_) {
33     if (block_)
34       block_ = Block_copy(block_);
35   }
36 
~ScopedBlock()37   ~ScopedBlock() {
38     if (block_)
39       Block_release(block_);
40   }
41 
42   ScopedBlock& operator=(const ScopedBlock<B>& that) {
43     reset(that.get(), base::scoped_policy::RETAIN);
44     return *this;
45   }
46 
47   void reset(B block = NULL,
48              base::scoped_policy::OwnershipPolicy policy =
49                  base::scoped_policy::ASSUME) {
50     if (block && policy == base::scoped_policy::RETAIN)
51       block = Block_copy(block);
52     if (block_)
53       Block_release(block_);
54     block_ = block;
55   }
56 
57   bool operator==(B that) const {
58     return block_ == that;
59   }
60 
61   bool operator!=(B that) const {
62     return block_ != that;
63   }
64 
B()65   operator B() const {
66     return block_;
67   }
68 
get()69   B get() const {
70     return block_;
71   }
72 
swap(ScopedBlock & that)73   void swap(ScopedBlock& that) {
74     B temp = that.block_;
75     that.block_ = block_;
76     block_ = temp;
77   }
78 
release()79   B release() WARN_UNUSED_RESULT {
80     B temp = block_;
81     block_ = NULL;
82     return temp;
83   }
84 
85  private:
86   B block_;
87 };
88 
89 }  // namespace mac
90 }  // namespace base
91 
92 #endif  // BASE_MAC_SCOPED_BLOCK_H_
93