2007-07-28 Miguel de Icaza <miguel@novell.com>
[mono.git] / mcs / class / corlib / System.Text / StringBuilder.cs
1 // -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
2 //
3 // System.Text.StringBuilder
4 //
5 // Authors: 
6 //   Marcin Szczepanski (marcins@zipworld.com.au)
7 //   Paolo Molaro (lupus@ximian.com)
8 //   Patrik Torstensson
9 //
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.
15 //
16
17 //
18 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
19 //
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:
27 // 
28 // The above copyright notice and this permission notice shall be
29 // included in all copies or substantial portions of the Software.
30 // 
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.
38 //
39 using System.Runtime.Serialization;
40 using System.Runtime.CompilerServices;
41 using System.Runtime.InteropServices;
42
43 namespace System.Text {
44         
45         [Serializable]
46 #if NET_2_0
47         [ComVisible (true)]
48 #endif
49         [MonoTODO ("Serialization format not compatible with .NET")]
50         public sealed class StringBuilder
51 #if NET_2_0
52                 : ISerializable
53 #endif
54         {
55                 private int _length;
56                 private string _str;
57                 private string _cached_str;
58                 
59                 private int _maxCapacity = Int32.MaxValue;
60                 private const int constDefaultCapacity = 16;
61
62                 public StringBuilder(string value, int startIndex, int length, int capacity) 
63                 {
64                         // first, check the parameters and throw appropriate exceptions if needed
65                         if (null == value)
66                                 value = "";
67
68                         // make sure startIndex is zero or positive
69                         if (startIndex < 0)
70                                 throw new System.ArgumentOutOfRangeException ("startIndex", startIndex, "StartIndex cannot be less than zero.");
71
72                         // make sure length is zero or positive
73                         if(length < 0)
74                                 throw new System.ArgumentOutOfRangeException ("length", length, "Length cannot be less than zero.");
75
76                         if (capacity < 0)
77                                 throw new System.ArgumentOutOfRangeException ("capacity", capacity, "capacity must be greater than zero.");
78
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.");
83
84                         if (capacity == 0)
85                                 capacity = constDefaultCapacity;
86
87                         _str = String.InternalAllocateStr ((length > capacity) ? length : capacity);
88                         if (length > 0)
89                                 String.InternalStrcpy(_str, 0, value, startIndex, length);
90                         
91                         _length = length;
92                 }
93
94                 public StringBuilder () : this (null) {}
95
96                 public StringBuilder(int capacity) : this (String.Empty, 0, 0, capacity) {}
97
98                 public StringBuilder(int capacity, int maxCapacity) : this (String.Empty, 0, 0, capacity) {
99                         if (maxCapacity < 1)
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.");
103
104                         _maxCapacity = maxCapacity;
105                 }
106
107                 public StringBuilder (string value)
108                 {
109                         /*
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.
113                          */
114                         if (null == value)
115                                 value = "";
116                         
117                         _length = value.Length;
118                         _str = _cached_str = value;
119                 }
120         
121                 public StringBuilder( string value, int capacity) : this(value, 0, value.Length, capacity) {}
122         
123                 public int MaxCapacity {
124                         get {
125                                 // MS runtime always returns Int32.MaxValue.
126                                 return _maxCapacity;
127                         }
128                 }
129
130                 public int Capacity {
131                         get {
132                                 if (_str.Length == 0)
133                                         return constDefaultCapacity;
134                                 
135                                 return _str.Length;
136                         }
137
138                         set {
139                                 if (value < _length)
140                                         throw new ArgumentException( "Capacity must be larger than length" );
141
142                                 InternalEnsureCapacity(value);
143                         }
144                 }
145
146                 public int Length {
147                         get {
148                                 return _length;
149                         }
150
151                         set {
152                                 if( value < 0 || value > _maxCapacity)
153                                         throw new ArgumentOutOfRangeException();
154
155                                 if (value == _length)
156                                         return;
157
158                                 if (value < _length) {
159                                         // LAMESPEC:  The spec is unclear as to what to do
160                                         // with the capacity when truncating the string.
161
162                                         // Do as MS, keep the capacity
163                                         
164                                         // Make sure that we invalidate any cached string.
165                                         InternalEnsureCapacity (value);
166                                         _length = value;
167                                 } else {
168                                         // Expand the capacity to the new length and
169                                         // pad the string with NULL characters.
170                                         Append('\0', value - _length);
171                                 }
172                         }
173                 }
174
175                 [IndexerName("Chars")]
176                 public char this [int index] {
177                         get {
178                                 if (index >= _length || index < 0)
179                                         throw new IndexOutOfRangeException();
180
181                                 return _str [index];
182                         } 
183
184                         set {
185                                 if (index >= _length || index < 0)
186                                         throw new IndexOutOfRangeException();
187
188                                 if (null != _cached_str)
189                                         InternalEnsureCapacity (_length);
190                                 
191                                 _str.InternalSetChar (index, value);
192                         }
193                 }
194
195                 public override string ToString () 
196                 {
197                         if (_length == 0)
198                                 return String.Empty;
199
200                         if (null != _cached_str)
201                                 return _cached_str;
202
203                         // If we only have a half-full buffer we return a new string.
204                         if (_length < (_str.Length >> 1)) 
205                         {
206                                 _cached_str = _str.Substring(0, _length);
207                                 return _cached_str;
208                         }
209
210                         _cached_str = _str;
211                         _str.InternalSetLength(_length);
212
213                         return _str;
214                 }
215
216                 public string ToString (int startIndex, int length) 
217                 {
218                         // re-ordered to avoid possible integer overflow
219                         if (startIndex < 0 || length < 0 || startIndex > _length - length)
220                                 throw new ArgumentOutOfRangeException();
221
222                         return _str.Substring (startIndex, length);
223                 }
224
225                 public int EnsureCapacity (int capacity) 
226                 {
227                         if (capacity < 0)
228                                 throw new ArgumentOutOfRangeException ("Capacity must be greater than 0." );
229
230                         if( capacity <= _str.Length )
231                                 return _str.Length;
232
233                         InternalEnsureCapacity (capacity);
234
235                         return _str.Length;
236                 }
237
238                 public bool Equals (StringBuilder sb) 
239                 {
240                         if (((object)sb) == null)
241                                 return false;
242                         
243                         if (_length == sb.Length && _str == sb._str )
244                                 return true;
245
246                         return false;
247                 }
248
249                 public StringBuilder Remove (int startIndex, int length)
250                 {
251                         // re-ordered to avoid possible integer overflow
252                         if (startIndex < 0 || length < 0 || startIndex > _length - length)
253                                 throw new ArgumentOutOfRangeException();
254                         
255                         if (null != _cached_str)
256                                 InternalEnsureCapacity (_length);
257                         
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));
262
263                         _length -= length;
264
265                         return this;
266                 }                              
267
268                 public StringBuilder Replace (char oldChar, char newChar) 
269                 {
270                         return Replace( oldChar, newChar, 0, _length);
271                 }
272
273                 public StringBuilder Replace (char oldChar, char newChar, int startIndex, int count) 
274                 {
275                         // re-ordered to avoid possible integer overflow
276                         if (startIndex > _length - count || startIndex < 0 || count < 0)
277                                 throw new ArgumentOutOfRangeException();
278
279                         if (null != _cached_str)
280                                 InternalEnsureCapacity (_str.Length);
281
282                         for (int replaceIterate = startIndex; replaceIterate < startIndex + count; replaceIterate++ ) {
283                                 if( _str [replaceIterate] == oldChar )
284                                         _str.InternalSetChar (replaceIterate, newChar);
285                         }
286
287                         return this;
288                 }
289
290                 public StringBuilder Replace( string oldValue, string newValue ) {
291                         return Replace (oldValue, newValue, 0, _length);
292                 }
293
294                 public StringBuilder Replace( string oldValue, string newValue, int startIndex, int count ) 
295                 {
296                         if (oldValue == null)
297                                 throw new ArgumentNullException ("The old value cannot be null.");
298
299                         if (startIndex < 0 || count < 0 || startIndex > _length - count)
300                                 throw new ArgumentOutOfRangeException ();
301
302                         if (oldValue.Length == 0)
303                                 throw new ArgumentException ("The old value cannot be zero length.");
304
305                         // TODO: OPTIMIZE!
306                         string replace = _str.Substring(startIndex, count).Replace(oldValue, newValue);
307
308                         InternalEnsureCapacity (replace.Length + (_length - count));
309
310                         string end = _str.Substring (startIndex + count, _length - startIndex - count );
311
312                         String.InternalStrcpy (_str, startIndex, replace);
313                         String.InternalStrcpy (_str, startIndex + replace.Length, end);
314                         
315                         _length = replace.Length + (_length - count);
316
317                         return this;
318                 }
319
320                       
321                 /* The Append Methods */
322                 public StringBuilder Append (char[] value) 
323                 {
324                         if (value == null)
325                                 return this;
326
327                         int needed_cap = _length + value.Length;
328                         if (null != _cached_str || _str.Length < needed_cap)
329                                 InternalEnsureCapacity (needed_cap);
330                         
331                         String.InternalStrcpy (_str, _length, value);
332                         _length = needed_cap;
333
334                         return this;
335                 } 
336                 
337                 public StringBuilder Append (string value) 
338                 {
339                         if (value == null)
340                                 return this;
341                         
342                         if (_length == 0 && value.Length < _maxCapacity && value.Length > _str.Length) {
343                                 _length = value.Length;
344                                 _str = _cached_str = value;
345                                 return this;
346                         }
347
348                         int needed_cap = _length + value.Length;
349                         if (null != _cached_str || _str.Length < needed_cap)
350                                 InternalEnsureCapacity (needed_cap);
351
352                         String.InternalStrcpy (_str, _length, value);
353                         _length = needed_cap;
354                         return this;
355                 }
356
357                 public StringBuilder Append (bool value) {
358                         return Append (value.ToString());
359                 }
360                 
361                 public StringBuilder Append (byte value) {
362                         return Append (value.ToString());
363                 }
364
365                 public StringBuilder Append (decimal value) {
366                         return Append (value.ToString());
367                 }
368
369                 public StringBuilder Append (double value) {
370                         return Append (value.ToString());
371                 }
372
373                 public StringBuilder Append (short value) {
374                         return Append (value.ToString());
375                 }
376
377                 public StringBuilder Append (int value) {
378                         return Append (value.ToString());
379                 }
380
381                 public StringBuilder Append (long value) {
382                         return Append (value.ToString());
383                 }
384
385                 public StringBuilder Append (object value) {
386                         if (value == null)
387                                 return this;
388
389                         return Append (value.ToString());
390                 }
391
392                 [CLSCompliant(false)]
393                 public StringBuilder Append (sbyte value) {
394                         return Append (value.ToString());
395                 }
396
397                 public StringBuilder Append (float value) {
398                         return Append (value.ToString());
399                 }
400
401                 [CLSCompliant(false)]
402                 public StringBuilder Append (ushort value) {
403                         return Append (value.ToString());
404                 }       
405                 
406                 [CLSCompliant(false)]
407                 public StringBuilder Append (uint value) {
408                         return Append (value.ToString());
409                 }
410
411                 [CLSCompliant(false)]
412                 public StringBuilder Append (ulong value) {
413                         return Append (value.ToString());
414                 }
415
416                 public StringBuilder Append (char value) 
417                 {
418                         int needed_cap = _length + 1;
419                         if (null != _cached_str || _str.Length < needed_cap)
420                                 InternalEnsureCapacity (needed_cap);
421
422                         _str.InternalSetChar(_length, value);
423                         _length = needed_cap;
424
425                         return this;
426                 }
427
428                 public StringBuilder Append (char value, int repeatCount) 
429                 {
430                         if( repeatCount < 0 )
431                                 throw new ArgumentOutOfRangeException();
432
433                         InternalEnsureCapacity (_length + repeatCount);
434                         
435                         for (int i = 0; i < repeatCount; i++)
436                                 _str.InternalSetChar (_length++, value);
437
438                         return this;
439                 }
440
441                 public StringBuilder Append( char[] value, int startIndex, int charCount ) 
442                 {
443                         if (value == null) {
444                                 if (!(startIndex == 0 && charCount == 0))
445                                         throw new ArgumentNullException ("value");
446
447                                 return this;
448                         }
449
450                         if ((charCount < 0 || startIndex < 0) || (startIndex > value.Length - charCount)) 
451                                 throw new ArgumentOutOfRangeException();
452                         
453                         int needed_cap = _length + charCount;
454                         InternalEnsureCapacity (needed_cap);
455
456                         String.InternalStrcpy (_str, _length, value, startIndex, charCount);
457                         _length = needed_cap;
458
459                         return this;
460                 }
461
462                 public StringBuilder Append (string value, int startIndex, int count) 
463                 {
464                         if (value == null) {
465                                 if (startIndex != 0 && count != 0)
466                                         throw new ArgumentNullException ("value");
467                                         
468                                 return this;
469                         }
470
471                         if ((count < 0 || startIndex < 0) || (startIndex > value.Length - count))
472                                 throw new ArgumentOutOfRangeException();
473                         
474                         int needed_cap = _length + count;
475                         if (null != _cached_str || _str.Length < needed_cap)
476                                 InternalEnsureCapacity (needed_cap);
477
478                         String.InternalStrcpy (_str, _length, value, startIndex, count);
479                         
480                         _length = needed_cap;
481
482                         return this;
483                 }
484
485 #if NET_2_0
486                 [ComVisible (false)]
487                 public StringBuilder AppendLine ()
488                 {
489                         return Append (System.Environment.NewLine);
490                 }
491
492                 [ComVisible (false)]
493                 public StringBuilder AppendLine (string value)
494                 {
495                         return Append (value).Append (System.Environment.NewLine);
496                 }
497 #endif
498
499                 public StringBuilder AppendFormat (string format, object arg0)
500                 {
501                         return AppendFormat (null, format, new object [] { arg0 });
502                 }
503
504                 public StringBuilder AppendFormat (string format, params object[] args)
505                 {
506                         return AppendFormat (null, format, args);
507                 }
508
509                 public StringBuilder AppendFormat (IFormatProvider provider,
510                                                    string format,
511                                                    params object[] args)
512                 {
513                         String.FormatHelper (this, provider, format, args);
514                         return this;
515                 }
516
517                 public StringBuilder AppendFormat (string format, object arg0, object arg1)
518                 {
519                         return AppendFormat (null, format, new object [] { arg0, arg1 });
520                 }
521
522                 public StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2)
523                 {
524                         return AppendFormat (null, format, new object [] { arg0, arg1, arg2 });
525                 }
526
527                 /*  The Insert Functions */
528                 
529                 public StringBuilder Insert (int index, char[] value) 
530                 {
531                         return Insert (index, new string (value));
532                 }
533                                 
534                 public StringBuilder Insert (int index, string value) 
535                 {
536                         if( index > _length || index < 0)
537                                 throw new ArgumentOutOfRangeException();
538
539                         if (value == null || value.Length == 0)
540                                 return this;
541
542                         InternalEnsureCapacity (_length + value.Length);
543
544                         // Move everything to the right of the insert point across
545                         String.InternalStrcpy (_str, index + value.Length, _str, index, _length - index);
546                         
547                         // Copy in stuff from the insert buffer
548                         String.InternalStrcpy (_str, index, value);
549                         
550                         _length += value.Length;
551
552                         return this;
553                 }
554
555                 public StringBuilder Insert( int index, bool value ) {
556                         return Insert (index, value.ToString());
557                 }
558                 
559                 public StringBuilder Insert( int index, byte value ) {
560                         return Insert (index, value.ToString());
561                 }
562
563                 public StringBuilder Insert( int index, char value) 
564                 {
565                         if (index > _length || index < 0)
566                                 throw new ArgumentOutOfRangeException ("index");
567
568                         InternalEnsureCapacity (_length + 1);
569                         
570                         // Move everything to the right of the insert point across
571                         String.InternalStrcpy (_str, index + 1, _str, index, _length - index);
572                         
573                         _str.InternalSetChar (index, value);
574                         _length++;
575
576                         return this;
577                 }
578
579                 public StringBuilder Insert( int index, decimal value ) {
580                         return Insert (index, value.ToString());
581                 }
582
583                 public StringBuilder Insert( int index, double value ) {
584                         return Insert (index, value.ToString());
585                 }
586                 
587                 public StringBuilder Insert( int index, short value ) {
588                         return Insert (index, value.ToString());
589                 }
590
591                 public StringBuilder Insert( int index, int value ) {
592                         return Insert (index, value.ToString());
593                 }
594
595                 public StringBuilder Insert( int index, long value ) {
596                         return Insert (index, value.ToString());
597                 }
598         
599                 public StringBuilder Insert( int index, object value ) {
600                         return Insert (index, value.ToString());
601                 }
602                 
603                 [CLSCompliant(false)]
604                 public StringBuilder Insert( int index, sbyte value ) {
605                         return Insert (index, value.ToString() );
606                 }
607
608                 public StringBuilder Insert (int index, float value) {
609                         return Insert (index, value.ToString() );
610                 }
611
612                 [CLSCompliant(false)]
613                 public StringBuilder Insert (int index, ushort value) {
614                         return Insert (index, value.ToString() );
615                 }
616
617                 [CLSCompliant(false)]
618                 public StringBuilder Insert (int index, uint value) {
619                         return Insert ( index, value.ToString() );
620                 }
621                 
622                 [CLSCompliant(false)]
623                 public StringBuilder Insert (int index, ulong value) {
624                         return Insert ( index, value.ToString() );
625                 }
626
627                 public StringBuilder Insert (int index, string value, int count) 
628                 {
629                         // LAMESPEC: The spec says to throw an exception if 
630                         // count < 0, while MS throws even for count < 1!
631                         if ( count < 0 )
632                                 throw new ArgumentOutOfRangeException();
633
634                         if (value != null && value != String.Empty)
635                                 for (int insertCount = 0; insertCount < count; insertCount++)
636                                         Insert( index, value );
637
638                         return this;
639                 }
640
641                 public StringBuilder Insert (int index, char [] value, int startIndex, int charCount)
642                 {
643                         if (value == null) {
644                                 if (startIndex == 0 && charCount == 0)
645                                         return this;
646
647                                 throw new ArgumentNullException ("value");
648                         }
649
650                         if (charCount < 0 || startIndex < 0 || startIndex > value.Length - charCount)
651                                 throw new ArgumentOutOfRangeException ();
652
653                         return Insert (index, new String (value, startIndex, charCount));
654                 }
655         
656                 private void InternalEnsureCapacity (int size) 
657                 {
658                         if (size > _str.Length || (object) _cached_str == (object) _str) {
659                                 int capacity = _str.Length;
660
661                                 // Try double buffer, if that doesn't work, set the length as capacity
662                                 if (size > capacity) {
663                                         
664                                         // The first time a string is appended, we just set _cached_str
665                                         // and _str to it. This allows us to do some optimizations.
666                                         // Below, we take this into account.
667                                         if ((object) _cached_str == (object) _str && capacity < constDefaultCapacity)
668                                                 capacity = constDefaultCapacity;
669                                         
670                                         capacity = capacity << 1;
671                                         if (size > capacity)
672                                                 capacity = size;
673
674                                         if (capacity >= Int32.MaxValue || capacity < 0)
675                                                 capacity = Int32.MaxValue;
676
677                                         if (capacity > _maxCapacity && size <= _maxCapacity)
678                                                 capacity = _maxCapacity;
679                                         
680                                         if (capacity > _maxCapacity)
681                                                 throw new ArgumentOutOfRangeException ("size", "capacity was less than the current size.");
682                                 }
683
684                                 string tmp = String.InternalAllocateStr (capacity);
685                                 if (_length > 0)
686                                         String.InternalStrcpy (tmp, 0, _str, 0, _length);
687
688                                 _str = tmp;
689                         }
690
691                         _cached_str = null;
692                 }
693
694 #if NET_2_0
695                 [ComVisible (false)]
696                 public void CopyTo (int sourceIndex, char [] destination, int destinationIndex, int count)
697                 {
698                         if (destination == null)
699                                 throw new ArgumentNullException ("destination");
700                         if ((Length - count < sourceIndex) ||
701                             (destination.Length -count < destinationIndex) ||
702                             (sourceIndex < 0 || destinationIndex < 0 || count < 0))
703                                 throw new ArgumentOutOfRangeException ();
704
705                         for (int i = 0; i < count; i++)
706                                 destination [destinationIndex+i] = _str [sourceIndex+i];
707                 }
708
709                 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
710                 {
711                         info.AddValue ("m_MaxCapacity", _maxCapacity);
712                         info.AddValue ("Capacity", Capacity);
713                         info.AddValue ("m_StringValue", ToString ());
714                         info.AddValue ("m_currentThread", 0);
715                 }
716
717                 StringBuilder (SerializationInfo info, StreamingContext context)
718                 {
719                         string s = info.GetString ("m_StringValue");
720                         if (s == null)
721                                 s = "";
722                         _length = s.Length;
723                         _str = _cached_str = s;
724                         
725                         _maxCapacity = info.GetInt32 ("m_MaxCapacity");
726                         if (_maxCapacity < 0)
727                                 _maxCapacity = Int32.MaxValue;
728                         Capacity = info.GetInt32 ("Capacity");
729                 }
730 #endif
731         }
732 }