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.InternalStrcpy(_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 _cached_str = _str.Substring(0, _length);
211 _str.InternalSetLength(_length);
216 public string ToString (int startIndex, int length)
218 // re-ordered to avoid possible integer overflow
219 if (startIndex < 0 || length < 0 || startIndex > _length - length)
220 throw new ArgumentOutOfRangeException();
222 return _str.Substring (startIndex, length);
225 public int EnsureCapacity (int capacity)
228 throw new ArgumentOutOfRangeException ("Capacity must be greater than 0." );
230 if( capacity <= _str.Length )
233 InternalEnsureCapacity (capacity);
238 public bool Equals (StringBuilder sb)
240 if (((object)sb) == null)
243 if (_length == sb.Length && _str == sb._str )
249 public StringBuilder Remove (int startIndex, int length)
251 // re-ordered to avoid possible integer overflow
252 if (startIndex < 0 || length < 0 || startIndex > _length - length)
253 throw new ArgumentOutOfRangeException();
255 if (null != _cached_str)
256 InternalEnsureCapacity (_length);
258 // Copy everything after the 'removed' part to the start
259 // of the removed part and truncate the sLength
260 if (_length - (startIndex + length) > 0)
261 String.InternalStrcpy (_str, startIndex, _str, startIndex + length, _length - (startIndex + length));
268 public StringBuilder Replace (char oldChar, char newChar)
270 return Replace( oldChar, newChar, 0, _length);
273 public StringBuilder Replace (char oldChar, char newChar, int startIndex, int count)
275 // re-ordered to avoid possible integer overflow
276 if (startIndex > _length - count || startIndex < 0 || count < 0)
277 throw new ArgumentOutOfRangeException();
279 if (null != _cached_str)
280 InternalEnsureCapacity (_str.Length);
282 for (int replaceIterate = startIndex; replaceIterate < startIndex + count; replaceIterate++ ) {
283 if( _str [replaceIterate] == oldChar )
284 _str.InternalSetChar (replaceIterate, newChar);
290 public StringBuilder Replace( string oldValue, string newValue ) {
291 return Replace (oldValue, newValue, 0, _length);
294 public StringBuilder Replace( string oldValue, string newValue, int startIndex, int count )
296 if (oldValue == null)
297 throw new ArgumentNullException ("The old value cannot be null.");
299 if (startIndex < 0 || count < 0 || startIndex > _length - count)
300 throw new ArgumentOutOfRangeException ();
302 if (oldValue.Length == 0)
303 throw new ArgumentException ("The old value cannot be zero length.");
306 string replace = _str.Substring(startIndex, count).Replace(oldValue, newValue);
308 InternalEnsureCapacity (replace.Length + (_length - count));
310 string end = _str.Substring (startIndex + count, _length - startIndex - count );
312 String.InternalStrcpy (_str, startIndex, replace);
313 String.InternalStrcpy (_str, startIndex + replace.Length, end);
315 _length = replace.Length + (_length - count);
321 /* The Append Methods */
322 public StringBuilder Append (char[] value)
327 int needed_cap = _length + value.Length;
328 if (null != _cached_str || _str.Length < needed_cap)
329 InternalEnsureCapacity (needed_cap);
331 String.InternalStrcpy (_str, _length, value);
332 _length = needed_cap;
337 public StringBuilder Append (string value)
342 if (_length == 0 && value.Length < _maxCapacity && value.Length > _str.Length) {
343 _length = value.Length;
344 _str = _cached_str = value;
348 int needed_cap = _length + value.Length;
349 if (null != _cached_str || _str.Length < needed_cap)
350 InternalEnsureCapacity (needed_cap);
352 String.InternalStrcpy (_str, _length, value);
353 _length = needed_cap;
357 public StringBuilder Append (bool value) {
358 return Append (value.ToString());
361 public StringBuilder Append (byte value) {
362 return Append (value.ToString());
365 public StringBuilder Append (decimal value) {
366 return Append (value.ToString());
369 public StringBuilder Append (double value) {
370 return Append (value.ToString());
373 public StringBuilder Append (short value) {
374 return Append (value.ToString());
377 public StringBuilder Append (int value) {
378 return Append (value.ToString());
381 public StringBuilder Append (long value) {
382 return Append (value.ToString());
385 public StringBuilder Append (object value) {
389 return Append (value.ToString());
392 [CLSCompliant(false)]
393 public StringBuilder Append (sbyte value) {
394 return Append (value.ToString());
397 public StringBuilder Append (float value) {
398 return Append (value.ToString());
401 [CLSCompliant(false)]
402 public StringBuilder Append (ushort value) {
403 return Append (value.ToString());
406 [CLSCompliant(false)]
407 public StringBuilder Append (uint value) {
408 return Append (value.ToString());
411 [CLSCompliant(false)]
412 public StringBuilder Append (ulong value) {
413 return Append (value.ToString());
416 public StringBuilder Append (char value)
418 int needed_cap = _length + 1;
419 if (null != _cached_str || _str.Length < needed_cap)
420 InternalEnsureCapacity (needed_cap);
422 _str.InternalSetChar(_length, value);
423 _length = needed_cap;
428 public StringBuilder Append (char value, int repeatCount)
430 if( repeatCount < 0 )
431 throw new ArgumentOutOfRangeException();
433 InternalEnsureCapacity (_length + repeatCount);
435 for (int i = 0; i < repeatCount; i++)
436 _str.InternalSetChar (_length++, value);
441 public StringBuilder Append( char[] value, int startIndex, int charCount )
444 if (!(startIndex == 0 && charCount == 0))
445 throw new ArgumentNullException ("value");
450 if ((charCount < 0 || startIndex < 0) || (startIndex > value.Length - charCount))
451 throw new ArgumentOutOfRangeException();
453 int needed_cap = _length + charCount;
454 InternalEnsureCapacity (needed_cap);
456 String.InternalStrcpy (_str, _length, value, startIndex, charCount);
457 _length = needed_cap;
462 public StringBuilder Append (string value, int startIndex, int count)
465 if (startIndex != 0 && count != 0)
466 throw new ArgumentNullException ("value");
471 if ((count < 0 || startIndex < 0) || (startIndex > value.Length - count))
472 throw new ArgumentOutOfRangeException();
474 int needed_cap = _length + count;
475 if (null != _cached_str || _str.Length < needed_cap)
476 InternalEnsureCapacity (needed_cap);
478 String.InternalStrcpy (_str, _length, value, startIndex, count);
480 _length = needed_cap;
487 public StringBuilder AppendLine ()
489 return Append (System.Environment.NewLine);
493 public StringBuilder AppendLine (string value)
495 return Append (value).Append (System.Environment.NewLine);
499 public StringBuilder AppendFormat (string format, params object[] args)
501 return AppendFormat (null, format, args);
504 public StringBuilder AppendFormat (IFormatProvider provider,
506 params object[] args)
508 String.FormatHelper (this, provider, format, args);
517 StringBuilder AppendFormat (string format, object arg0)
519 return AppendFormat (null, format, new object [] { arg0 });
527 StringBuilder AppendFormat (string format, object arg0, object arg1)
529 return AppendFormat (null, format, new object [] { arg0, arg1 });
537 StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2)
539 return AppendFormat (null, format, new object [] { arg0, arg1, arg2 });
542 /* The Insert Functions */
544 public StringBuilder Insert (int index, char[] value)
546 return Insert (index, new string (value));
549 public StringBuilder Insert (int index, string value)
551 if( index > _length || index < 0)
552 throw new ArgumentOutOfRangeException();
554 if (value == null || value.Length == 0)
557 InternalEnsureCapacity (_length + value.Length);
559 // Move everything to the right of the insert point across
560 String.InternalStrcpy (_str, index + value.Length, _str, index, _length - index);
562 // Copy in stuff from the insert buffer
563 String.InternalStrcpy (_str, index, value);
565 _length += value.Length;
570 public StringBuilder Insert( int index, bool value ) {
571 return Insert (index, value.ToString());
574 public StringBuilder Insert( int index, byte value ) {
575 return Insert (index, value.ToString());
578 public StringBuilder Insert( int index, char value)
580 if (index > _length || index < 0)
581 throw new ArgumentOutOfRangeException ("index");
583 InternalEnsureCapacity (_length + 1);
585 // Move everything to the right of the insert point across
586 String.InternalStrcpy (_str, index + 1, _str, index, _length - index);
588 _str.InternalSetChar (index, value);
594 public StringBuilder Insert( int index, decimal value ) {
595 return Insert (index, value.ToString());
598 public StringBuilder Insert( int index, double value ) {
599 return Insert (index, value.ToString());
602 public StringBuilder Insert( int index, short value ) {
603 return Insert (index, value.ToString());
606 public StringBuilder Insert( int index, int value ) {
607 return Insert (index, value.ToString());
610 public StringBuilder Insert( int index, long value ) {
611 return Insert (index, value.ToString());
614 public StringBuilder Insert( int index, object value ) {
615 return Insert (index, value.ToString());
618 [CLSCompliant(false)]
619 public StringBuilder Insert( int index, sbyte value ) {
620 return Insert (index, value.ToString() );
623 public StringBuilder Insert (int index, float value) {
624 return Insert (index, value.ToString() );
627 [CLSCompliant(false)]
628 public StringBuilder Insert (int index, ushort value) {
629 return Insert (index, value.ToString() );
632 [CLSCompliant(false)]
633 public StringBuilder Insert (int index, uint value) {
634 return Insert ( index, value.ToString() );
637 [CLSCompliant(false)]
638 public StringBuilder Insert (int index, ulong value) {
639 return Insert ( index, value.ToString() );
642 public StringBuilder Insert (int index, string value, int count)
644 // LAMESPEC: The spec says to throw an exception if
645 // count < 0, while MS throws even for count < 1!
647 throw new ArgumentOutOfRangeException();
649 if (value != null && value != String.Empty)
650 for (int insertCount = 0; insertCount < count; insertCount++)
651 Insert( index, value );
656 public StringBuilder Insert (int index, char [] value, int startIndex, int charCount)
659 if (startIndex == 0 && charCount == 0)
662 throw new ArgumentNullException ("value");
665 if (charCount < 0 || startIndex < 0 || startIndex > value.Length - charCount)
666 throw new ArgumentOutOfRangeException ();
668 return Insert (index, new String (value, startIndex, charCount));
671 private void InternalEnsureCapacity (int size)
673 if (size > _str.Length || (object) _cached_str == (object) _str) {
674 int capacity = _str.Length;
676 // Try double buffer, if that doesn't work, set the length as capacity
677 if (size > capacity) {
679 // The first time a string is appended, we just set _cached_str
680 // and _str to it. This allows us to do some optimizations.
681 // Below, we take this into account.
682 if ((object) _cached_str == (object) _str && capacity < constDefaultCapacity)
683 capacity = constDefaultCapacity;
685 capacity = capacity << 1;
689 if (capacity >= Int32.MaxValue || capacity < 0)
690 capacity = Int32.MaxValue;
692 if (capacity > _maxCapacity && size <= _maxCapacity)
693 capacity = _maxCapacity;
695 if (capacity > _maxCapacity)
696 throw new ArgumentOutOfRangeException ("size", "capacity was less than the current size.");
699 string tmp = String.InternalAllocateStr (capacity);
701 String.InternalStrcpy (tmp, 0, _str, 0, _length);
711 public void CopyTo (int sourceIndex, char [] destination, int destinationIndex, int count)
713 if (destination == null)
714 throw new ArgumentNullException ("destination");
715 if ((Length - count < sourceIndex) ||
716 (destination.Length -count < destinationIndex) ||
717 (sourceIndex < 0 || destinationIndex < 0 || count < 0))
718 throw new ArgumentOutOfRangeException ();
720 for (int i = 0; i < count; i++)
721 destination [destinationIndex+i] = _str [sourceIndex+i];
724 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
726 info.AddValue ("m_MaxCapacity", _maxCapacity);
727 info.AddValue ("Capacity", Capacity);
728 info.AddValue ("m_StringValue", ToString ());
729 info.AddValue ("m_currentThread", 0);
732 StringBuilder (SerializationInfo info, StreamingContext context)
734 string s = info.GetString ("m_StringValue");
738 _str = _cached_str = s;
740 _maxCapacity = info.GetInt32 ("m_MaxCapacity");
741 if (_maxCapacity < 0)
742 _maxCapacity = Int32.MaxValue;
743 Capacity = info.GetInt32 ("Capacity");