Lean  $LEAN_TAG$
CircularQueue.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System;
17 using System.Collections.Generic;
18 
19 namespace QuantConnect.Util
20 {
21  /// <summary>
22  /// A never ending queue that will dequeue and reenqueue the same item
23  /// </summary>
24  public class CircularQueue<T>
25  {
26  private readonly T _head;
27  private readonly Queue<T> _queue;
28 
29  /// <summary>
30  /// Fired when we do a full circle
31  /// </summary>
32  public event EventHandler CircleCompleted;
33 
34  /// <summary>
35  /// Initializes a new instance of the <see cref="CircularQueue{T}"/> class
36  /// </summary>
37  /// <param name="items">The items in the queue</param>
38  public CircularQueue(params T[] items)
39  : this((IEnumerable<T>)items)
40  {
41  }
42 
43  /// <summary>
44  /// Initializes a new instance of the <see cref="CircularQueue{T}"/> class
45  /// </summary>
46  /// <param name="items">The items in the queue</param>
47  public CircularQueue(IEnumerable<T> items)
48  {
49  _queue = new Queue<T>();
50 
51  var first = true;
52  foreach (var item in items)
53  {
54  if (first)
55  {
56  first = false;
57  _head = item;
58  }
59  _queue.Enqueue(item);
60  }
61  }
62 
63  /// <summary>
64  /// Dequeues the next item
65  /// </summary>
66  /// <returns>The next item</returns>
67  public T Dequeue()
68  {
69  var item = _queue.Dequeue();
70  if (item.Equals(_head))
71  {
73  }
74  _queue.Enqueue(item);
75  return item;
76  }
77 
78  /// <summary>
79  /// Event invocator for the <see cref="CircleCompleted"/> evet
80  /// </summary>
81  protected virtual void OnCircleCompleted()
82  {
83  var handler = CircleCompleted;
84  if (handler != null) handler(this, EventArgs.Empty);
85  }
86  }
87 }