1 // -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
3 // System.Text.StringBuilder
6 // Marcin Szczepanski (marcins@zipworld.com.au)
7 // Paolo Molaro (lupus@ximian.com)
10 // NOTE: In the case the buffer is only filled by 50% a new string
11 // will be returned by ToString() is cached in the '_cached_str'
12 // cache_string will also control if a string has been handed out
13 // to via ToString(). If you are chaning the code make sure that
14 // if you modify the string data set the cache_string to null.
18 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
20 // Permission is hereby granted, free of charge, to any person obtaining
21 // a copy of this software and associated documentation files (the
22 // "Software"), to deal in the Software without restriction, including
23 // without limitation the rights to use, copy, modify, merge, publish,
24 // distribute, sublicense, and/or sell copies of the Software, and to
25 // permit persons to whom the Software is furnished to do so, subject to
26 // the following conditions:
28 // The above copyright notice and this permission notice shall be
29 // included in all copies or substantial portions of the Software.
31 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
32 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
34 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
35 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
36 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
37 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
39 using System.Runtime.Serialization;
40 using System.Runtime.CompilerServices;
41 using System.Runtime.InteropServices;
43 namespace System.Text {
49 [MonoTODO ("Serialization format not compatible with .NET")]
50 public sealed class StringBuilder
57 private string _cached_str;
59 private int _maxCapacity = Int32.MaxValue;
60 private const int constDefaultCapacity = 16;
62 public StringBuilder(string value, int startIndex, int length, int capacity)
64 // first, check the parameters and throw appropriate exceptions if needed
68 // make sure startIndex is zero or positive
70 throw new System.ArgumentOutOfRangeException ("startIndex", startIndex, "StartIndex cannot be less than zero.");
72 // make sure length is zero or positive
74 throw new System.ArgumentOutOfRangeException ("length", length, "Length cannot be less than zero.");
77 throw new System.ArgumentOutOfRangeException ("capacity", capacity, "capacity must be greater than zero.");
79 // make sure startIndex and length give a valid substring of value
80 // re-ordered to avoid possible integer overflow
81 if (startIndex > value.Length - length)
82 throw new System.ArgumentOutOfRangeException ("startIndex", startIndex, "StartIndex and length must refer to a location within the string.");
85 capacity = constDefaultCapacity;
87 _str = String.InternalAllocateStr ((length > capacity) ? length : capacity);
89 String.CharCopy (_str, 0, value, startIndex, length);
94 public StringBuilder () : this (null) {}
96 public StringBuilder(int capacity) : this (String.Empty, 0, 0, capacity) {}
98 public StringBuilder(int capacity, int maxCapacity) : this (String.Empty, 0, 0, capacity) {
100 throw new System.ArgumentOutOfRangeException ("maxCapacity", "maxCapacity is less than one.");
101 if (capacity > maxCapacity)
102 throw new System.ArgumentOutOfRangeException ("capacity", "Capacity exceeds maximum capacity.");
104 _maxCapacity = maxCapacity;
107 public StringBuilder (string value)
110 * This is an optimization to avoid allocating the internal string
111 * until the first Append () call.
112 * The runtime pinvoke marshalling code needs to be aware of this.
117 _length = value.Length;
118 _str = _cached_str = value;
121 public StringBuilder( string value, int capacity) : this(value, 0, value.Length, capacity) {}
123 public int MaxCapacity {
125 // MS runtime always returns Int32.MaxValue.
130 public int Capacity {
132 if (_str.Length == 0)
133 return constDefaultCapacity;
140 throw new ArgumentException( "Capacity must be larger than length" );
142 InternalEnsureCapacity(value);
152 if( value < 0 || value > _maxCapacity)
153 throw new ArgumentOutOfRangeException();
155 if (value == _length)
158 if (value < _length) {
159 // LAMESPEC: The spec is unclear as to what to do
160 // with the capacity when truncating the string.
162 // Do as MS, keep the capacity
164 // Make sure that we invalidate any cached string.
165 InternalEnsureCapacity (value);
168 // Expand the capacity to the new length and
169 // pad the string with NULL characters.
170 Append('\0', value - _length);
175 [IndexerName("Chars")]
176 public char this [int index] {
178 if (index >= _length || index < 0)
179 throw new IndexOutOfRangeException();
185 if (index >= _length || index < 0)
186 throw new IndexOutOfRangeException();
188 if (null != _cached_str)
189 InternalEnsureCapacity (_length);
191 _str.InternalSetChar (index, value);
195 public override string ToString ()
200 if (null != _cached_str)
203 // If we only have a half-full buffer we return a new string.
204 if (_length < (_str.Length >> 1))
206 // use String.SubstringUnchecked instead of String.Substring
207 // as the former is guaranteed to create a new string object
208 _cached_str = _str.SubstringUnchecked (0, _length);
213 _str.InternalSetLength(_length);
218 public string ToString (int startIndex, int length)
220 // re-ordered to avoid possible integer overflow
221 if (startIndex < 0 || length < 0 || startIndex > _length - length)
222 throw new ArgumentOutOfRangeException();
224 // use String.SubstringUnchecked instead of String.Substring
225 // as the former is guaranteed to create a new string object
226 if (startIndex == 0 && length == _length)
229 return _str.SubstringUnchecked (startIndex, length);
232 public int EnsureCapacity (int capacity)
235 throw new ArgumentOutOfRangeException ("Capacity must be greater than 0." );
237 if( capacity <= _str.Length )
240 InternalEnsureCapacity (capacity);
245 public bool Equals (StringBuilder sb)
247 if (((object)sb) == null)
250 if (_length == sb.Length && _str == sb._str )
256 public StringBuilder Remove (int startIndex, int length)
258 // re-ordered to avoid possible integer overflow
259 if (startIndex < 0 || length < 0 || startIndex > _length - length)
260 throw new ArgumentOutOfRangeException();
262 if (null != _cached_str)
263 InternalEnsureCapacity (_length);
265 // Copy everything after the 'removed' part to the start
266 // of the removed part and truncate the sLength
267 if (_length - (startIndex + length) > 0)
268 String.CharCopy (_str, startIndex, _str, startIndex + length, _length - (startIndex + length));
275 public StringBuilder Replace (char oldChar, char newChar)
277 return Replace( oldChar, newChar, 0, _length);
280 public StringBuilder Replace (char oldChar, char newChar, int startIndex, int count)
282 // re-ordered to avoid possible integer overflow
283 if (startIndex > _length - count || startIndex < 0 || count < 0)
284 throw new ArgumentOutOfRangeException();
286 if (null != _cached_str)
287 InternalEnsureCapacity (_str.Length);
289 for (int replaceIterate = startIndex; replaceIterate < startIndex + count; replaceIterate++ ) {
290 if( _str [replaceIterate] == oldChar )
291 _str.InternalSetChar (replaceIterate, newChar);
297 public StringBuilder Replace( string oldValue, string newValue ) {
298 return Replace (oldValue, newValue, 0, _length);
301 public StringBuilder Replace( string oldValue, string newValue, int startIndex, int count )
303 if (oldValue == null)
304 throw new ArgumentNullException ("The old value cannot be null.");
306 if (startIndex < 0 || count < 0 || startIndex > _length - count)
307 throw new ArgumentOutOfRangeException ();
309 if (oldValue.Length == 0)
310 throw new ArgumentException ("The old value cannot be zero length.");
313 string replace = _str.Substring(startIndex, count).Replace(oldValue, newValue);
315 InternalEnsureCapacity (replace.Length + (_length - count));
317 string end = _str.Substring (startIndex + count, _length - startIndex - count );
319 String.CharCopy (_str, startIndex, replace, 0, replace.Length);
320 String.CharCopy (_str, startIndex + replace.Length, end, 0, end.Length);
322 _length = replace.Length + (_length - count);
328 /* The Append Methods */
329 public StringBuilder Append (char[] value)
334 int needed_cap = _length + value.Length;
335 if (null != _cached_str || _str.Length < needed_cap)
336 InternalEnsureCapacity (needed_cap);
338 String.CharCopy (_str, _length, value, 0, value.Length);
339 _length = needed_cap;
344 public StringBuilder Append (string value)
349 if (_length == 0 && value.Length < _maxCapacity && value.Length > _str.Length) {
350 _length = value.Length;
351 _str = _cached_str = value;
355 int needed_cap = _length + value.Length;
356 if (null != _cached_str || _str.Length < needed_cap)
357 InternalEnsureCapacity (needed_cap);
359 String.CharCopy (_str, _length, value, 0, value.Length);
360 _length = needed_cap;
364 public StringBuilder Append (bool value) {
365 return Append (value.ToString());
368 public StringBuilder Append (byte value) {
369 return Append (value.ToString());
372 public StringBuilder Append (decimal value) {
373 return Append (value.ToString());
376 public StringBuilder Append (double value) {
377 return Append (value.ToString());
380 public StringBuilder Append (short value) {
381 return Append (value.ToString());
384 public StringBuilder Append (int value) {
385 return Append (value.ToString());
388 public StringBuilder Append (long value) {
389 return Append (value.ToString());
392 public StringBuilder Append (object value) {
396 return Append (value.ToString());
399 [CLSCompliant(false)]
400 public StringBuilder Append (sbyte value) {
401 return Append (value.ToString());
404 public StringBuilder Append (float value) {
405 return Append (value.ToString());
408 [CLSCompliant(false)]
409 public StringBuilder Append (ushort value) {
410 return Append (value.ToString());
413 [CLSCompliant(false)]
414 public StringBuilder Append (uint value) {
415 return Append (value.ToString());
418 [CLSCompliant(false)]
419 public StringBuilder Append (ulong value) {
420 return Append (value.ToString());
423 public StringBuilder Append (char value)
425 int needed_cap = _length + 1;
426 if (null != _cached_str || _str.Length < needed_cap)
427 InternalEnsureCapacity (needed_cap);
429 _str.InternalSetChar(_length, value);
430 _length = needed_cap;
435 public StringBuilder Append (char value, int repeatCount)
437 if( repeatCount < 0 )
438 throw new ArgumentOutOfRangeException();
440 InternalEnsureCapacity (_length + repeatCount);
442 for (int i = 0; i < repeatCount; i++)
443 _str.InternalSetChar (_length++, value);
448 public StringBuilder Append( char[] value, int startIndex, int charCount )
451 if (!(startIndex == 0 && charCount == 0))
452 throw new ArgumentNullException ("value");
457 if ((charCount < 0 || startIndex < 0) || (startIndex > value.Length - charCount))
458 throw new ArgumentOutOfRangeException();
460 int needed_cap = _length + charCount;
461 InternalEnsureCapacity (needed_cap);
463 String.CharCopy (_str, _length, value, startIndex, charCount);
464 _length = needed_cap;
469 public StringBuilder Append (string value, int startIndex, int count)
472 if (startIndex != 0 && count != 0)
473 throw new ArgumentNullException ("value");
478 if ((count < 0 || startIndex < 0) || (startIndex > value.Length - count))
479 throw new ArgumentOutOfRangeException();
481 int needed_cap = _length + count;
482 if (null != _cached_str || _str.Length < needed_cap)
483 InternalEnsureCapacity (needed_cap);
485 String.CharCopy (_str, _length, value, startIndex, count);
487 _length = needed_cap;
494 public StringBuilder AppendLine ()
496 return Append (System.Environment.NewLine);
500 public StringBuilder AppendLine (string value)
502 return Append (value).Append (System.Environment.NewLine);
506 public StringBuilder AppendFormat (string format, params object[] args)
508 return AppendFormat (null, format, args);
511 public StringBuilder AppendFormat (IFormatProvider provider,
513 params object[] args)
515 String.FormatHelper (this, provider, format, args);
524 StringBuilder AppendFormat (string format, object arg0)
526 return AppendFormat (null, format, new object [] { arg0 });
534 StringBuilder AppendFormat (string format, object arg0, object arg1)
536 return AppendFormat (null, format, new object [] { arg0, arg1 });
544 StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2)
546 return AppendFormat (null, format, new object [] { arg0, arg1, arg2 });
549 /* The Insert Functions */
551 public StringBuilder Insert (int index, char[] value)
553 return Insert (index, new string (value));
556 public StringBuilder Insert (int index, string value)
558 if( index > _length || index < 0)
559 throw new ArgumentOutOfRangeException();
561 if (value == null || value.Length == 0)
564 InternalEnsureCapacity (_length + value.Length);
566 // Move everything to the right of the insert point across
567 String.CharCopyReverse (_str, index + value.Length, _str, index, _length - index);
569 // Copy in stuff from the insert buffer
570 String.CharCopy (_str, index, value, 0, value.Length);
572 _length += value.Length;
577 public StringBuilder Insert( int index, bool value ) {
578 return Insert (index, value.ToString());
581 public StringBuilder Insert( int index, byte value ) {
582 return Insert (index, value.ToString());
585 public StringBuilder Insert( int index, char value)
587 if (index > _length || index < 0)
588 throw new ArgumentOutOfRangeException ("index");
590 InternalEnsureCapacity (_length + 1);
592 // Move everything to the right of the insert point across
593 String.CharCopyReverse (_str, index + 1, _str, index, _length - index);
595 _str.InternalSetChar (index, value);
601 public StringBuilder Insert( int index, decimal value ) {
602 return Insert (index, value.ToString());
605 public StringBuilder Insert( int index, double value ) {
606 return Insert (index, value.ToString());
609 public StringBuilder Insert( int index, short value ) {
610 return Insert (index, value.ToString());
613 public StringBuilder Insert( int index, int value ) {
614 return Insert (index, value.ToString());
617 public StringBuilder Insert( int index, long value ) {
618 return Insert (index, value.ToString());
621 public StringBuilder Insert( int index, object value ) {
622 return Insert (index, value.ToString());
625 [CLSCompliant(false)]
626 public StringBuilder Insert( int index, sbyte value ) {
627 return Insert (index, value.ToString() );
630 public StringBuilder Insert (int index, float value) {
631 return Insert (index, value.ToString() );
634 [CLSCompliant(false)]
635 public StringBuilder Insert (int index, ushort value) {
636 return Insert (index, value.ToString() );
639 [CLSCompliant(false)]
640 public StringBuilder Insert (int index, uint value) {
641 return Insert ( index, value.ToString() );
644 [CLSCompliant(false)]
645 public StringBuilder Insert (int index, ulong value) {
646 return Insert ( index, value.ToString() );
649 public StringBuilder Insert (int index, string value, int count)
651 // LAMESPEC: The spec says to throw an exception if
652 // count < 0, while MS throws even for count < 1!
654 throw new ArgumentOutOfRangeException();
656 if (value != null && value != String.Empty)
657 for (int insertCount = 0; insertCount < count; insertCount++)
658 Insert( index, value );
663 public StringBuilder Insert (int index, char [] value, int startIndex, int charCount)
666 if (startIndex == 0 && charCount == 0)
669 throw new ArgumentNullException ("value");
672 if (charCount < 0 || startIndex < 0 || startIndex > value.Length - charCount)
673 throw new ArgumentOutOfRangeException ();
675 return Insert (index, new String (value, startIndex, charCount));
678 private void InternalEnsureCapacity (int size)
680 if (size > _str.Length || (object) _cached_str == (object) _str) {
681 int capacity = _str.Length;
683 // Try double buffer, if that doesn't work, set the length as capacity
684 if (size > capacity) {
686 // The first time a string is appended, we just set _cached_str
687 // and _str to it. This allows us to do some optimizations.
688 // Below, we take this into account.
689 if ((object) _cached_str == (object) _str && capacity < constDefaultCapacity)
690 capacity = constDefaultCapacity;
692 capacity = capacity << 1;
696 if (capacity >= Int32.MaxValue || capacity < 0)
697 capacity = Int32.MaxValue;
699 if (capacity > _maxCapacity && size <= _maxCapacity)
700 capacity = _maxCapacity;
702 if (capacity > _maxCapacity)
703 throw new ArgumentOutOfRangeException ("size", "capacity was less than the current size.");
706 string tmp = String.InternalAllocateStr (capacity);
708 String.CharCopy (tmp, 0, _str, 0, _length);
718 public void CopyTo (int sourceIndex, char [] destination, int destinationIndex, int count)
720 if (destination == null)
721 throw new ArgumentNullException ("destination");
722 if ((Length - count < sourceIndex) ||
723 (destination.Length -count < destinationIndex) ||
724 (sourceIndex < 0 || destinationIndex < 0 || count < 0))
725 throw new ArgumentOutOfRangeException ();
727 for (int i = 0; i < count; i++)
728 destination [destinationIndex+i] = _str [sourceIndex+i];
731 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
733 info.AddValue ("m_MaxCapacity", _maxCapacity);
734 info.AddValue ("Capacity", Capacity);
735 info.AddValue ("m_StringValue", ToString ());
736 info.AddValue ("m_currentThread", 0);
739 StringBuilder (SerializationInfo info, StreamingContext context)
741 string s = info.GetString ("m_StringValue");
745 _str = _cached_str = s;
747 _maxCapacity = info.GetInt32 ("m_MaxCapacity");
748 if (_maxCapacity < 0)
749 _maxCapacity = Int32.MaxValue;
750 Capacity = info.GetInt32 ("Capacity");