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.
Debug.Print "Buffer size: " & oBuffer.Size & " bytes"
If oBuffer.Size > 0 Then
ProcessData oBuffer
End IfCapacity - Buffer Capacity
Type: Long
Read/Write: Read-only
Description: The total allocated capacity of the buffer (bytes).
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).
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:
Public Sub Append(ByRef Data() As Byte)Parameters:
| Parameter | Type | Description |
|---|---|---|
Data() | Byte() | Byte array to append |
Description:
- Automatically expands capacity if needed
- Data is appended to the end of the buffer
Example:
' 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 SubAppendByte - Append Single Byte
Syntax:
Public Sub AppendByte(ByVal Value As Byte)Parameters:
| Parameter | Type | Description |
|---|---|---|
Value | Byte | Byte value to append |
Example:
' Build protocol header
oBuffer.AppendByte &H01 ' Version
oBuffer.AppendByte &H02 ' Type
oBuffer.AppendByte &H03 ' FlagsPeek - View Data (No Consume)
Syntax:
Public Function Peek(ByVal Offset As Long, ByVal Length As Long, ByRef OutData() As Byte) As BooleanParameters:
| Parameter | Type | Description |
|---|---|---|
Offset | Long | Offset position (starting from 0) |
Length | Long | Number 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:
' 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 IfPeekByte - View Single Byte
Syntax:
Public Function PeekByte(ByVal Offset As Long) As ByteParameters:
| Parameter | Type | Description |
|---|---|---|
Offset | Long | Offset position |
Return Value: Read byte value
Example:
' Check first byte
Dim bFirst As Byte
bFirst = oBuffer.PeekByte(0)
Debug.Print "First byte: " & Hex$(bFirst)Consume - Consume Data
Syntax:
Public Sub Consume(ByVal Length As Long)Parameters:
| Parameter | Type | Description |
|---|---|---|
Length | Long | Number 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:
' Consume first 4 bytes
oBuffer.Consume 4
' Consume processed data
oBuffer.Consume lProcessedBytesExtract - Extract and Consume Data
Syntax:
Public Function Extract(ByVal Length As Long) As Byte()Parameters:
| Parameter | Type | Description |
|---|---|---|
Length | Long | Number of bytes to extract |
Return Value: Extracted byte array
Description:
- Returns data of specified length
- Automatically removes from buffer
Example:
' 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 SubToArray - Get All Data
Syntax:
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:
' Get all data
Dim baAll() As Byte
baAll = oBuffer.ToArray
Debug.Print "Total data: " & (UBound(baAll) + 1) & " bytes"
' Save to file
SaveToFile "data.bin", baAllClear - Clear Buffer
Syntax:
Public Sub Clear()Description: Clears all data but retains capacity.
Example:
' Clear buffer
oBuffer.Clear
Debug.Print "Buffer cleared, size: " & oBuffer.SizeReset - Reset Buffer
Syntax:
Public Sub Reset()Description:
- Clears all data
- Resets capacity to initial value (4KB)
Example:
' Complete reset
oBuffer.Reset
Debug.Print "Buffer reset, capacity: " & oBuffer.CapacityGetBufferPtr - Get Buffer Pointer
Syntax:
Public Function GetBufferPtr() As LongReturn Value: Memory address of internal buffer
Description:
- Used for high-performance scenarios
- ⚠️ Dangerous operation, do not write beyond Size range
Example:
' 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
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 SubNetwork Data Reception
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 SubProtocol Header Building
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 FunctionData Fragmentation Handling
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
- Capacity auto-growth - Append will automatically expand if exceeding capacity
- Peek is read-only - Peek operations do not modify buffer
- Consume removes - Data is deleted after Consume
- Extract consumes - Extract is equivalent to Peek + Consume
- GetBufferPtr is dangerous - For advanced use only, ensure no out-of-bounds access
🔍 Performance Optimization
Batch Append
' ✅ 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 iAvoid Frequent ToArray
' ✅ 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 iLast Updated: 2026-01-10