Merge mozilla-central to autoland. CLOSED TREE
[gecko.git] / netwerk / base / AutoClose.h
bloba0e3a48e17fd3cae9db77b615b6370d39962e8f9
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_net_AutoClose_h
8 #define mozilla_net_AutoClose_h
10 #include "nsCOMPtr.h"
11 #include "mozilla/Mutex.h"
13 namespace mozilla {
14 namespace net {
16 // A container for XPCOM streams (e.g. nsIAsyncInputStream) and other
17 // refcounted classes that need to have the Close() method called explicitly
18 // before they are destroyed.
19 template <typename T>
20 class AutoClose {
21 public:
22 AutoClose() : mMutex("net::AutoClose.mMutex") {}
23 ~AutoClose() { CloseAndRelease(); }
25 explicit operator bool() {
26 MutexAutoLock lock(mMutex);
27 return mPtr;
30 already_AddRefed<T> forget() {
31 MutexAutoLock lock(mMutex);
32 return mPtr.forget();
35 void takeOver(nsCOMPtr<T>& rhs) { TakeOverInternal(rhs.forget()); }
37 void CloseAndRelease() { TakeOverInternal(nullptr); }
39 private:
40 void TakeOverInternal(already_AddRefed<T>&& aOther) {
41 nsCOMPtr<T> ptr(std::move(aOther));
43 MutexAutoLock lock(mMutex);
44 ptr.swap(mPtr);
47 if (ptr) {
48 ptr->Close();
52 void operator=(const AutoClose<T>&) = delete;
53 AutoClose(const AutoClose<T>&) = delete;
55 nsCOMPtr<T> mPtr;
56 Mutex mMutex MOZ_UNANNOTATED;
59 } // namespace net
60 } // namespace mozilla
62 #endif // mozilla_net_AutoClose_h