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/mac/scoped_typeref.h"
11 
12 #if defined(__has_feature) && __has_feature(objc_arc)
13 #define BASE_MAC_BRIDGE_CAST(TYPE, VALUE) (__bridge TYPE)(VALUE)
14 #else
15 #define BASE_MAC_BRIDGE_CAST(TYPE, VALUE) VALUE
16 #endif
17 
18 namespace base {
19 namespace mac {
20 
21 namespace internal {
22 
23 template <typename B>
24 struct ScopedBlockTraits {
InvalidValueScopedBlockTraits25   static B InvalidValue() { return nullptr; }
RetainScopedBlockTraits26   static B Retain(B block) {
27     return BASE_MAC_BRIDGE_CAST(
28         B, Block_copy(BASE_MAC_BRIDGE_CAST(const void*, block)));
29   }
ReleaseScopedBlockTraits30   static void Release(B block) {
31     Block_release(BASE_MAC_BRIDGE_CAST(const void*, block));
32   }
33 };
34 
35 }  // namespace internal
36 
37 // ScopedBlock<> is patterned after ScopedCFTypeRef<>, but uses Block_copy() and
38 // Block_release() instead of CFRetain() and CFRelease().
39 
40 template <typename B>
41 using ScopedBlock = ScopedTypeRef<B, internal::ScopedBlockTraits<B>>;
42 
43 }  // namespace mac
44 }  // namespace base
45 
46 #undef BASE_MAC_BRIDGE_CAST
47 
48 #endif  // BASE_MAC_SCOPED_BLOCK_H_
49