Skip to content

Instantly share code, notes, and snippets.

@arlm
Forked from jmcd/ByteArrayBuilder.cs
Created March 1, 2018 09:57
Show Gist options
  • Save arlm/19d5b203346c627d20f5bf8b69407028 to your computer and use it in GitHub Desktop.
Save arlm/19d5b203346c627d20f5bf8b69407028 to your computer and use it in GitHub Desktop.
Byte-array builder
public class ByteArrayBuilder
{
private byte[] _buffer;
public int Length { get; set; }
public ByteArrayBuilder()
{
_buffer = new byte[4096];
Length = 0;
}
public ByteArrayBuilder Append(byte b)
{
if (GetUnusedBufferLength() == 0)
{
_buffer = IncreaseCapacity(_buffer, _buffer.Length * 2);
}
_buffer[Length] = b;
Length++;
return this;
}
public ByteArrayBuilder Append(byte[] buffer)
{
var unusedBufferLength = GetUnusedBufferLength();
if (unusedBufferLength < buffer.Length)
{
_buffer = IncreaseCapacity(_buffer, _buffer.Length + buffer.Length);
}
Array.Copy(buffer, 0, _buffer, Length, buffer.Length);
Length += buffer.Length;
return this;
}
public byte[] ToArray()
{
var unusedBufferLength = GetUnusedBufferLength();
if (unusedBufferLength == 0)
{
return _buffer;
}
var result = new byte[Length];
Array.Copy(_buffer, result, result.Length);
return result;
}
private int GetUnusedBufferLength()
{
return _buffer.Length - Length;
}
private static byte[] IncreaseCapacity(byte[] buffer, int targetLength)
{
var result = new byte[targetLength];
Array.Copy(buffer, result, buffer.Length);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment