using System; using System.Diagnostics; namespace NAudio.Utils { /// /// A very basic circular buffer implementation /// public class CircularBuffer { private readonly byte[] buffer; private readonly object lockObject; private int writePosition; private int readPosition; private int byteCount; /// /// Create a new circular buffer /// /// Max buffer size in bytes public CircularBuffer(int size) { buffer = new byte[size]; lockObject = new object(); } /// /// Write data to the buffer /// /// Data to write /// Offset into data /// Number of bytes to write /// number of bytes written public int Write(byte[] data, int offset, int count) { lock (lockObject) { var bytesWritten = 0; if (count > buffer.Length - byteCount) { count = buffer.Length - byteCount; } // write to end int writeToEnd = Math.Min(buffer.Length - writePosition, count); Array.Copy(data, offset, buffer, writePosition, writeToEnd); writePosition += writeToEnd; writePosition %= buffer.Length; bytesWritten += writeToEnd; if (bytesWritten < count) { Debug.Assert(writePosition == 0); // must have wrapped round. Write to start Array.Copy(data, offset + bytesWritten, buffer, writePosition, count - bytesWritten); writePosition += (count - bytesWritten); bytesWritten = count; } byteCount += bytesWritten; return bytesWritten; } } /// /// Read from the buffer /// /// Buffer to read into /// Offset into read buffer /// Bytes to read /// Number of bytes actually read public int Read(byte[] data, int offset, int count) { lock (lockObject) { if (count > byteCount) { count = byteCount; } int bytesRead = 0; int readToEnd = Math.Min(buffer.Length - readPosition, count); Array.Copy(buffer, readPosition, data, offset, readToEnd); bytesRead += readToEnd; readPosition += readToEnd; readPosition %= buffer.Length; if (bytesRead < count) { // must have wrapped round. Read from start Debug.Assert(readPosition == 0); Array.Copy(buffer, readPosition, data, offset + bytesRead, count - bytesRead); readPosition += (count - bytesRead); bytesRead = count; } byteCount -= bytesRead; Debug.Assert(byteCount >= 0); return bytesRead; } } /// /// Maximum length of this circular buffer /// public int MaxLength => buffer.Length; /// /// Number of bytes currently stored in the circular buffer /// public int Count { get { lock (lockObject) { return byteCount; } } } /// /// Resets the buffer /// public void Reset() { lock (lockObject) { ResetInner(); } } private void ResetInner() { byteCount = 0; readPosition = 0; writePosition = 0; } /// /// Advances the buffer, discarding bytes /// /// Bytes to advance public void Advance(int count) { lock (lockObject) { if (count >= byteCount) { ResetInner(); } else { byteCount -= count; readPosition += count; readPosition %= MaxLength; } } } } }