using System; namespace Orvid.Graphics.FontSupport.bdf { public class StringBuilder { /// /// The internal private copy of the string /// private char[] _storedString; /// /// The number of allocated characters /// private int lngAllocated; /// /// The number of used characters /// private int lngUsed; /// /// Number of characters to allocated with an increase /// private int lngAllocSize; /// /// Get the length of the string /// public int Length { get { return lngUsed; } } /// /// The default constructor for the class /// /// Sets the allocation size to 1000 public StringBuilder() { lngAllocSize = 1000; lngAllocated = lngAllocSize; _storedString = new char[lngAllocSize]; } /// /// The constructor used to set the initial value of the string /// /// Sets the allocation size to 1000 public StringBuilder(string InitialValue) { lngAllocSize = 1000; lngAllocated = lngAllocSize; _storedString = new char[lngAllocSize]; Append(InitialValue); } /// /// Constructor used to define a custom allocation size /// /// The size of every allocation public StringBuilder(int AllocationSize) { lngAllocSize = AllocationSize; lngAllocated = lngAllocSize; _storedString = new char[lngAllocSize]; } /// /// The constructor used to set the initial value of the string /// /// The initial value of the string /// The size of every allocation public StringBuilder(string InitialValue, int AllocationSize) { lngAllocSize = AllocationSize; lngAllocated = lngAllocSize; _storedString = new char[lngAllocSize]; Append(InitialValue); } /// /// Append a string to the internal string /// /// The string to be appended public void Append(string StringToAppend) { int lngLength; int lngToAllocate; lngLength = StringToAppend.Length; if (lngLength > 0) { if (lngLength + lngUsed > lngAllocated) { throw new Exception(); lngToAllocate = lngAllocSize * (1 + (lngUsed + lngLength - lngAllocated) / lngAllocSize); lngAllocated += lngToAllocate; _storedString = ResizeArray(_storedString, lngAllocated); } int counter = 0; foreach (char c in StringToAppend) { _storedString[lngUsed + counter] = c; counter++; } lngUsed += lngLength; } } /// /// Overwrite the string with the specified string /// /// The new string value of the string public void Overwrite(string StringToWrite) { Clear(); Append(StringToWrite); } /// /// Get the string /// /// The string that has been built public override string ToString() { string returnString = new string(_storedString, 0, lngUsed); return returnString; } /// /// Clear the string from memory /// public void Clear() { _storedString = null; lngUsed = 0; lngAllocated = lngAllocSize; _storedString = new char[lngAllocSize]; } /// /// Resize the internal array /// /// The old array to resize /// The new size of the expanded array /// a New bigger array with all the contents of the old array private char[] ResizeArray(System.Array oldArray, int newSize) { char[] newArray = new char[newSize]; Array.Copy(oldArray, newArray, oldArray.Length); return newArray; } } }