Last active
March 9, 2017 14:34
-
-
Save khellang/5b23d2406d9633c20e61f9c4a6bd160d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Concurrent; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
[DebuggerTypeProxy(typeof(CircularBuffer<>.DebugView))] | |
[DebuggerDisplay("Count = {Count}, Type = {Collection}")] | |
public class CircularBuffer<T> : IReadOnlyCollection<T>, ICollection | |
{ | |
public CircularBuffer(int boundedCapacity) | |
: this(new ConcurrentQueue<T>(), boundedCapacity) | |
{ | |
} | |
public CircularBuffer(IProducerConsumerCollection<T> collection, int boundedCapacity) | |
{ | |
Collection = collection; | |
BoundedCapacity = boundedCapacity; | |
} | |
public int BoundedCapacity { get; } | |
public int Count => Collection.Count; | |
int ICollection.Count => Count; | |
bool ICollection.IsSynchronized => false; | |
object ICollection.SyncRoot | |
{ | |
get { throw new NotSupportedException(); } | |
} | |
private IProducerConsumerCollection<T> Collection { get; } | |
void ICollection.CopyTo(Array array, int index) | |
{ | |
Collection.CopyTo(array, index); | |
} | |
public void CopyTo(T[] array, int index) | |
{ | |
Collection.CopyTo(array, index); | |
} | |
public bool TryAdd(T item) | |
{ | |
if (Count == BoundedCapacity) | |
{ | |
T dropped; | |
if (TryTake(out dropped)) | |
{ | |
return Collection.TryAdd(item); | |
} | |
return false; // Not sure how this could ever happen... | |
} | |
return Collection.TryAdd(item); | |
} | |
public bool TryTake(out T item) | |
{ | |
return Collection.TryTake(out item); | |
} | |
public T[] ToArray() | |
{ | |
return Collection.ToArray(); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return GetEnumerator(); | |
} | |
public IEnumerator<T> GetEnumerator() | |
{ | |
return Collection.GetEnumerator(); | |
} | |
private sealed class DebugView | |
{ | |
public DebugView(CircularBuffer<T> buffer) | |
{ | |
Buffer = buffer; | |
} | |
private CircularBuffer<T> Buffer { get; } | |
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] | |
public T[] Items => Buffer.ToArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment