/src/mozilla-central/netwerk/base/AutoClose.h
Line | Count | Source (jump to first uncovered line) |
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 { namespace net { |
14 | | |
15 | | // Like an nsAutoPtr for XPCOM streams (e.g. nsIAsyncInputStream) and other |
16 | | // refcounted classes that need to have the Close() method called explicitly |
17 | | // before they are destroyed. |
18 | | template <typename T> |
19 | | class AutoClose |
20 | | { |
21 | | public: |
22 | 0 | AutoClose() : mMutex("net::AutoClose.mMutex") { } |
23 | 0 | ~AutoClose(){ |
24 | 0 | CloseAndRelease(); |
25 | 0 | } |
26 | | |
27 | | explicit operator bool() |
28 | 0 | { |
29 | 0 | MutexAutoLock lock(mMutex); |
30 | 0 | return mPtr; |
31 | 0 | } |
32 | | |
33 | | already_AddRefed<T> forget() |
34 | 0 | { |
35 | 0 | MutexAutoLock lock(mMutex); |
36 | 0 | return mPtr.forget(); |
37 | 0 | } |
38 | | |
39 | | void takeOver(nsCOMPtr<T> & rhs) |
40 | 0 | { |
41 | 0 | TakeOverInternal(rhs.forget()); |
42 | 0 | } |
43 | | |
44 | | void CloseAndRelease() |
45 | 0 | { |
46 | 0 | TakeOverInternal(nullptr); |
47 | 0 | } |
48 | | |
49 | | private: |
50 | | void TakeOverInternal(already_AddRefed<T>&& aOther) |
51 | 0 | { |
52 | 0 | nsCOMPtr<T> ptr(std::move(aOther)); |
53 | 0 | { |
54 | 0 | MutexAutoLock lock(mMutex); |
55 | 0 | ptr.swap(mPtr); |
56 | 0 | } |
57 | 0 |
|
58 | 0 | if (ptr) { |
59 | 0 | ptr->Close(); |
60 | 0 | } |
61 | 0 | } |
62 | | |
63 | | void operator=(const AutoClose<T> &) = delete; |
64 | | AutoClose(const AutoClose<T> &) = delete; |
65 | | |
66 | | nsCOMPtr<T> mPtr; |
67 | | Mutex mMutex; |
68 | | }; |
69 | | |
70 | | } // namespace net |
71 | | } // namespace mozilla |
72 | | |
73 | | #endif // mozilla_net_AutoClose_h |