1+ using System ;
2+ using System . Collections . Generic ;
3+
4+ namespace Simulation
5+ {
6+ /// <summary>
7+ /// Dispatches messages for static methods with the <see cref="ListenerAttribute{T}"/>.
8+ /// </summary>
9+ public static class GlobalSimulator
10+ {
11+ private static readonly List < Action > clearFunctions = new ( ) ;
12+
13+ /// <summary>
14+ /// Registers a listener for messages of type <typeparamref name="T"/>.
15+ /// </summary>
16+ public static void Register < T > ( Receive < T > receive ) where T : unmanaged
17+ {
18+ Array . Resize ( ref Listeners < T > . list , Listeners < T > . list . Length + 1 ) ;
19+ Listeners < T > . list [ ^ 1 ] = receive ;
20+ }
21+
22+ /// <summary>
23+ /// Registers a <paramref name="listener"/>.
24+ /// </summary>
25+ public static void Register < T > ( IListener < T > listener ) where T : unmanaged
26+ {
27+ Receive < T > receive = listener . Receive ;
28+ Array . Resize ( ref Listeners < T > . list , Listeners < T > . list . Length + 1 ) ;
29+ Listeners < T > . list [ ^ 1 ] = receive ;
30+ }
31+
32+ /// <summary>
33+ /// Resets the global simulator to initial state, with no listeners registered.
34+ /// </summary>
35+ public static void Reset ( )
36+ {
37+ foreach ( Action clearFunction in clearFunctions )
38+ {
39+ clearFunction ( ) ;
40+ }
41+ }
42+
43+ /// <summary>
44+ /// Broadcasts the given <paramref name="message"/>.
45+ /// </summary>
46+ public static void Broadcast < T > ( T message ) where T : unmanaged
47+ {
48+ int length = Listeners < T > . list . Length ;
49+ for ( int i = 0 ; i < length ; i ++ )
50+ {
51+ Listeners < T > . list [ i ] ( ref message ) ;
52+ }
53+ }
54+
55+ /// <summary>
56+ /// Broadcasts the given <paramref name="message"/>.
57+ /// </summary>
58+ public static void Broadcast < T > ( ref T message ) where T : unmanaged
59+ {
60+ int length = Listeners < T > . list . Length ;
61+ for ( int i = 0 ; i < length ; i ++ )
62+ {
63+ Listeners < T > . list [ i ] ( ref message ) ;
64+ }
65+ }
66+
67+ private static class Listeners < T > where T : unmanaged
68+ {
69+ public static Receive < T > [ ] list = [ ] ;
70+
71+ static Listeners ( )
72+ {
73+ clearFunctions . Add ( Reset ) ;
74+ }
75+
76+ public static void Reset ( )
77+ {
78+ Array . Resize ( ref list , 0 ) ;
79+ }
80+ }
81+
82+ /// <summary>
83+ /// Delegate for message receivers.
84+ /// </summary>
85+ public delegate void Receive < T > ( ref T message ) where T : unmanaged;
86+ }
87+ }
0 commit comments