LCOV - code coverage report
Current view: top level - src/util - btcsignals.h (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 98.1 % 53 52
Test Date: 2026-11-25 06:45:13 Functions: 69.6 % 112 78
Branches: 32.2 % 366 118

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #ifndef BITCOIN_UTIL_BTCSIGNALS_H
       6                 :             : #define BITCOIN_UTIL_BTCSIGNALS_H
       7                 :             : 
       8                 :             : #include <sync.h>
       9                 :             : 
      10                 :             : #include <algorithm>
      11                 :             : #include <atomic>
      12                 :             : #include <functional>
      13                 :             : #include <memory>
      14                 :             : #include <optional>
      15                 :             : #include <type_traits>
      16                 :             : #include <utility>
      17                 :             : #include <vector>
      18                 :             : 
      19                 :             : /**
      20                 :             :  * btcsignals is a simple mechanism for signaling events to multiple subscribers.
      21                 :             :  * It is api-compatible with a minimal subset of boost::signals2.
      22                 :             :  *
      23                 :             :  * Rather than using a custom slot type, and the features/complexity that they
      24                 :             :  * imply, std::function is used to store the callbacks. There is no automatic
      25                 :             :  * tracking of objects the callbacks refer to, so callers need to disconnect
      26                 :             :  * callbacks before those objects are destroyed.
      27                 :             :  *
      28                 :             :  * Like boost::signals2, disconnecting a connection destroys its callback
      29                 :             :  * object, or if the callback is running at the time, destroys it when the
      30                 :             :  * call returns. Callbacks that are never disconnected are destroyed with the
      31                 :             :  * signal.
      32                 :             :  *
      33                 :             :  * All usage is thread-safe except for interacting with a connection while
      34                 :             :  * copying/moving it on another thread.
      35                 :             :  */
      36                 :             : 
      37                 :             : namespace btcsignals {
      38                 :             : 
      39                 :             : /// The default combiner, which only returns void.
      40                 :             : class null_value
      41                 :             : {
      42                 :             : public:
      43                 :             :     using result_type = void;
      44                 :             : };
      45                 :             : 
      46                 :             : /// A combiner, which checks if at least one callback returned true.
      47                 :             : class any_of
      48                 :             : {
      49                 :             : public:
      50                 :             :     // This is the only supported combiner with a non-void return type. As
      51                 :             :     // such, its behavior is embedded into the signal functor.
      52                 :             :     using result_type = bool;
      53                 :             : };
      54                 :             : 
      55                 :             : template <typename Signature, typename Combiner = null_value>
      56                 :             : class signal;
      57                 :             : 
      58                 :             : namespace detail {
      59                 :             : #ifdef __cpp_lib_atomic_shared_ptr
      60                 :             : template <typename T>
      61                 :             : using atomic_shared_ptr = std::atomic<std::shared_ptr<T>>;
      62                 :             : #else
      63                 :             : //! Substitute for the C++20 std::atomic<std::shared_ptr<T>> specialization on
      64                 :             : //! standard libraries that do not provide it yet (feature-test macro
      65                 :             : //! __cpp_lib_atomic_shared_ptr), implemented with the C++11 atomic_load and
      66                 :             : //! atomic_store overloads for shared_ptr. Only the members used here are
      67                 :             : //! provided.
      68                 :             : template <typename T>
      69                 :             : class atomic_shared_ptr
      70                 :             : {
      71                 :             :     std::shared_ptr<T> m_ptr;
      72                 :             : 
      73                 :             : public:
      74                 :             :     explicit atomic_shared_ptr(std::shared_ptr<T> ptr) noexcept : m_ptr{std::move(ptr)} {}
      75                 :             :     atomic_shared_ptr(const atomic_shared_ptr&) = delete;
      76                 :             :     atomic_shared_ptr& operator=(const atomic_shared_ptr&) = delete;
      77                 :             :     std::shared_ptr<T> load() const noexcept { return std::atomic_load(&m_ptr); }
      78                 :             :     void store(std::shared_ptr<T> ptr) noexcept { std::atomic_store(&m_ptr, std::move(ptr)); }
      79                 :             : };
      80                 :             : #endif
      81                 :             : } // namespace detail
      82                 :             : 
      83                 :             : /*
      84                 :             :  * State object representing the liveness of a registered callback.
      85                 :             :  * signal::connect() returns an enabled connection which can be held and
      86                 :             :  * disabled in the future.
      87                 :             :  */
      88   [ -  +  +  -  :       30385 : class connection
          -  +  +  +  -  
          +  +  +  +  -  
          +  -  +  -  -  
          -  -  -  -  -  
          -  +  +  -  -  
          +  +  -  -  +  
          +  -  +  -  +  
          -  +  -  -  -  
          -  -  -  -  -  
          +  +  -  +  -  
          -  -  +  -  -  
          -  -  +  +  -  
          +  -  -  -  +  
          -  -  +  +  -  
          +  -  -  -  -  
          +  +  -  -  +  
          +  -  +  -  +  
          -  +  -  -  -  
          -  -  +  -  +  
             -  +  -  +  
           - ][ +  -  -  
          -  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
           # ][ +  +  +  
          +  +  +  -  +  
             -  +  -  + ]
           [ #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  #  
           # ][ #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
              # ][ #  # ]
           [ #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  #  
                      # ]
      89                 :             : {
      90                 :             :     template <typename Signature, typename Combiner>
      91                 :             :     friend class signal;
      92                 :             :     /**
      93                 :             :      * Track liveness. Also serves as a tag for the constructor used by signal.
      94                 :             :      */
      95                 :       49182 :     class liveness
      96                 :             :     {
      97                 :             :         friend class connection;
      98                 :             : 
      99                 :             :         //! Callback object, type-erased so connection does not depend on the
     100                 :             :         //! signal type, and set to null by disconnect(). Signal invocation
     101                 :             :         //! holds a reference to it while calling it, so a callback
     102                 :             :         //! disconnected during a call is destroyed when the call returns.
     103                 :             :         detail::atomic_shared_ptr<const void> m_callback;
     104                 :             : 
     105         [ +  + ]:        1439 :         void disconnect() { m_callback.store(nullptr); }
     106                 :             : 
     107                 :             :     protected:
     108                 :       24591 :         explicit liveness(std::shared_ptr<const void> callback) : m_callback{std::move(callback)} {}
     109                 :             : 
     110                 :     1089968 :         std::shared_ptr<const void> load() const { return m_callback.load(); }
     111                 :             : 
     112                 :             :     public:
     113         [ +  + ]:      263256 :         bool connected() const { return load() != nullptr; }
     114                 :             :     };
     115                 :             : 
     116                 :             :     /**
     117                 :             :      * connections have shared_ptr-like copy and move semantics.
     118                 :             :      */
     119                 :             :     std::shared_ptr<liveness> m_state{};
     120                 :             : 
     121                 :             :     /**
     122                 :             :      * Only a signal can create an enabled connection.
     123                 :             :      */
     124                 :       24591 :     explicit connection(std::shared_ptr<liveness>&& state) : m_state{std::move(state)}{}
     125                 :             : 
     126                 :             : public:
     127                 :             :     /**
     128                 :             :      * The default constructor creates a connection with no associated signal
     129                 :             :      */
     130                 :             :     constexpr connection() noexcept = default;
     131                 :             : 
     132                 :             :     /**
     133                 :             :      * If a callback is associated with this connection, prevent it from being
     134                 :             :      * called in the future.
     135                 :             :      *
     136                 :             :      * If a connection is disabled as part of a signal's callback function, it
     137                 :             :      * will _not_ be executed in the current signal invocation.
     138                 :             :      *
     139                 :             :      * The callback object is destroyed here (or when the last concurrently
     140                 :             :      * executing invocation of it completes). The empty holder entry is not
     141                 :             :      * removed from the owning signal; it is garbage collected in
     142                 :             :      * signal::connect().
     143                 :             :      */
     144                 :        1939 :     void disconnect()
     145                 :             :     {
     146   [ +  -  +  -  :         434 :         if (m_state) {
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
           +  - ][ +  - ]
           [ +  -  +  -  
          +  -  +  -  +  
                -  +  - ]
     147                 :        1439 :             m_state->disconnect();
     148                 :             :         }
     149                 :             :     }
     150                 :             : 
     151                 :             :     /**
     152                 :             :      * Returns true if this connection was created by a signal and has not been
     153                 :             :      * disabled.
     154                 :             :      */
     155                 :        1019 :     bool connected() const
     156                 :             :     {
     157   [ +  +  +  + ]:        1019 :         return m_state && m_state->connected();
     158                 :             :     }
     159                 :             : };
     160                 :             : 
     161                 :             : /*
     162                 :             :  * RAII-style connection management
     163                 :             :  */
     164                 :             : class scoped_connection
     165                 :             : {
     166                 :             :     connection m_conn;
     167                 :             : 
     168                 :             : public:
     169   [ +  +  +  -  :        1003 :     explicit scoped_connection(connection rhs) noexcept : m_conn{std::move(rhs)} {}
             +  -  +  - ]
     170                 :             : 
     171                 :         500 :     scoped_connection(scoped_connection&&) noexcept = default;
     172                 :             : 
     173                 :             :     /**
     174                 :             :      * For simplicity, disable copy construction and copy/move assignment.
     175                 :             :      */
     176                 :             :     scoped_connection& operator=(scoped_connection&&) = delete;
     177                 :             :     scoped_connection& operator=(const scoped_connection&) = delete;
     178                 :             :     scoped_connection(const scoped_connection&) = delete;
     179                 :             : 
     180                 :        1505 :     void disconnect()
     181                 :             :     {
     182   [ +  -  +  - ]:           2 :         m_conn.disconnect();
                 [ #  # ]
     183                 :             :     }
     184                 :             : 
     185                 :        1504 :     ~scoped_connection()
     186                 :             :     {
     187         [ +  + ]:        1504 :         disconnect();
     188         [ +  + ]:        1504 :     }
     189                 :             : };
     190                 :             : 
     191                 :             : /*
     192                 :             :  * Functor for calling zero or more connected callbacks
     193                 :             :  */
     194                 :             : template <typename Signature, typename Combiner>
     195                 :             : class signal
     196                 :             : {
     197                 :             :     using function_type = std::function<Signature>;
     198                 :             : 
     199                 :             :     /*
     200                 :             :      * Helper struct for maintaining a callback and its associated connection liveness
     201                 :             :      */
     202                 :       24591 :     struct connection_holder : connection::liveness {
     203                 :             :         template <typename Callable>
     204                 :       24591 :         explicit connection_holder(Callable&& callback)
     205   [ -  +  -  + ]:       24591 :             : liveness{std::make_shared<const function_type>(std::forward<Callable>(callback))}
     206                 :             :         {
     207                 :       24591 :         }
     208                 :             : 
     209                 :             :         //! Return the callback, or null if disconnected. The callback stays
     210                 :             :         //! alive while the returned pointer is held.
     211                 :      281728 :         std::shared_ptr<const function_type> callback() const
     212                 :             :         {
     213         [ -  + ]:      281728 :             return std::static_pointer_cast<const function_type>(load());
     214                 :             :         }
     215                 :             :     };
     216                 :             : 
     217                 :             :     mutable Mutex m_mutex;
     218                 :             : 
     219                 :             :     std::vector<std::shared_ptr<connection_holder>> m_connections GUARDED_BY(m_mutex){};
     220                 :             : 
     221                 :             : public:
     222                 :             :     using result_type = Combiner::result_type;
     223                 :             : 
     224                 :        9795 :     constexpr signal() noexcept = default;
     225   [ +  -  +  -  :        9805 :     ~signal() = default;
             +  -  +  - ]
     226                 :             : 
     227                 :             :     /*
     228                 :             :      * For simplicity, disable all moving/copying/assigning.
     229                 :             :      */
     230                 :             :     signal(const signal&) = delete;
     231                 :             :     signal(signal&&) = delete;
     232                 :             :     signal& operator=(const signal&) = delete;
     233                 :             :     signal& operator=(signal&&) = delete;
     234                 :             : 
     235                 :             :     /*
     236                 :             :      * Execute all enabled callbacks for the signal. Rather than allowing for
     237                 :             :      * custom combiners, the behavior of any_of is hard-coded here.
     238                 :             :      *
     239                 :             :      * Callbacks which return void require special handling.
     240                 :             :      *
     241                 :             :      * In order to avoid locking during the callbacks, the list of callbacks is
     242                 :             :      * cached before they are called. This allows a callback to call connect(),
     243                 :             :      * but the newly connected callback will not be run during the current
     244                 :             :      * signal invocation.
     245                 :             :      *
     246                 :             :      * Note that the parameters are accepted as universal references, though
     247                 :             :      * they are not perfectly forwarded as that could cause a use-after-move if
     248                 :             :      * more than one callback is enabled.
     249                 :             :      */
     250                 :             :     template <typename... Args>
     251                 :      322193 :     [[nodiscard]] result_type operator()(Args&&... args) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
     252                 :             :     {
     253                 :      322193 :         std::vector<std::shared_ptr<connection_holder>> connections;
     254                 :             :         {
     255         [ +  - ]:      322193 :             LOCK(m_mutex);
     256         [ +  - ]:      322193 :             connections = m_connections;
     257                 :           0 :         }
     258                 :             :         if constexpr (std::is_void_v<result_type>) {
     259                 :             :             static_assert(std::is_same_v<result_type, typename function_type::result_type>,
     260                 :             :                           "Callback result type must be equal to the combiner result type (void).");
     261         [ +  + ]:      603885 :             for (const auto& connection : connections) {
     262                 :             :                 // Holding the callback pointer keeps the callback alive until
     263                 :             :                 // the call returns, even if it is disconnected concurrently.
     264         [ +  + ]:      563418 :                 if (const auto callback{connection->callback()}) {
     265         [ +  - ]:      295953 :                     (*callback)(args...);
           [ +  -  +  - ]
     266                 :             :                 }
     267                 :             :             }
     268                 :             :         } else {
     269                 :             :             static_assert(std::is_same_v<Combiner, any_of>,
     270                 :             :                           "only the any_of combiner is supported and hard-coded into this functor.");
     271                 :             :             static_assert(std::is_same_v<result_type, typename function_type::result_type>,
     272                 :             :                           "Callback result type must be equal to the combiner result type (bool).");
     273                 :          17 :             result_type ret{false};
     274         [ +  + ]:          36 :             for (const auto& connection : connections) {
     275         [ +  + ]:          38 :                 if (const auto callback{connection->callback()}) {
     276         [ +  - ]:          15 :                     ret |= (*callback)(args...);
     277                 :             :                 }
     278                 :             :             }
     279                 :          17 :             return ret;
     280                 :             :         }
     281                 :      322193 :     }
     282                 :             : 
     283                 :             :     /*
     284                 :             :      * Connect a new callback to the signal. A forwarding callable accepts
     285                 :             :      * anything that can be stored in a std::function.
     286                 :             :      */
     287                 :             :     template <typename Callable>
     288                 :       24591 :     connection connect(Callable&& func) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
     289                 :             :     {
     290                 :       24591 :         LOCK(m_mutex);
     291                 :             : 
     292                 :             :         // Garbage-collect disconnected connections to prevent unbounded growth
     293                 :      285314 :         std::erase_if(m_connections, [](const auto& holder) { return !holder->connected(); });
     294                 :             : 
     295   [ +  -  +  -  :       24591 :         const auto& entry = m_connections.emplace_back(std::make_shared<connection_holder>(std::forward<Callable>(func)));
             -  +  +  - ]
     296         [ +  - ]:       24591 :         return connection(entry);
     297                 :       24591 :     }
     298                 :             : 
     299                 :             :     /*
     300                 :             :      * Returns true if there are no enabled callbacks
     301                 :             :      */
     302                 :        2251 :     [[nodiscard]] bool empty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
     303                 :             :     {
     304                 :        2251 :         LOCK(m_mutex);
     305         [ +  - ]:        3766 :         return std::ranges::none_of(m_connections, [](const auto& holder) {
     306                 :        1515 :             return holder->connected();
     307                 :        2251 :         });
     308                 :        2251 :     }
     309                 :             : };
     310                 :             : 
     311                 :             : } // namespace btcsignals
     312                 :             : 
     313                 :             : #endif // BITCOIN_UTIL_BTCSIGNALS_H
        

Generated by: LCOV version 2.0-1