Skip to content

Commit

Permalink
Implemented generic callback functionality for alerts.
Browse files Browse the repository at this point in the history
  • Loading branch information
joriscarrier committed Nov 18, 2023
1 parent 9c18976 commit 154c7e6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
20 changes: 20 additions & 0 deletions include/libtorrent/alert.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Copyright (c) 2003, Daniel Wallin
Copyright (c) 2004-2005, 2008-2009, 2013-2020, 2022, Arvid Norberg
Copyright (c) 2004, Magnus Jonsson
Copyright (c) 2016, Alden Torres
Copyright (c) 2023, Joris Carrier
All rights reserved.
Redistribution and use in source and binary forms, with or without
Expand Down Expand Up @@ -37,6 +38,7 @@ POSSIBILITY OF SUCH DAMAGE.
#define TORRENT_ALERT_HPP_INCLUDED

#include <string>
#include <functional>

// OVERVIEW
//
Expand Down Expand Up @@ -186,6 +188,24 @@ namespace alert_category {

#include "libtorrent/aux_/disable_deprecation_warnings_push.hpp"

template<typename T>
struct TORRENT_EXPORT callback_t {
using type = std::function<void(const T*)>;

callback_t(type func) : m_callback(std::move(func)) {}

bool has_callback() const {
return static_cast<bool>(m_callback);
}

void callback() {
m_callback(static_cast<const T*>(this));
}

private:
type m_callback;
};

// The ``alert`` class is the base class that specific messages are derived from.
// alert types are not copyable, and cannot be constructed by the client. The
// pointers returned by libtorrent are short lived (the details are described
Expand Down
5 changes: 5 additions & 0 deletions include/libtorrent/aux_/alert_manager.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
Copyright (c) 2003-2013, Daniel Wallin
Copyright (c) 2013, 2015-2020, Arvid Norberg
Copyright (c) 2016, 2018, 2020, Alden Torres
Copyright (c) 2023, Joris Carrier
All rights reserved.
Redistribution and use in source and binary forms, with or without
Expand Down Expand Up @@ -88,6 +89,10 @@ namespace aux {
T& alert = queue.emplace_back<T>(
m_allocations[m_generation], std::forward<Args>(args)...);

if constexpr (std::is_base_of<callback_t<T>, T>::value) {
if (alert.has_callback()) alert.callback();
}

maybe_notify(&alert);
}
catch (std::bad_alloc const&)
Expand Down

0 comments on commit 154c7e6

Please sign in to comment.