michael@0: /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* vim: set ts=2 et sw=2 tw=80: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this file, michael@0: * You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #ifndef mozilla_net_AutoClose_h michael@0: #define mozilla_net_AutoClose_h michael@0: michael@0: #include "nsCOMPtr.h" michael@0: michael@0: namespace mozilla { namespace net { michael@0: michael@0: // Like an nsAutoPtr for XPCOM streams (e.g. nsIAsyncInputStream) and other michael@0: // refcounted classes that need to have the Close() method called explicitly michael@0: // before they are destroyed. michael@0: template michael@0: class AutoClose michael@0: { michael@0: public: michael@0: AutoClose() { } michael@0: ~AutoClose(){ michael@0: Close(); michael@0: } michael@0: michael@0: operator bool() const michael@0: { michael@0: return mPtr; michael@0: } michael@0: michael@0: already_AddRefed forget() michael@0: { michael@0: return mPtr.forget(); michael@0: } michael@0: michael@0: void takeOver(nsCOMPtr & rhs) michael@0: { michael@0: Close(); michael@0: mPtr = rhs.forget(); michael@0: } michael@0: michael@0: void takeOver(AutoClose & rhs) michael@0: { michael@0: Close(); michael@0: mPtr = rhs.mPtr.forget(); michael@0: } michael@0: michael@0: void CloseAndRelease() michael@0: { michael@0: Close(); michael@0: mPtr = nullptr; michael@0: } michael@0: michael@0: T* operator->() const michael@0: { michael@0: return mPtr.operator->(); michael@0: } michael@0: michael@0: private: michael@0: void Close() michael@0: { michael@0: if (mPtr) { michael@0: mPtr->Close(); michael@0: } michael@0: } michael@0: michael@0: void operator=(const AutoClose &) MOZ_DELETE; michael@0: AutoClose(const AutoClose &) MOZ_DELETE; michael@0: michael@0: nsCOMPtr mPtr; michael@0: }; michael@0: michael@0: } } // namespace mozilla::net michael@0: michael@0: #endif // mozilla_net_AutoClose_h