Skip to content

Instantly share code, notes, and snippets.

@jmcd
Created April 26, 2012 15:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jmcd/2500463 to your computer and use it in GitHub Desktop.
Save jmcd/2500463 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