andrew4582

String Buffer

Aug 15th, 2010
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | None | 0 0
  1.  
  2.  
  3. using System;
  4.  
  5. namespace System.Utilities
  6. {
  7.   /// <summary>
  8.   /// Builds a string. Unlike StringBuilder this class lets you reuse it's internal buffer.
  9.   /// </summary>
  10.   internal class StringBuffer
  11.   {
  12.     private char[] _buffer;
  13.     private int _position;
  14.  
  15.     private static readonly char[] _emptyBuffer = new char[0];
  16.  
  17.     public int Position
  18.     {
  19.       get { return _position; }
  20.       set { _position = value; }
  21.     }
  22.  
  23.     public StringBuffer()
  24.     {
  25.       _buffer = _emptyBuffer;
  26.     }
  27.  
  28.     public StringBuffer(int initalSize)
  29.     {
  30.       _buffer = new char[initalSize];
  31.     }
  32.  
  33.     public void Append(char value)
  34.     {
  35.       // test if the buffer array is large enough to take the value
  36.       if (_position + 1 > _buffer.Length)
  37.       {
  38.         EnsureSize(1);
  39.       }
  40.  
  41.       // set value and increment poisition
  42.       _buffer[_position++] = value;
  43.     }
  44.  
  45.     public void Clear()
  46.     {
  47.       _buffer = _emptyBuffer;
  48.       _position = 0;
  49.     }
  50.  
  51.     private void EnsureSize(int appendLength)
  52.     {
  53.       char[] newBuffer = new char[(_position + appendLength) * 2];
  54.  
  55.       Array.Copy(_buffer, newBuffer, _position);
  56.  
  57.       _buffer = newBuffer;
  58.     }
  59.  
  60.     public override string ToString()
  61.     {
  62.       return ToString(0, _position);
  63.     }
  64.  
  65.     public string ToString(int start, int length)
  66.     {
  67.       // TODO: validation
  68.       return new string(_buffer, start, length);
  69.     }
  70.   }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment