AutoClose.h (1545B)
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/. */ 6 7 #ifndef mozilla_net_AutoClose_h 8 #define mozilla_net_AutoClose_h 9 10 #include "nsCOMPtr.h" 11 #include "mozilla/Mutex.h" 12 13 namespace mozilla { 14 namespace net { 15 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(); } 24 25 explicit operator bool() { 26 MutexAutoLock lock(mMutex); 27 return mPtr; 28 } 29 30 already_AddRefed<T> forget() { 31 MutexAutoLock lock(mMutex); 32 return mPtr.forget(); 33 } 34 35 void takeOver(nsCOMPtr<T>& rhs) { TakeOverInternal(rhs.forget()); } 36 37 void CloseAndRelease() { TakeOverInternal(nullptr); } 38 39 private: 40 void TakeOverInternal(already_AddRefed<T>&& aOther) { 41 nsCOMPtr<T> ptr(std::move(aOther)); 42 { 43 MutexAutoLock lock(mMutex); 44 ptr.swap(mPtr); 45 } 46 47 if (ptr) { 48 ptr->Close(); 49 } 50 } 51 52 void operator=(const AutoClose<T>&) = delete; 53 AutoClose(const AutoClose<T>&) = delete; 54 55 nsCOMPtr<T> mPtr; 56 Mutex mMutex MOZ_UNANNOTATED; 57 }; 58 59 } // namespace net 60 } // namespace mozilla 61 62 #endif // mozilla_net_AutoClose_h