Skip to content

Instantly share code, notes, and snippets.

@yKimisaki
Last active December 16, 2015 06:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yKimisaki/374f9925d152e5232f62 to your computer and use it in GitHub Desktop.
Save yKimisaki/374f9925d152e5232f62 to your computer and use it in GitHub Desktop.
using System;
namespace Tonari.Text
{
public class StringBuilder : IDisposable
{
private char[] _buffer;
private int _bufferLength;
private int _position;
public StringBuilder(int capacity)
{
_bufferLength = capacity;
_buffer = new char[_bufferLength];
}
public void Dispose()
{
_buffer = null;
}
public void Clear()
{
_position = 0;
}
public void Append(string source)
{
if (source == null) return;
var length = source.Length;
if (_position + length > _bufferLength)
{
ExtendBuffer(length);
}
for (var i = 0; i < length; ++i)
{
_buffer[_position + i] = source[i];
}
_position += length;
}
public void Append(StringBuilder builder)
{
if (builder == null) return;
var length = builder._position;
if (_position + length > _bufferLength)
{
ExtendBuffer(length);
}
for (var i = 0; i < length; ++i)
{
_buffer[_position + i] = builder._buffer[i];
}
_position += length;
}
private void ExtendBuffer(int length)
{
var temp = _buffer;
var tempLength = _bufferLength;
do
{
_bufferLength *= 2;
} while (_bufferLength < tempLength + length);
_buffer = new char[_bufferLength];
Buffer.BlockCopy(temp, 0, _buffer, 0, sizeof(char) * tempLength);
}
public override string ToString()
{
return new string(_buffer, 0, _position);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment