-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathchannel.d
136 lines (101 loc) · 2.27 KB
/
channel.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
module jin.go.channel;
public import jin.go.output;
public import jin.go.input;
/// Common `Queue` collections implementation.
mixin template Channel(Message)
{
import jin.go.queue;
alias Self = typeof(this);
/// Allow transferring between tasks.
enum __isIsolatedType = true;
/// Destructor is disabled when `true`.
bool immortal;
/// All registered Queues.
Queue!Message[] queues;
/// Index of current Queue.
private size_t current;
/// O(1) Remove current queue.
private void currentUnlink()
{
if (this.current + 1 < this.queues.length)
{
this.queues[this.current] = this.queues.back;
this.queues.popBack;
return;
}
this.queues.popBack;
this.current = 0;
}
/// Makes new registered `Queue` and returns `Pair` channel.
/// Maximum count of messages in a buffer can be provided.
Pair!Message pair()
{
auto queue = new Queue!Message;
this.queues ~= queue;
Pair!Message pair;
pair.queues ~= queue;
return pair;
}
@disable this(this);
this( ref Self source ) {
this.queues ~= source.queues;
source.queues.length = 0;
}
void opOpAssign(string op: "~")(Self source) {
this.queues ~= source.queues;
source.queues.length = 0;
}
}
/// Autofinalize and take all.
unittest
{
auto ii = Input!int();
{
auto oo = ii.pair;
oo.put(7);
oo.put(77);
}
assert(ii[] == [7, 77]);
}
/// Movement.
unittest
{
import std.algorithm;
auto i1 = Input!int();
auto o1 = i1.pair;
auto i2 = i1;
auto o2 = o1;
o2.put(7);
o2.put(77);
o2.destroy();
assert(i1[] == []);
assert(i2[] == [7, 77]);
}
/// Batched input
unittest
{
auto ii = Input!int();
auto o1 = ii.pair;
auto o2 = ii.pair;
o1.put(7);
o1.put(777);
o1.destroy();
o2.put(13);
o2.put(666);
o2.destroy();
assert(ii[] == [7, 777, 13, 666]);
}
/// Round robin output
unittest
{
auto oo = Output!int();
auto i1 = oo.pair;
auto i2 = oo.pair;
oo.put(7);
oo.put(13);
oo.put(777);
oo.put(666);
oo.destroy();
assert(i1[] == [7, 777]);
assert(i2[] == [13, 666]);
}