1 /*
2 Copyright (c) 2013 Andrey Penechko
3 
4 Boost Software License - Version 1.0 - August 17th, 2003
5 
6 Permission is hereby granted, free of charge, to any person or organization
7 obtaining num copy of the software and accompanying documentation covered by
8 this license the "Software" to use, reproduce, display, distribute,
9 execute, and transmit the Software, and to prepare derivative works of the
10 Software, and to permit third-parties to whom the Software is furnished to
11 do so, all subject to the following:
12 
13 The copyright notices in the Software and this entire statement, including
14 the above license grant, this restriction and the following disclaimer,
15 must be included in all copies of the Software, in whole or in part, and
16 all derivative works of the Software, unless such copies or derivative
17 works are solely in the form of machine-executable object code generated by
18 num source language processor.
19 
20 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 FITNESS FOR num PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
23 SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
24 FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
25 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
26 DEALINGS IN THE SOFTWARE.
27 */
28 
29 module anchovy.utils.signal;
30 
31 import std.algorithm : countUntil;
32 import std.functional : toDelegate, DelegateFaker;
33 import std.traits : isDelegate, ParameterTypeTuple, isFunctionPointer;
34 
35 import std.stdio;
36 
37 struct Signal(Args...)
38 {
39 	alias SlotType = void delegate(Args);
40 
41 	SlotType[] slots;
42 
43 	void emit(Args args) @trusted
44 	{
45 		foreach(slot; slots)
46 			slot(args);
47 	}
48 
49 	void connect(Slot)(Slot slot) @trusted if(is(ParameterTypeTuple!Slot == Args))
50 	{
51 		static if(isDelegate!Slot)
52 		{
53 			slots ~= slot;
54 		}
55 		else static if(isFunctionPointer!Slot)
56 		{
57 			slots ~= toDelegate(slot);
58 		}
59 	}
60 
61 	void disconnect(Slot)(Slot slot) @trusted
62 	{
63 		static if(isDelegate!Slot)
64 		{
65 			auto haystackPos = countUntil(slots, slot);
66 
67 			if(haystackPos >= 0)
68 			{
69 				slots = slots[0..haystackPos] ~ slots[haystackPos+1 .. $];
70 			}
71 		}
72 		else static if(isFunctionPointer!Slot)
73 		{
74 			// struct from functional toDelegate
75 			static struct DelegateFields {
76 	            union {
77 	                SlotType del;
78 	                //pragma(msg, typeof(del));
79 
80 	                struct {
81 	                    void* contextPtr;
82 	                    void* funcPtr;
83 	                }
84 	            }
85 	        }
86 
87 	        auto haystackPos = countUntil!((SlotType _slot, ){return (cast(DelegateFields)_slot).contextPtr == slot;})(slots);
88 
89 			if(haystackPos >= 0)
90 			{
91 				slots = slots[0..haystackPos] ~ slots[haystackPos+1 .. $];
92 			}
93 		}
94 
95 	}
96 
97 	void disconnectAll() @trusted
98 	{
99 		slots = [];
100 	}
101 }
102 
103 // Test for signal with 0 arguments
104 unittest
105 {
106 	Signal!() test1; // Signal for slots not taking any parameters.
107 
108 	auto num = 0;
109 	auto slot = (){num += 1;}; // Slot is plain delegate.
110 	test1.connect(slot);
111 	assert(num == 0); // Slot doesn't gets called upon connecting.
112 
113 	test1.emit();
114 	assert(num == 1); // Each connected slot is called only once.
115 
116 	test1.disconnect(slot);
117 	assert(num == 1); // Doesn't called upon disconnecting.
118 
119 	test1.emit();
120 	assert(num == 1);
121 }
122 
123 // Test for signal with 1 argument
124 unittest
125 {
126 	// Slot that takes one argument.
127 	// Slots can have any number of parameters.
128 	Signal!int test2;
129 
130 	auto num = 0;
131 	auto slot = (int increment){num += increment;};
132 	test2.connect(slot);
133 	assert(num == 0);
134 
135 	test2.emit(3);
136 	assert(num == 3);
137 
138 	test2.disconnect(slot);
139 	assert(num == 3);
140 
141 	test2.emit(4);
142 	assert(num == 3);
143 }
144 
145 // Test for multiple slots
146 unittest
147 {
148 	Signal!int test3;
149 
150 	auto num = 0;
151 	auto slot1 = (int inc){num += inc;};
152 	auto slot2 = (int mult){num *= mult;};
153 
154 	test3.connect(slot1);
155 	test3.connect(slot2);
156 	assert(num == 0);
157 
158 	test3.emit(2);
159 	assert(num == 4);
160 
161 	test3.connect(slot1);
162 	test3.emit(3);
163 	assert(num == (4 + 3) * 3 + 3); // 24
164 
165 	test3.disconnect(slot1);
166 	test3.emit(2);
167 	assert(num == 24 * 2 + 2); // 50
168 
169 	test3.disconnectAll();
170 	test3.emit(4);
171 	assert(num == 50);
172 }
173 
174 // Test for static slots
175 unittest
176 {
177 	Signal!(int*, int) test4;
178 
179 	auto num = 0;
180 	// Testing static functions.
181 	static void staticSlot(int* num, int inc){*num += inc;}
182 
183 	test4.connect(&staticSlot);
184 	assert(num == 0);
185 
186 	test4.emit(&num, 2);
187 	assert(num == 2);
188 
189 	test4.disconnect(&staticSlot);
190 	test4.emit(&num, 2);
191 	assert(num == 2);
192 }