comparison foosdk/sdk/pfc/notifyList.h @ 1:20d02a178406 default tip

*: check in everything else yay
author Paper <paper@tflc.us>
date Mon, 05 Jan 2026 02:15:46 -0500
parents
children
comparison
equal deleted inserted replaced
0:e9bb126753e7 1:20d02a178406
1 #pragma once
2
3 #include <functional>
4 #include <map>
5 #include <memory>
6
7 namespace pfc {
8 class notifyList {
9 public:
10
11 typedef size_t token_t;
12
13 typedef std::function<void () > notify_t;
14 token_t add( notify_t f ) {
15 auto token = ++ m_increment;
16 m_notify[token] = f;
17 return token;
18 }
19
20 void remove( token_t t ) {
21 m_notify.erase(t);
22 }
23
24 void dispatch() {
25 // Safeguard against someone altering our state in mid-dispatch
26 auto temp = m_notify;
27 for( auto walk = temp.begin(); walk != temp.end(); ++ walk ) {
28 if ( m_notify.count( walk->first ) > 0 ) { // still there?
29 walk->second();
30 }
31 }
32 }
33
34
35 static std::shared_ptr<notifyList> make() {
36 return std::make_shared<notifyList>();
37 }
38 private:
39 token_t m_increment = 0;
40
41 std::map<token_t, notify_t> m_notify;
42 };
43
44 typedef std::shared_ptr< notifyList > notifyListRef_t;
45
46 class notifyEntry {
47 public:
48 notifyEntry() {}
49
50 notifyEntry & operator<<( notifyList & l ) {
51 PFC_ASSERT( m_list == nullptr );
52 m_list = &l;
53 return *this;
54 }
55 notifyEntry & operator<<( notifyListRef_t l ) {
56 PFC_ASSERT( m_list == nullptr );
57 m_listShared = l;
58 m_list = &*l;
59 return *this;
60 }
61 notifyEntry & operator<<( notifyList::notify_t f ) {
62 PFC_ASSERT( m_list != nullptr );
63 PFC_ASSERT( m_token == 0 );
64 m_token = m_list->add( f );
65 return *this;
66 }
67 void clear() {
68 if ( m_list != nullptr && m_token != 0 ) {
69 m_list->remove(m_token);
70 m_token = 0;
71 }
72 }
73 ~notifyEntry() {
74 clear();
75 }
76
77 private:
78 notifyListRef_t m_listShared;
79 notifyList * m_list = nullptr;
80 notifyList::token_t m_token = 0;
81
82 notifyEntry( const notifyEntry & ) = delete;
83 void operator=( const notifyEntry & ) = delete;
84 };
85 }