blob: 8481e3e71c0fc6c79f04e87e1158282888cb38cc [file] [log] [blame]
fischman@chromium.orgdc221a72012-03-25 05:37:27 +09001// 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// This defines helpful methods for dealing with Callbacks. Because Callbacks
6// are implemented using templates, with a class per callback signature, adding
7// methods to Callback<> itself is unattractive (lots of extra code gets
8// generated). Instead, consider adding methods here.
9//
10// ResetAndReturn(&cb) is like cb.Reset() but allows executing a callback (via a
11// copy) after the original callback is Reset(). This can be handy if Run()
12// reads/writes the variable holding the Callback.
13
14#ifndef BASE_CALLBACK_HELPERS_H_
15#define BASE_CALLBACK_HELPERS_H_
16
avi@chromium.orgb74bab82013-08-30 11:04:04 +090017#include "base/basictypes.h"
fischman@chromium.orgdc221a72012-03-25 05:37:27 +090018#include "base/callback.h"
avi@chromium.orgb74bab82013-08-30 11:04:04 +090019#include "base/compiler_specific.h"
fischman@chromium.orgdc221a72012-03-25 05:37:27 +090020
21namespace base {
22
23template <typename Sig>
24base::Callback<Sig> ResetAndReturn(base::Callback<Sig>* cb) {
25 base::Callback<Sig> ret(*cb);
26 cb->Reset();
27 return ret;
28}
29
avi@chromium.orgb74bab82013-08-30 11:04:04 +090030// ScopedClosureRunner is akin to scoped_ptr for Closures. It ensures that the
31// Closure is executed and deleted no matter how the current scope exits.
32class BASE_EXPORT ScopedClosureRunner {
33 public:
34 ScopedClosureRunner();
35 explicit ScopedClosureRunner(const Closure& closure);
36 ~ScopedClosureRunner();
37
38 void Reset();
39 void Reset(const Closure& closure);
40 Closure Release() WARN_UNUSED_RESULT;
41
42 private:
43 Closure closure_;
44
45 DISALLOW_COPY_AND_ASSIGN(ScopedClosureRunner);
46};
47
fischman@chromium.orgdc221a72012-03-25 05:37:27 +090048} // namespace base
49
50#endif // BASE_CALLBACK_HELPERS_H_