netwerk/base/AutoClose.h
author Mozilla Releng Treescript <release+treescript@mozilla.org>
Tue, 16 Aug 2022 19:03:11 +0000
changeset 627318 a51ffdf576ee6dde088f4a39c8e0d7d37844a830
parent 610788 1a24671d0ce8770da8c215250b415c423b796b34
permissions -rw-r--r--
no bug - Bumping Firefox l10n changesets r=release a=l10n-bump DONTBUILD cy -> fe475b7bab2af983d4cee8e65e4972bfbcf66cec en-CA -> a3ef65c7edaf9177bc6d86a575da123b8724a329 en-GB -> a5a0d021121c2b7a8df335e57bfb0b432f7c7ca4 fr -> 4970122e206d2d09f9c62e143b6c762f0cbe1a9a fy-NL -> 291db3aaa83f252be9f5da671b265bb6fb45a28c gn -> 788acda2302098b31a0812bac3041737be91f8e3 it -> 12c20d432cac1df7c787e5c3d3aa112079c2378d nn-NO -> 2b14fbbce8aab53ad5eebbe7c2f13022a0fddd0f si -> 579629b003e5dd54eefdef80b4fd0c41bc167ee7 tr -> 1ace5ae3f35fafb4c08e4f2c6b43f87716f2bd7e

/* -*- 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,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_net_AutoClose_h
#define mozilla_net_AutoClose_h

#include "nsCOMPtr.h"
#include "mozilla/Mutex.h"

namespace mozilla {
namespace net {

// A container for XPCOM streams (e.g. nsIAsyncInputStream) and other
// refcounted classes that need to have the Close() method called explicitly
// before they are destroyed.
template <typename T>
class AutoClose {
 public:
  AutoClose() : mMutex("net::AutoClose.mMutex") {}
  ~AutoClose() { CloseAndRelease(); }

  explicit operator bool() {
    MutexAutoLock lock(mMutex);
    return mPtr;
  }

  already_AddRefed<T> forget() {
    MutexAutoLock lock(mMutex);
    return mPtr.forget();
  }

  void takeOver(nsCOMPtr<T>& rhs) { TakeOverInternal(rhs.forget()); }

  void CloseAndRelease() { TakeOverInternal(nullptr); }

 private:
  void TakeOverInternal(already_AddRefed<T>&& aOther) {
    nsCOMPtr<T> ptr(std::move(aOther));
    {
      MutexAutoLock lock(mMutex);
      ptr.swap(mPtr);
    }

    if (ptr) {
      ptr->Close();
    }
  }

  void operator=(const AutoClose<T>&) = delete;
  AutoClose(const AutoClose<T>&) = delete;

  nsCOMPtr<T> mPtr;
  Mutex mMutex MOZ_UNANNOTATED;
};

}  // namespace net
}  // namespace mozilla

#endif  // mozilla_net_AutoClose_h