Skip to content

cByteBuffer Class Reference

📋 Class Overview

cByteBuffer is an efficient byte buffer class for managing binary data streams.

Design Features

  • Pre-allocated - Initially allocates 4KB to avoid frequent memory allocation
  • Smart growth - Grows by 1.5x to balance space and performance
  • Minimal copying - Uses CopyMemory API for efficiency
  • Peek/Consume - Supports viewing data without consuming

🔧 Property Reference

Size - Current Data Size

Type: Long
Read/Write: Read-only

Description: The number of bytes of data currently stored in the buffer.

vb
Debug.Print "Buffer size: " & oBuffer.Size & " bytes"

If oBuffer.Size > 0 Then
    ProcessData oBuffer
End If

Capacity - Buffer Capacity

Type: Long
Read/Write: Read-only

Description: The total allocated capacity of the buffer (bytes).

vb
Debug.Print "Capacity: " & oBuffer.Capacity & " bytes"
Debug.Print "Usage: " & (oBuffer.Size / oBuffer.Capacity * 100) & "%"

IsEmpty - Is Empty

Type: Boolean
Read/Write: Read-only

Description: Whether the buffer is empty (Size = 0).

vb
If oBuffer.IsEmpty Then
    Debug.Print "Buffer is empty"
Else
    Debug.Print "Buffer has " & oBuffer.Size & " bytes of data"
End If

🚀 Method Reference

Append - Append Data

Syntax:

vb
Public Sub Append(ByRef Data() As Byte)

Parameters:

ParameterTypeDescription
Data()Byte()Byte array to append

Description:

  • Automatically expands capacity if needed
  • Data is appended to the end of the buffer

Example:

vb
' Append byte array
Dim baData() As Byte
baData = StringToUTF8("Hello")
oBuffer.Append baData

' Append received network data
Private Sub Socket_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
    Dim baData() As Byte
    Client.GetData baData, vbByte + vbArray
    oBuffer.Append baData
    
    ' Process buffer
    ProcessBuffer
End Sub

AppendByte - Append Single Byte

Syntax:

vb
Public Sub AppendByte(ByVal Value As Byte)

Parameters:

ParameterTypeDescription
ValueByteByte value to append

Example:

vb
' Build protocol header
oBuffer.AppendByte &H01  ' Version
oBuffer.AppendByte &H02  ' Type
oBuffer.AppendByte &H03  ' Flags

Peek - View Data (No Consume)

Syntax:

vb
Public Function Peek(ByVal Offset As Long, ByVal Length As Long, ByRef OutData() As Byte) As Boolean

Parameters:

ParameterTypeDescription
OffsetLongOffset position (starting from 0)
LengthLongNumber of bytes to view
OutData()Byte()Output byte array

Return Value: Boolean - Returns True if successful, otherwise False

Description:

  • Read-only operation, does not modify buffer
  • Suitable for pre-checking data

Example:

vb
' Check if first 4 bytes are specific value
Dim baHeader() As Byte
If oBuffer.Peek(0, 4, baHeader) Then
    If baHeader(0) = &HDE And baHeader(1) = &HAD Then
        Debug.Print "Magic number detected"
    End If
End If

PeekByte - View Single Byte

Syntax:

vb
Public Function PeekByte(ByVal Offset As Long) As Byte

Parameters:

ParameterTypeDescription
OffsetLongOffset position

Return Value: Read byte value

Example:

vb
' Check first byte
Dim bFirst As Byte
bFirst = oBuffer.PeekByte(0)
Debug.Print "First byte: " & Hex$(bFirst)

Consume - Consume Data

Syntax:

vb
Public Sub Consume(ByVal Length As Long)

Parameters:

ParameterTypeDescription
LengthLongNumber of bytes to consume

Description:

  • Removes specified number of bytes from the front of the buffer
  • Remaining data moves forward
  • Buffer becomes empty if all data is consumed

Example:

vb
' Consume first 4 bytes
oBuffer.Consume 4

' Consume processed data
oBuffer.Consume lProcessedBytes

Extract - Extract and Consume Data

Syntax:

vb
Public Function Extract(ByVal Length As Long) As Byte()

Parameters:

ParameterTypeDescription
LengthLongNumber of bytes to extract

Return Value: Extracted byte array

Description:

  • Returns data of specified length
  • Automatically removes from buffer

Example:

vb
' Extract and consume first 10 bytes
Dim baData() As Byte
baData = oBuffer.Extract(10)
Debug.Print "Extracted " & (UBound(baData) + 1) & " bytes"

' WebSocket frame extraction example
Private Sub ExtractFrame(oBuffer As cByteBuffer)
    Dim oFrame As New cWebSocketFrame
    
    If oFrame.ParseHeader(oBuffer) Then
        If oFrame.IsCompleteFrame(oBuffer) Then
            Dim baFrame() As Byte
            baFrame = oBuffer.Extract(oFrame.TotalFrameLength)
            ' Process frame...
        End If
    End If
End Sub

ToArray - Get All Data

Syntax:

vb
Public Function ToArray() As Byte()

Return Value: Copy of all buffer data

Description:

  • Returns a copy of the data, does not affect the buffer
  • Returns empty array for empty buffer

Example:

vb
' Get all data
Dim baAll() As Byte
baAll = oBuffer.ToArray
Debug.Print "Total data: " & (UBound(baAll) + 1) & " bytes"

' Save to file
SaveToFile "data.bin", baAll

Clear - Clear Buffer

Syntax:

vb
Public Sub Clear()

Description: Clears all data but retains capacity.

Example:

vb
' Clear buffer
oBuffer.Clear
Debug.Print "Buffer cleared, size: " & oBuffer.Size

Reset - Reset Buffer

Syntax:

vb
Public Sub Reset()

Description:

  • Clears all data
  • Resets capacity to initial value (4KB)

Example:

vb
' Complete reset
oBuffer.Reset
Debug.Print "Buffer reset, capacity: " & oBuffer.Capacity

GetBufferPtr - Get Buffer Pointer

Syntax:

vb
Public Function GetBufferPtr() As Long

Return Value: Memory address of internal buffer

Description:

  • Used for high-performance scenarios
  • ⚠️ Dangerous operation, do not write beyond Size range

Example:

vb
' High-performance filling (advanced usage only)
Dim pBuffer As Long
pBuffer = oBuffer.GetBufferPtr

If pBuffer <> 0 Then
    ' Use CopyMemory API to write directly
    CopyMemory ByVal pBuffer, baData(0), UBound(baData) + 1
    oBuffer.Size = oBuffer.Size + UBound(baData) + 1
End If

📝 Usage Examples

WebSocket Frame Parsing

vb
Private Sub ProcessWebSocketData(oBuffer As cByteBuffer)
    Dim oFrame As New cWebSocketFrame
    
    Do While oBuffer.Size >= 2
        ' Parse header
        If Not oFrame.ParseHeader(oBuffer) Then
            Exit Do ' Need more data
        End If
        
        ' Check completeness
        If Not oFrame.IsCompleteFrame(oBuffer) Then
            Exit Do ' Need more data
        End If
        
        ' Extract frame
        Dim baFrame() As Byte
        baFrame = oBuffer.Extract(oFrame.TotalFrameLength)
        
        ' Process frame
        ProcessFrame baFrame, oFrame
    Loop
End Sub

Network Data Reception

vb
Private WithEvents m_Socket As cWinsock
Private m_RecvBuffer As cByteBuffer

Private Sub Form_Load()
    Set m_RecvBuffer = New cByteBuffer
End Sub

Private Sub m_Socket_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
    Dim baData() As Byte
    Client.GetData baData, vbByte + vbArray
    
    ' Append to buffer
    m_RecvBuffer.Append baData
    
    ' Process complete messages in buffer
    ProcessBuffer
End Sub

Private Sub ProcessBuffer()
    Do While m_RecvBuffer.Size >= 4
        ' Read message length (assume first 4 bytes are length)
        Dim lLen As Long
        lLen = CLng(m_RecvBuffer.PeekByte(0)) * 256& ^ 3 + _
                 CLng(m_RecvBuffer.PeekByte(1)) * 256& ^ 2 + _
                 CLng(m_RecvBuffer.PeekByte(2)) * 256& + _
                 CLng(m_RecvBuffer.PeekByte(3))
        
        ' Check if complete message exists
        If m_RecvBuffer.Size < 4 + lLen Then
            Exit Do ' Need more data
        End If
        
        ' Extract message header
        m_RecvBuffer.Consume 4
        
        ' Extract message body
        Dim baMessage() As Byte
        baMessage = m_RecvBuffer.Extract(lLen)
        
        ' Process message
        ProcessMessage baMessage
    Loop
End Sub

Protocol Header Building

vb
Private Function BuildProtocolHeader() As cByteBuffer
    Dim oBuffer As New cByteBuffer
    
    ' Build protocol header
    oBuffer.AppendByte &H01              ' Version
    oBuffer.AppendByte &H00              ' Type
    oBuffer.AppendByte &H00              ' Flags
    oBuffer.AppendByte &H00              ' Reserved
    
    ' Add length (4 bytes)
    Dim lLen As Long
    lLen = 1234
    oBuffer.AppendByte (lLen And &HFF000000) \ &H1000000
    oBuffer.AppendByte (lLen And &HFF0000) \ &H10000
    oBuffer.AppendByte (lLen And &HFF00&) \ &H100&
    oBuffer.AppendByte (lLen And &HFF&)
    
    Set BuildProtocolHeader = oBuffer
End Function

Data Fragmentation Handling

vb
Private m_FragmentBuffer As cByteBuffer

Private Sub HandleFragmentedFrame(oFrame As cWebSocketFrame, oBuffer As cByteBuffer)
    ' Extract frame
    Dim baPayload() As Byte
    baPayload = oBuffer.Extract(oFrame.TotalFrameLength)
    
    If m_FragmentBuffer.IsEmpty Then
        ' First fragment
        If Not oFrame.FIN Then
            ' Start fragmented message
            m_FragmentBuffer.Clear
            m_FragmentBuffer.Append baPayload
        Else
            ' Single frame (no fragmentation)
            ProcessCompleteMessage baPayload, oFrame.OpCode
        End If
    Else
        ' Subsequent fragments
        m_FragmentBuffer.Append baPayload
        
        If oFrame.FIN Then
            ' Last fragment
            Dim baComplete() As Byte
            baComplete = m_FragmentBuffer.ToArray
            ProcessCompleteMessage baComplete, oFrame.OpCode
            m_FragmentBuffer.Clear
        End If
    End If
End Sub

⚠️ Notes

  1. Capacity auto-growth - Append will automatically expand if exceeding capacity
  2. Peek is read-only - Peek operations do not modify buffer
  3. Consume removes - Data is deleted after Consume
  4. Extract consumes - Extract is equivalent to Peek + Consume
  5. GetBufferPtr is dangerous - For advanced use only, ensure no out-of-bounds access

🔍 Performance Optimization

Batch Append

vb
' ✅ Good: single Append
Dim baData() As Byte
baData = BuildLargeData()
oBuffer.Append baData

' ❌ Bad: multiple Appends
For i = 0 To 10000
    oBuffer.AppendByte baData(i)
Next i

Avoid Frequent ToArray

vb
' ✅ Good: direct use of Peek/Consume
If oBuffer.Peek(0, 4, baHeader) Then
    ProcessHeader baHeader
End If

' ❌ Bad: frequent ToArray
Dim baAll() As Byte
baAll = oBuffer.ToArray
For i = 0 To 100
    ProcessSegment baAll, i * 100, 100
Next i

Last Updated: 2026-01-10

VB6 and LOGO copyright of Microsoft Corporation