VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
  Persistable = 0  'NotPersistable
  DataBindingBehavior = 0  'vbNone
  DataSourceBehavior  = 0  'vbNone
  MTSTransactionMode  = 0  'NotAnMTSObject
END
Attribute VB_Name = "RingBufferClass"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

Public BufferSize As Long
Public UsedBytes As Long

Public ByteLen As Long
Public DataPtr As Long

Private CurrBuffReadPos As Long
Private CurrBuffWritePos As Long
Private BuffArr() As Byte
Private BuffPtr As Long
Private BufferIsFull As Boolean

Public Sub InitBuffer(newBufferSize As Long)
  BufferSize = newBufferSize
  ReDim BuffArr(BufferSize - 1)
  BuffPtr = VarPtr(BuffArr(0))
End Sub

Public Function StartDataAdd(RequDataLen As Long) As Long
  If RequDataLen > BufferSize - CurrBuffWritePos Then
    ByteLen = BufferSize - CurrBuffWritePos
  Else
    ByteLen = RequDataLen
  End If
  If (CurrBuffWritePos < CurrBuffReadPos And CurrBuffWritePos + ByteLen > CurrBuffReadPos) Or BufferIsFull Then
    ByteLen = CurrBuffReadPos - CurrBuffWritePos
  End If
  DataPtr = BuffPtr + CurrBuffWritePos
  StartDataAdd = ByteLen
End Function

Public Sub DataAdded(DataLen As Long)
  UsedBytes = UsedBytes + DataLen
  CurrBuffWritePos = CurrBuffWritePos + DataLen
  If CurrBuffWritePos = BufferSize Then CurrBuffWritePos = 0
  If CurrBuffWritePos > BufferSize Then Stop
  If CurrBuffWritePos = CurrBuffReadPos Then BufferIsFull = True
End Sub

Public Function StartDataRead(RequDataLen As Long) As Long
  If RequDataLen > BufferSize - CurrBuffReadPos Then
    ByteLen = BufferSize - CurrBuffReadPos
  Else
    ByteLen = RequDataLen
  End If
  If CurrBuffReadPos <= CurrBuffWritePos And CurrBuffReadPos + ByteLen > CurrBuffWritePos And (Not BufferIsFull) Then
    ByteLen = CurrBuffWritePos - CurrBuffReadPos
  End If
  DataPtr = BuffPtr + CurrBuffReadPos
  StartDataRead = ByteLen
End Function

Public Sub DataRemove(DataLen As Long)
  UsedBytes = UsedBytes - DataLen
  CurrBuffReadPos = CurrBuffReadPos + DataLen
  If CurrBuffReadPos = BufferSize Then CurrBuffReadPos = 0
  If CurrBuffReadPos > BufferSize Then Stop
  If DataLen Then BufferIsFull = False
End Sub

Public Function ReadByte() As Byte
  StartDataRead 1
  If ByteLen = 1 Then
    ReadByte = BuffArr(CurrBuffReadPos)
    DataRemove 1
  End If
End Function

