forked from cschladetsch/Flow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Channel.cs
69 lines (56 loc) · 1.2 KB
/
Channel.cs
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
// (C) 2012 Christian Schladetsch. See http://www.schladetsch.net/flow/license.txt for Licensing information.
using System;
using System.Collections.Generic;
namespace Flow
{
internal class Channel<TR> : Subroutine<bool>, IChannel<TR>
{
/// <inheritdoc />
public IFuture<TR> Extract()
{
var future = Factory.NewFuture<TR>();
_requests.Enqueue(future);
return future;
}
/// <inheritdoc />
public void Insert(TR val)
{
_values.Enqueue(val);
}
/// <inheritdoc />
public void Flush()
{
while (_values.Count > 0 && _requests.Count > 0)
{
_requests.Dequeue().Value = _values.Dequeue();
}
}
internal Channel(IKernel kernel)
{
Sub = StepChannel;
Completed += (tr) => Close();
}
internal void Close()
{
Flush();
foreach (var f in _requests)
f.Complete();
}
internal Channel(IKernel kernel, ITypedGenerator<TR> gen)
: this(kernel)
{
gen.Stepped += g => Insert(gen.Value);
CompleteAfter(gen);
}
bool StepChannel(IGenerator self)
{
base.Step();
if (Completed)
return;
Flush();
return true;
}
readonly Queue<TR> _values = new Queue<TR>();
readonly Queue<IFuture<TR>> _requests = new Queue<IFuture<TR>>();
}
}