2019-01-02 19:48:05 +01:00
|
|
|
// Matrix Construct
|
|
|
|
//
|
|
|
|
// Copyright (C) Matrix Construct Developers, Authors & Contributors
|
|
|
|
// Copyright (C) 2016-2019 Jason Volk <jason@zemos.net>
|
|
|
|
//
|
|
|
|
// Permission to use, copy, modify, and/or distribute this software for any
|
|
|
|
// purpose with or without fee is hereby granted, provided that the above
|
|
|
|
// copyright notice and this permission notice is present in all copies. The
|
|
|
|
// full license for this software is available in the LICENSE file.
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
#define HAVE_IRCD_UTIL_SCOPE_COUNT_H
|
|
|
|
|
2019-06-23 10:01:26 +02:00
|
|
|
namespace ircd {
|
|
|
|
inline namespace util
|
2019-01-02 19:48:05 +01:00
|
|
|
{
|
2019-02-28 22:23:09 +01:00
|
|
|
template<class T> struct scope_count;
|
2020-05-29 00:17:05 +02:00
|
|
|
}}
|
2019-01-02 19:48:05 +01:00
|
|
|
|
2020-05-29 00:17:05 +02:00
|
|
|
/// Increment a counter when constructed and decrement it when destructed.
|
|
|
|
/// This takes a runtime reference to that counter. The counter thus maintains
|
|
|
|
/// the number of reentrances (or entrances across different contexts).
|
|
|
|
///
|
2019-02-28 22:23:09 +01:00
|
|
|
template<class T>
|
2019-01-02 19:48:05 +01:00
|
|
|
struct ircd::util::scope_count
|
|
|
|
{
|
2019-02-28 22:23:09 +01:00
|
|
|
T *count {nullptr};
|
2020-05-07 02:30:12 +02:00
|
|
|
T inc {1};
|
2019-01-02 19:48:05 +01:00
|
|
|
|
2020-05-07 02:30:12 +02:00
|
|
|
scope_count(T &count, const T & = 1);
|
2019-01-02 19:48:05 +01:00
|
|
|
scope_count(const scope_count &) = delete;
|
|
|
|
scope_count(scope_count &&) noexcept = delete;
|
|
|
|
~scope_count() noexcept;
|
|
|
|
};
|
|
|
|
|
2019-02-28 22:23:09 +01:00
|
|
|
template<class T>
|
2020-05-07 02:30:12 +02:00
|
|
|
ircd::util::scope_count<T>::scope_count(T &count,
|
|
|
|
const T &inc)
|
2019-01-02 19:48:05 +01:00
|
|
|
:count{&count}
|
2020-05-07 02:30:12 +02:00
|
|
|
,inc{inc}
|
2019-01-02 19:48:05 +01:00
|
|
|
{
|
2020-05-07 02:30:12 +02:00
|
|
|
count += inc;
|
2019-01-02 19:48:05 +01:00
|
|
|
}
|
|
|
|
|
2019-02-28 22:23:09 +01:00
|
|
|
template<class T>
|
|
|
|
ircd::util::scope_count<T>::~scope_count()
|
2019-01-02 19:48:05 +01:00
|
|
|
noexcept
|
|
|
|
{
|
|
|
|
assert(count);
|
2020-05-07 02:30:12 +02:00
|
|
|
(*count) -= inc;
|
2019-01-02 19:48:05 +01:00
|
|
|
}
|