Merge pull request #409 from Alkarex/patch-1
[mono.git] / mcs / class / System.Threading.Tasks.Dataflow / System.Threading.Tasks.Dataflow / WriteOnceBlock.cs
1 // WriteOnceBlock.cs
2 //
3 // Copyright (c) 2011 Jérémie "garuma" Laval
4 // Copyright (c) 2012 Petr Onderka
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining a copy
7 // of this software and associated documentation files (the "Software"), to deal
8 // in the Software without restriction, including without limitation the rights
9 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 // copies of the Software, and to permit persons to whom the Software is
11 // furnished to do so, subject to the following conditions:
12 //
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 // THE SOFTWARE.
23
24 using System.Collections.Generic;
25 using System.Collections.Concurrent;
26
27 namespace System.Threading.Tasks.Dataflow {
28         public sealed class WriteOnceBlock<T> : IPropagatorBlock<T, T>, IReceivableSourceBlock<T> {
29                 readonly CompletionHelper compHelper;
30                 readonly BlockingCollection<T> messageQueue = new BlockingCollection<T> ();
31                 readonly MessageBox<T> messageBox;
32                 readonly DataflowBlockOptions dataflowBlockOptions;
33                 readonly Func<T, T> cloningFunction;
34                 readonly BroadcastOutgoingQueue<T> outgoing;
35                 AtomicBooleanValue written;
36
37                 public WriteOnceBlock (Func<T, T> cloningFunction)
38                         : this (cloningFunction, DataflowBlockOptions.Default)
39                 {
40                 }
41
42                 public WriteOnceBlock (Func<T, T> cloningFunction,
43                                        DataflowBlockOptions dataflowBlockOptions)
44                 {
45                         if (dataflowBlockOptions == null)
46                                 throw new ArgumentNullException ("dataflowBlockOptions");
47
48                         this.cloningFunction = cloningFunction;
49                         this.dataflowBlockOptions = dataflowBlockOptions;
50                         this.compHelper = CompletionHelper.GetNew (dataflowBlockOptions);
51                         this.messageBox = new PassingMessageBox<T> (this, messageQueue, compHelper,
52                                 () => true, _ => BroadcastProcess (), dataflowBlockOptions,
53                                 canAccept: () => written.TrySet ());
54                         this.outgoing = new BroadcastOutgoingQueue<T> (this, compHelper,
55                                 () => messageQueue.IsCompleted, messageBox.DecreaseCount,
56                                 dataflowBlockOptions, cloningFunction != null);
57                 }
58
59                 DataflowMessageStatus ITargetBlock<T>.OfferMessage (
60                         DataflowMessageHeader messageHeader, T messageValue,
61                         ISourceBlock<T> source, bool consumeToAccept)
62                 {
63                         var result = messageBox.OfferMessage (messageHeader, messageValue, source,
64                                 consumeToAccept);
65                         if (result == DataflowMessageStatus.Accepted)
66                                 messageQueue.CompleteAdding ();
67                         return result;
68                 }
69
70                 public IDisposable LinkTo (ITargetBlock<T> target,
71                                            DataflowLinkOptions linkOptions)
72                 {
73                         return outgoing.AddTarget (target, linkOptions);
74                 }
75
76                 T ISourceBlock<T>.ConsumeMessage (DataflowMessageHeader messageHeader,
77                                                   ITargetBlock<T> target,
78                                                   out bool messageConsumed)
79                 {
80                         T message = outgoing.ConsumeMessage (
81                                 messageHeader, target, out messageConsumed);
82                         if (messageConsumed && cloningFunction != null)
83                                 message = cloningFunction (message);
84                         return message;
85                 }
86
87                 void ISourceBlock<T>.ReleaseReservation (DataflowMessageHeader messageHeader,
88                                                          ITargetBlock<T> target)
89                 {
90                         outgoing.ReleaseReservation (messageHeader, target);
91                 }
92
93                 bool ISourceBlock<T>.ReserveMessage (DataflowMessageHeader messageHeader,
94                                                      ITargetBlock<T> target)
95                 {
96                         return outgoing.ReserveMessage (messageHeader, target);
97                 }
98
99                 public bool TryReceive (Predicate<T> filter, out T item)
100                 {
101                         var received = outgoing.TryReceive (filter, out item);
102                         if (received && cloningFunction != null)
103                                 item = cloningFunction (item);
104                         return received;
105                 }
106
107                 bool IReceivableSourceBlock<T>.TryReceiveAll (out IList<T> items)
108                 {
109                         T item;
110                         if (!TryReceive (null, out item)) {
111                                 items = null;
112                                 return false;
113                         }
114
115                         items = new[] { item };
116                         return true;
117                 }
118
119                 /// <summary>
120                 /// Moves an item from the input queue to the output queue.
121                 /// </summary>
122                 void BroadcastProcess ()
123                 {
124                         T item;
125                         if (messageQueue.TryTake (out item))
126                                 outgoing.AddData (item);
127                         outgoing.DequeueItem ();
128                 }
129
130                 public void Complete ()
131                 {
132                         messageBox.Complete ();
133                         outgoing.Complete ();
134                 }
135
136                 void IDataflowBlock.Fault (Exception exception)
137                 {
138                         compHelper.RequestFault (exception);
139                 }
140
141                 public Task Completion {
142                         get { return compHelper.Completion; }
143                 }
144
145                 public override string ToString ()
146                 {
147                         return NameHelper.GetName (this, dataflowBlockOptions);
148                 }
149         }
150 }