Line data Source code
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 :
12 : namespace mozilla { namespace net {
13 :
14 : // Like an nsAutoPtr for XPCOM streams (e.g. nsIAsyncInputStream) and other
15 : // refcounted classes that need to have the Close() method called explicitly
16 : // before they are destroyed.
17 : template <typename T>
18 : class AutoClose
19 : {
20 : public:
21 7 : AutoClose() { }
22 5 : ~AutoClose(){
23 5 : Close();
24 5 : }
25 :
26 6 : explicit operator bool() const
27 : {
28 6 : return mPtr;
29 : }
30 :
31 3 : already_AddRefed<T> forget()
32 : {
33 3 : return mPtr.forget();
34 : }
35 :
36 4 : void takeOver(nsCOMPtr<T> & rhs)
37 : {
38 4 : Close();
39 4 : mPtr = rhs.forget();
40 4 : }
41 :
42 : void takeOver(AutoClose<T> & rhs)
43 : {
44 : Close();
45 : mPtr = rhs.mPtr.forget();
46 : }
47 :
48 9 : void CloseAndRelease()
49 : {
50 9 : Close();
51 9 : mPtr = nullptr;
52 9 : }
53 :
54 : T* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN
55 : {
56 : return mPtr.operator->();
57 : }
58 :
59 : private:
60 18 : void Close()
61 : {
62 18 : if (mPtr) {
63 1 : mPtr->Close();
64 : }
65 18 : }
66 :
67 : void operator=(const AutoClose<T> &) = delete;
68 : AutoClose(const AutoClose<T> &) = delete;
69 :
70 : nsCOMPtr<T> mPtr;
71 : };
72 :
73 : } // namespace net
74 : } // namespace mozilla
75 :
76 : #endif // mozilla_net_AutoClose_h
|