/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections;
using System.Collections.Generic;
namespace QuantConnect.Util
{
///
/// Provides an implementation of an add-only fixed length, unique queue system
///
public class FixedSizeHashQueue : IEnumerable
{
private readonly int _size;
private readonly Queue _queue;
private readonly HashSet _hash;
///
/// Initializes a new instance of the class
///
/// The maximum number of items to hold
public FixedSizeHashQueue(int size)
{
_size = size;
_queue = new Queue(size);
_hash = new HashSet();
}
///
/// Returns true if the item was added and didn't already exists
///
public bool Add(T item)
{
if (_hash.Add(item))
{
_queue.Enqueue(item);
if (_queue.Count > _size)
{
// remove the item from both
_hash.Remove(_queue.Dequeue());
}
return true;
}
return false;
}
///
/// Tries to inspect the first item in the queue
///
public bool TryPeek(out T item)
{
return _queue.TryPeek(out item);
}
///
/// Dequeues and returns the next item in the queue
///
public T Dequeue()
{
var item = _queue.Dequeue();
_hash.Remove(item);
return item;
}
///
/// Returns true if the specified item exists in the collection
///
public bool Contains(T item)
{
return _hash.Contains(item);
}
///
/// Returns an enumerator that iterates through the collection.
///
///
/// A that can be used to iterate through the collection.
///
/// 1
public IEnumerator GetEnumerator()
{
return _queue.GetEnumerator();
}
///
/// Returns an enumerator that iterates through a collection.
///
///
/// An object that can be used to iterate through the collection.
///
/// 2
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}