summaryrefslogtreecommitdiffstats
path: root/chromium/base/mac/bind_objc_block.h
blob: 9deb2d22e75c5add2da220e47898060eca0f53b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_MAC_BIND_OBJC_BLOCK_H_
#define BASE_MAC_BIND_OBJC_BLOCK_H_

#include <Block.h>

#include "base/bind.h"
#include "base/callback_forward.h"
#include "base/mac/scoped_block.h"

// BindBlock builds a callback from an Objective-C block. Example usages:
//
// Closure closure = BindBlock(^{DoSomething();});
//
// Callback<int(void)> callback = BindBlock(^{return 42;});
//
// Callback<void(const std::string&, const std::string&)> callback =
//     BindBlock(^(const std::string& arg0, const std::string& arg1) {
//         ...
//     });

namespace base {

namespace internal {

// Helper functions to run the block contained in the parameter.
template<typename R>
R RunBlock(base::mac::ScopedBlock<R(^)()> block) {
  R(^extracted_block)() = block.get();
  return extracted_block();
}

template<typename R, typename A1>
R RunBlock(base::mac::ScopedBlock<R(^)(A1)> block, A1 a) {
  R(^extracted_block)(A1) = block.get();
  return extracted_block(a);
}

template<typename R, typename A1, typename A2>
R RunBlock(base::mac::ScopedBlock<R(^)(A1, A2)> block, A1 a, A2 b) {
  R(^extracted_block)(A1, A2) = block.get();
  return extracted_block(a, b);
}

}  // namespace internal

// Construct a callback with no argument from an objective-C block.
template<typename R>
base::Callback<R(void)> BindBlock(R(^block)()) {
  return base::Bind(&base::internal::RunBlock<R>,
                    base::mac::ScopedBlock<R(^)()>(Block_copy(block)));
}

// Construct a callback with one argument from an objective-C block.
template<typename R, typename A1>
base::Callback<R(A1)> BindBlock(R(^block)(A1)) {
  return base::Bind(&base::internal::RunBlock<R, A1>,
                    base::mac::ScopedBlock<R(^)(A1)>(Block_copy(block)));
}

// Construct a callback with two arguments from an objective-C block.
template<typename R, typename A1, typename A2>
base::Callback<R(A1, A2)> BindBlock(R(^block)(A1, A2)) {
  return base::Bind(&base::internal::RunBlock<R, A1, A2>,
                    base::mac::ScopedBlock<R(^)(A1, A2)>(Block_copy(block)));
}

}  // namespace base

#endif  // BASE_MAC_BIND_OBJC_BLOCK_H_