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)
19 // Copyright 2011 Xamarin Inc
21 // Permission is hereby granted, free of charge, to any person obtaining
22 // a copy of this software and associated documentation files (the
23 // "Software"), to deal in the Software without restriction, including
24 // without limitation the rights to use, copy, modify, merge, publish,
25 // distribute, sublicense, and/or sell copies of the Software, and to
26 // permit persons to whom the Software is furnished to do so, subject to
27 // the following conditions:
29 // The above copyright notice and this permission notice shall be
30 // included in all copies or substantial portions of the Software.
32 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
33 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
34 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
35 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
36 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
37 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
38 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
40 using System.Runtime.Serialization;
41 using System.Runtime.CompilerServices;
42 using System.Runtime.InteropServices;
44 namespace System.Text {
48 [MonoLimitation ("Serialization format not compatible with .NET")]
49 public sealed class StringBuilder : ISerializable
53 private string _cached_str;
55 private int _maxCapacity;
56 private const int constDefaultCapacity = 16;
58 public StringBuilder(string value, int startIndex, int length, int capacity)
59 : this (value, startIndex, length, capacity, Int32.MaxValue)
63 private StringBuilder(string value, int startIndex, int length, int capacity, int maxCapacity)
65 // first, check the parameters and throw appropriate exceptions if needed
69 // make sure startIndex is zero or positive
71 throw new System.ArgumentOutOfRangeException ("startIndex", startIndex, "StartIndex cannot be less than zero.");
73 // make sure length is zero or positive
75 throw new System.ArgumentOutOfRangeException ("length", length, "Length cannot be less than zero.");
78 throw new System.ArgumentOutOfRangeException ("capacity", capacity, "capacity must be greater than zero.");
81 throw new System.ArgumentOutOfRangeException ("maxCapacity", "maxCapacity is less than one.");
82 if (capacity > maxCapacity)
83 throw new System.ArgumentOutOfRangeException ("capacity", "Capacity exceeds maximum capacity.");
85 // make sure startIndex and length give a valid substring of value
86 // re-ordered to avoid possible integer overflow
87 if (startIndex > value.Length - length)
88 throw new System.ArgumentOutOfRangeException ("startIndex", startIndex, "StartIndex and length must refer to a location within the string.");
91 if (maxCapacity > constDefaultCapacity)
92 capacity = constDefaultCapacity;
94 _str = _cached_str = String.Empty;
96 _maxCapacity = maxCapacity;
99 _str = String.InternalAllocateStr ((length > capacity) ? length : capacity);
101 String.CharCopy (_str, 0, value, startIndex, length);
106 public StringBuilder () : this (null) {}
108 public StringBuilder(int capacity) : this (String.Empty, 0, 0, capacity) {}
110 public StringBuilder(int capacity, int maxCapacity) : this (String.Empty, 0, 0, capacity, maxCapacity) { }
112 public StringBuilder (string value)
115 * This is an optimization to avoid allocating the internal string
116 * until the first Append () call.
117 * The runtime pinvoke marshalling code needs to be aware of this.
122 _length = value.Length;
123 _str = _cached_str = value;
124 _maxCapacity = Int32.MaxValue;
127 public StringBuilder( string value, int capacity) : this(value == null ? "" : value, 0, value == null ? 0 : value.Length, capacity) {}
129 public int MaxCapacity {
135 public int Capacity {
137 if (_str.Length == 0)
138 return Math.Min (_maxCapacity, constDefaultCapacity);
145 throw new ArgumentException( "Capacity must be larger than length" );
147 if (value > _maxCapacity)
148 throw new ArgumentOutOfRangeException ("value", "Should be less than or equal to MaxCapacity");
150 InternalEnsureCapacity(value);
160 if( value < 0 || value > _maxCapacity)
161 throw new ArgumentOutOfRangeException();
163 if (value == _length)
166 if (value < _length) {
167 // LAMESPEC: The spec is unclear as to what to do
168 // with the capacity when truncating the string.
170 // Do as MS, keep the capacity
172 // Make sure that we invalidate any cached string.
173 InternalEnsureCapacity (value);
176 // Expand the capacity to the new length and
177 // pad the string with NULL characters.
178 Append('\0', value - _length);
183 [IndexerName("Chars")]
184 public char this [int index] {
186 if (index >= _length || index < 0)
187 throw new IndexOutOfRangeException();
193 if (index >= _length || index < 0)
194 throw new IndexOutOfRangeException();
196 if (null != _cached_str)
197 InternalEnsureCapacity (_length);
199 _str.InternalSetChar (index, value);
203 public override string ToString ()
208 if (null != _cached_str)
211 // If we only have a half-full buffer we return a new string.
212 if (_length < (_str.Length >> 1) || (_str.Length > string.LOS_limit && _length <= string.LOS_limit))
214 // use String.SubstringUnchecked instead of String.Substring
215 // as the former is guaranteed to create a new string object
216 _cached_str = _str.SubstringUnchecked (0, _length);
221 _str.InternalSetLength(_length);
226 public string ToString (int startIndex, int length)
228 // re-ordered to avoid possible integer overflow
229 if (startIndex < 0 || length < 0 || startIndex > _length - length)
230 throw new ArgumentOutOfRangeException();
232 // use String.SubstringUnchecked instead of String.Substring
233 // as the former is guaranteed to create a new string object
234 if (startIndex == 0 && length == _length)
237 return _str.SubstringUnchecked (startIndex, length);
240 public int EnsureCapacity (int capacity)
243 throw new ArgumentOutOfRangeException ("Capacity must be greater than 0." );
245 if( capacity <= _str.Length )
248 InternalEnsureCapacity (capacity);
253 public bool Equals (StringBuilder sb)
255 if (((object)sb) == null)
258 if (_length == sb.Length && _str == sb._str )
264 public StringBuilder Remove (int startIndex, int length)
266 // re-ordered to avoid possible integer overflow
267 if (startIndex < 0 || length < 0 || startIndex > _length - length)
268 throw new ArgumentOutOfRangeException();
270 if (null != _cached_str)
271 InternalEnsureCapacity (_length);
273 // Copy everything after the 'removed' part to the start
274 // of the removed part and truncate the sLength
275 if (_length - (startIndex + length) > 0)
276 String.CharCopy (_str, startIndex, _str, startIndex + length, _length - (startIndex + length));
283 public StringBuilder Replace (char oldChar, char newChar)
285 return Replace( oldChar, newChar, 0, _length);
288 public StringBuilder Replace (char oldChar, char newChar, int startIndex, int count)
290 // re-ordered to avoid possible integer overflow
291 if (startIndex > _length - count || startIndex < 0 || count < 0)
292 throw new ArgumentOutOfRangeException();
294 if (null != _cached_str)
295 InternalEnsureCapacity (_str.Length);
297 for (int replaceIterate = startIndex; replaceIterate < startIndex + count; replaceIterate++ ) {
298 if( _str [replaceIterate] == oldChar )
299 _str.InternalSetChar (replaceIterate, newChar);
305 public StringBuilder Replace( string oldValue, string newValue ) {
306 return Replace (oldValue, newValue, 0, _length);
309 public StringBuilder Replace( string oldValue, string newValue, int startIndex, int count )
311 if (oldValue == null)
312 throw new ArgumentNullException ("The old value cannot be null.");
314 if (startIndex < 0 || count < 0 || startIndex > _length - count)
315 throw new ArgumentOutOfRangeException ();
317 if (oldValue.Length == 0)
318 throw new ArgumentException ("The old value cannot be zero length.");
320 string substr = _str.Substring(startIndex, count);
321 string replace = substr.Replace(oldValue, newValue);
322 // return early if no oldValue was found
323 if ((object) replace == (object) substr)
326 InternalEnsureCapacity (replace.Length + (_length - count));
329 if (replace.Length < count)
330 String.CharCopy (_str, startIndex + replace.Length, _str, startIndex + count, _length - startIndex - count);
331 else if (replace.Length > count)
332 String.CharCopyReverse (_str, startIndex + replace.Length, _str, startIndex + count, _length - startIndex - count);
334 // copy middle part back into _str
335 String.CharCopy (_str, startIndex, replace, 0, replace.Length);
337 _length = replace.Length + (_length - count);
343 /* The Append Methods */
344 public StringBuilder Append (char[] value)
349 int needed_cap = _length + value.Length;
350 if (null != _cached_str || _str.Length < needed_cap)
351 InternalEnsureCapacity (needed_cap);
353 String.CharCopy (_str, _length, value, 0, value.Length);
354 _length = needed_cap;
359 public StringBuilder Append (string value)
364 if (_length == 0 && value.Length < _maxCapacity && value.Length > _str.Length) {
365 _length = value.Length;
366 _str = _cached_str = value;
370 int needed_cap = _length + value.Length;
371 if (null != _cached_str || _str.Length < needed_cap)
372 InternalEnsureCapacity (needed_cap);
374 String.CharCopy (_str, _length, value, 0, value.Length);
375 _length = needed_cap;
379 public StringBuilder Append (bool value) {
380 return Append (value.ToString());
383 public StringBuilder Append (byte value) {
384 return Append (value.ToString());
387 public StringBuilder Append (decimal value) {
388 return Append (value.ToString());
391 public StringBuilder Append (double value) {
392 return Append (value.ToString());
395 public StringBuilder Append (short value) {
396 return Append (value.ToString());
399 public StringBuilder Append (int value) {
400 return Append (value.ToString());
403 public StringBuilder Append (long value) {
404 return Append (value.ToString());
407 public StringBuilder Append (object value) {
411 return Append (value.ToString());
414 [CLSCompliant(false)]
415 public StringBuilder Append (sbyte value) {
416 return Append (value.ToString());
419 public StringBuilder Append (float value) {
420 return Append (value.ToString());
423 [CLSCompliant(false)]
424 public StringBuilder Append (ushort value) {
425 return Append (value.ToString());
428 [CLSCompliant(false)]
429 public StringBuilder Append (uint value) {
430 return Append (value.ToString());
433 [CLSCompliant(false)]
434 public StringBuilder Append (ulong value) {
435 return Append (value.ToString());
438 public StringBuilder Append (char value)
440 int needed_cap = _length + 1;
441 if (null != _cached_str || _str.Length < needed_cap)
442 InternalEnsureCapacity (needed_cap);
444 _str.InternalSetChar(_length, value);
445 _length = needed_cap;
450 public StringBuilder Append (char value, int repeatCount)
452 if( repeatCount < 0 )
453 throw new ArgumentOutOfRangeException();
455 InternalEnsureCapacity (_length + repeatCount);
457 for (int i = 0; i < repeatCount; i++)
458 _str.InternalSetChar (_length++, value);
463 public StringBuilder Append( char[] value, int startIndex, int charCount )
466 if (!(startIndex == 0 && charCount == 0))
467 throw new ArgumentNullException ("value");
472 if ((charCount < 0 || startIndex < 0) || (startIndex > value.Length - charCount))
473 throw new ArgumentOutOfRangeException();
475 int needed_cap = _length + charCount;
476 InternalEnsureCapacity (needed_cap);
478 String.CharCopy (_str, _length, value, startIndex, charCount);
479 _length = needed_cap;
484 public StringBuilder Append (string value, int startIndex, int count)
487 if (startIndex != 0 && count != 0)
488 throw new ArgumentNullException ("value");
493 if ((count < 0 || startIndex < 0) || (startIndex > value.Length - count))
494 throw new ArgumentOutOfRangeException();
496 int needed_cap = _length + count;
497 if (null != _cached_str || _str.Length < needed_cap)
498 InternalEnsureCapacity (needed_cap);
500 String.CharCopy (_str, _length, value, startIndex, count);
502 _length = needed_cap;
507 #if NET_4_0 || MOONLIGHT || MOBILE
508 public StringBuilder Clear ()
516 public StringBuilder AppendLine ()
518 return Append (System.Environment.NewLine);
522 public StringBuilder AppendLine (string value)
524 return Append (value).Append (System.Environment.NewLine);
527 public StringBuilder AppendFormat (string format, params object[] args)
529 return AppendFormat (null, format, args);
532 public StringBuilder AppendFormat (IFormatProvider provider,
534 params object[] args)
536 String.FormatHelper (this, provider, format, args);
545 StringBuilder AppendFormat (string format, object arg0)
547 return AppendFormat (null, format, new object [] { arg0 });
555 StringBuilder AppendFormat (string format, object arg0, object arg1)
557 return AppendFormat (null, format, new object [] { arg0, arg1 });
565 StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2)
567 return AppendFormat (null, format, new object [] { arg0, arg1, arg2 });
570 /* The Insert Functions */
572 public StringBuilder Insert (int index, char[] value)
574 return Insert (index, new string (value));
577 public StringBuilder Insert (int index, string value)
579 if( index > _length || index < 0)
580 throw new ArgumentOutOfRangeException();
582 if (value == null || value.Length == 0)
585 InternalEnsureCapacity (_length + value.Length);
587 // Move everything to the right of the insert point across
588 String.CharCopyReverse (_str, index + value.Length, _str, index, _length - index);
590 // Copy in stuff from the insert buffer
591 String.CharCopy (_str, index, value, 0, value.Length);
593 _length += value.Length;
598 public StringBuilder Insert( int index, bool value ) {
599 return Insert (index, value.ToString());
602 public StringBuilder Insert( int index, byte value ) {
603 return Insert (index, value.ToString());
606 public StringBuilder Insert( int index, char value)
608 if (index > _length || index < 0)
609 throw new ArgumentOutOfRangeException ("index");
611 InternalEnsureCapacity (_length + 1);
613 // Move everything to the right of the insert point across
614 String.CharCopyReverse (_str, index + 1, _str, index, _length - index);
616 _str.InternalSetChar (index, value);
622 public StringBuilder Insert( int index, decimal value ) {
623 return Insert (index, value.ToString());
626 public StringBuilder Insert( int index, double value ) {
627 return Insert (index, value.ToString());
630 public StringBuilder Insert( int index, short value ) {
631 return Insert (index, value.ToString());
634 public StringBuilder Insert( int index, int value ) {
635 return Insert (index, value.ToString());
638 public StringBuilder Insert( int index, long value ) {
639 return Insert (index, value.ToString());
642 public StringBuilder Insert( int index, object value ) {
643 return Insert (index, value.ToString());
646 [CLSCompliant(false)]
647 public StringBuilder Insert( int index, sbyte value ) {
648 return Insert (index, value.ToString() );
651 public StringBuilder Insert (int index, float value) {
652 return Insert (index, value.ToString() );
655 [CLSCompliant(false)]
656 public StringBuilder Insert (int index, ushort value) {
657 return Insert (index, value.ToString() );
660 [CLSCompliant(false)]
661 public StringBuilder Insert (int index, uint value) {
662 return Insert ( index, value.ToString() );
665 [CLSCompliant(false)]
666 public StringBuilder Insert (int index, ulong value) {
667 return Insert ( index, value.ToString() );
670 public StringBuilder Insert (int index, string value, int count)
672 // LAMESPEC: The spec says to throw an exception if
673 // count < 0, while MS throws even for count < 1!
675 throw new ArgumentOutOfRangeException();
677 if (value != null && value != String.Empty)
678 for (int insertCount = 0; insertCount < count; insertCount++)
679 Insert( index, value );
684 public StringBuilder Insert (int index, char [] value, int startIndex, int charCount)
687 if (startIndex == 0 && charCount == 0)
690 throw new ArgumentNullException ("value");
693 if (charCount < 0 || startIndex < 0 || startIndex > value.Length - charCount)
694 throw new ArgumentOutOfRangeException ();
696 return Insert (index, new String (value, startIndex, charCount));
699 private void InternalEnsureCapacity (int size)
701 if (size > _str.Length || (object) _cached_str == (object) _str) {
702 int capacity = _str.Length;
704 // Try double buffer, if that doesn't work, set the length as capacity
705 if (size > capacity) {
707 // The first time a string is appended, we just set _cached_str
708 // and _str to it. This allows us to do some optimizations.
709 // Below, we take this into account.
710 if ((object) _cached_str == (object) _str && capacity < constDefaultCapacity)
711 capacity = constDefaultCapacity;
713 capacity = capacity << 1;
717 if (capacity >= Int32.MaxValue || capacity < 0)
718 capacity = Int32.MaxValue;
720 if (capacity > _maxCapacity && size <= _maxCapacity)
721 capacity = _maxCapacity;
723 if (capacity > _maxCapacity)
724 throw new ArgumentOutOfRangeException ("size", "capacity was less than the current size.");
727 string tmp = String.InternalAllocateStr (capacity);
729 String.CharCopy (tmp, 0, _str, 0, _length);
738 public void CopyTo (int sourceIndex, char [] destination, int destinationIndex, int count)
740 if (destination == null)
741 throw new ArgumentNullException ("destination");
742 if ((Length - count < sourceIndex) ||
743 (destination.Length -count < destinationIndex) ||
744 (sourceIndex < 0 || destinationIndex < 0 || count < 0))
745 throw new ArgumentOutOfRangeException ();
747 for (int i = 0; i < count; i++)
748 destination [destinationIndex+i] = _str [sourceIndex+i];
751 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
753 info.AddValue ("m_MaxCapacity", _maxCapacity);
754 info.AddValue ("Capacity", Capacity);
755 info.AddValue ("m_StringValue", ToString ());
756 info.AddValue ("m_currentThread", 0);
759 StringBuilder (SerializationInfo info, StreamingContext context)
761 string s = info.GetString ("m_StringValue");
765 _str = _cached_str = s;
767 _maxCapacity = info.GetInt32 ("m_MaxCapacity");
768 if (_maxCapacity < 0)
769 _maxCapacity = Int32.MaxValue;
770 Capacity = info.GetInt32 ("Capacity");