2012-06-01 02:20:04 +04:00
|
|
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
|
|
|
|
/* vim: set ts=2 et sw=2 tw=80: */
|
|
|
|
/* This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
|
2012-06-28 23:18:25 +04:00
|
|
|
* You can obtain one at http://mozilla.org/MPL/2.0/. */
|
2014-06-19 04:56:02 +04:00
|
|
|
|
2012-06-28 23:18:25 +04:00
|
|
|
#ifndef mozilla_net_AutoClose_h
|
|
|
|
#define mozilla_net_AutoClose_h
|
2014-06-19 04:56:02 +04:00
|
|
|
|
2012-06-28 23:18:25 +04:00
|
|
|
#include "nsCOMPtr.h"
|
2017-12-07 04:48:06 +03:00
|
|
|
#include "mozilla/Mutex.h"
|
2014-06-19 04:56:02 +04:00
|
|
|
|
2012-06-28 23:18:25 +04:00
|
|
|
namespace mozilla {
|
|
|
|
namespace net {
|
2014-06-19 04:56:02 +04:00
|
|
|
|
2020-02-11 19:20:08 +03:00
|
|
|
// A container for XPCOM streams (e.g. nsIAsyncInputStream) and other
|
2012-06-28 23:18:25 +04:00
|
|
|
// refcounted classes that need to have the Close() method called explicitly
|
|
|
|
// before they are destroyed.
|
|
|
|
template <typename T>
|
|
|
|
class AutoClose {
|
|
|
|
public:
|
2017-12-07 04:48:06 +03:00
|
|
|
AutoClose() : mMutex("net::AutoClose.mMutex") {}
|
|
|
|
~AutoClose() { CloseAndRelease(); }
|
2014-06-19 04:56:02 +04:00
|
|
|
|
2017-12-07 04:48:06 +03:00
|
|
|
explicit operator bool() {
|
|
|
|
MutexAutoLock lock(mMutex);
|
2012-06-28 23:18:25 +04:00
|
|
|
return mPtr;
|
|
|
|
}
|
2014-06-19 04:56:02 +04:00
|
|
|
|
2012-06-28 23:18:25 +04:00
|
|
|
already_AddRefed<T> forget() {
|
2017-12-07 04:48:06 +03:00
|
|
|
MutexAutoLock lock(mMutex);
|
2012-06-28 23:18:25 +04:00
|
|
|
return mPtr.forget();
|
|
|
|
}
|
2014-06-19 04:56:02 +04:00
|
|
|
|
2018-09-21 23:45:49 +03:00
|
|
|
void takeOver(nsCOMPtr<T>& rhs) { TakeOverInternal(rhs.forget()); }
|
2014-06-19 04:56:02 +04:00
|
|
|
|
2017-12-07 04:48:06 +03:00
|
|
|
void CloseAndRelease() { TakeOverInternal(nullptr); }
|
2014-06-19 04:56:02 +04:00
|
|
|
|
2012-06-28 23:18:25 +04:00
|
|
|
private:
|
2018-09-21 23:45:49 +03:00
|
|
|
void TakeOverInternal(already_AddRefed<T>&& aOther) {
|
|
|
|
nsCOMPtr<T> ptr(std::move(aOther));
|
2017-12-07 04:48:06 +03:00
|
|
|
{
|
|
|
|
MutexAutoLock lock(mMutex);
|
|
|
|
ptr.swap(mPtr);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (ptr) {
|
|
|
|
ptr->Close();
|
2012-06-28 23:18:25 +04:00
|
|
|
}
|
|
|
|
}
|
2014-06-19 04:56:02 +04:00
|
|
|
|
2015-01-07 02:35:02 +03:00
|
|
|
void operator=(const AutoClose<T>&) = delete;
|
|
|
|
AutoClose(const AutoClose<T>&) = delete;
|
2014-06-19 04:56:02 +04:00
|
|
|
|
2012-06-28 23:18:25 +04:00
|
|
|
nsCOMPtr<T> mPtr;
|
2017-12-07 04:48:06 +03:00
|
|
|
Mutex mMutex;
|
2012-06-28 23:18:25 +04:00
|
|
|
};
|
2014-06-19 04:56:02 +04:00
|
|
|
|
2015-07-13 18:25:42 +03:00
|
|
|
} // namespace net
|
|
|
|
} // namespace mozilla
|
2014-06-19 04:56:02 +04:00
|
|
|
|
2012-06-28 23:18:25 +04:00
|
|
|
#endif // mozilla_net_AutoClose_h
|