Last active
December 16, 2015 06:43
-
-
Save yKimisaki/374f9925d152e5232f62 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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