StringBuilder.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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 ([email protected])
  7. // Paolo Molaro ([email protected])
  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. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  18. //
  19. // Permission is hereby granted, free of charge, to any person obtaining
  20. // a copy of this software and associated documentation files (the
  21. // "Software"), to deal in the Software without restriction, including
  22. // without limitation the rights to use, copy, modify, merge, publish,
  23. // distribute, sublicense, and/or sell copies of the Software, and to
  24. // permit persons to whom the Software is furnished to do so, subject to
  25. // the following conditions:
  26. //
  27. // The above copyright notice and this permission notice shall be
  28. // included in all copies or substantial portions of the Software.
  29. //
  30. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  31. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  32. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  33. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  34. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  35. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  36. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  37. //
  38. using System.Runtime.Serialization;
  39. using System.Runtime.CompilerServices;
  40. using System.Runtime.InteropServices;
  41. namespace System.Text {
  42. [Serializable]
  43. #if NET_2_0
  44. [ComVisible (true)]
  45. #endif
  46. [MonoTODO ("Serialization format not compatible with .NET")]
  47. public sealed class StringBuilder
  48. #if NET_2_0
  49. : ISerializable
  50. #endif
  51. {
  52. private int _length;
  53. private string _str;
  54. private string _cached_str;
  55. private int _maxCapacity = Int32.MaxValue;
  56. private const int constDefaultCapacity = 16;
  57. public StringBuilder(string value, int startIndex, int length, int capacity)
  58. {
  59. // first, check the parameters and throw appropriate exceptions if needed
  60. if (null == value)
  61. value = "";
  62. // make sure startIndex is zero or positive
  63. if (startIndex < 0)
  64. throw new System.ArgumentOutOfRangeException ("startIndex", startIndex, "StartIndex cannot be less than zero.");
  65. // make sure length is zero or positive
  66. if(length < 0)
  67. throw new System.ArgumentOutOfRangeException ("length", length, "Length cannot be less than zero.");
  68. if (capacity < 0)
  69. throw new System.ArgumentOutOfRangeException ("capacity", capacity, "capacity must be greater than zero.");
  70. // make sure startIndex and length give a valid substring of value
  71. // re-ordered to avoid possible integer overflow
  72. if (startIndex > value.Length - length)
  73. throw new System.ArgumentOutOfRangeException ("startIndex", startIndex, "StartIndex and length must refer to a location within the string.");
  74. if (capacity == 0)
  75. capacity = constDefaultCapacity;
  76. _str = String.InternalAllocateStr ((length > capacity) ? length : capacity);
  77. if (length > 0)
  78. String.InternalStrcpy(_str, 0, value, startIndex, length);
  79. _length = length;
  80. }
  81. public StringBuilder () : this (null) {}
  82. public StringBuilder(int capacity) : this (String.Empty, 0, 0, capacity) {}
  83. public StringBuilder(int capacity, int maxCapacity) : this (String.Empty, 0, 0, capacity) {
  84. if (maxCapacity < 1)
  85. throw new System.ArgumentOutOfRangeException ("maxCapacity", "maxCapacity is less than one.");
  86. if (capacity > maxCapacity)
  87. throw new System.ArgumentOutOfRangeException ("capacity", "Capacity exceeds maximum capacity.");
  88. _maxCapacity = maxCapacity;
  89. }
  90. public StringBuilder (string value)
  91. {
  92. /*
  93. * This is an optimization to avoid allocating the internal string
  94. * until the first Append () call.
  95. * The runtime pinvoke marshalling code needs to be aware of this.
  96. */
  97. if (null == value)
  98. value = "";
  99. _length = value.Length;
  100. _str = _cached_str = value;
  101. }
  102. public StringBuilder( string value, int capacity) : this(value, 0, value.Length, capacity) {}
  103. public int MaxCapacity {
  104. get {
  105. // MS runtime always returns Int32.MaxValue.
  106. return _maxCapacity;
  107. }
  108. }
  109. public int Capacity {
  110. get {
  111. if (_str.Length == 0)
  112. return constDefaultCapacity;
  113. return _str.Length;
  114. }
  115. set {
  116. if (value < _length)
  117. throw new ArgumentException( "Capacity must be larger than length" );
  118. InternalEnsureCapacity(value);
  119. }
  120. }
  121. public int Length {
  122. get {
  123. return _length;
  124. }
  125. set {
  126. if( value < 0 || value > _maxCapacity)
  127. throw new ArgumentOutOfRangeException();
  128. if (value == _length)
  129. return;
  130. if (value < _length) {
  131. // LAMESPEC: The spec is unclear as to what to do
  132. // with the capacity when truncating the string.
  133. // Do as MS, keep the capacity
  134. // Make sure that we invalidate any cached string.
  135. InternalEnsureCapacity (value);
  136. _length = value;
  137. } else {
  138. // Expand the capacity to the new length and
  139. // pad the string with NULL characters.
  140. Append('\0', value - _length);
  141. }
  142. }
  143. }
  144. [IndexerName("Chars")]
  145. public char this [int index] {
  146. get {
  147. if (index >= _length || index < 0)
  148. throw new IndexOutOfRangeException();
  149. return _str [index];
  150. }
  151. set {
  152. if (index >= _length || index < 0)
  153. throw new IndexOutOfRangeException();
  154. if (null != _cached_str)
  155. InternalEnsureCapacity (_length);
  156. _str.InternalSetChar (index, value);
  157. }
  158. }
  159. public override string ToString ()
  160. {
  161. if (_length == 0)
  162. return String.Empty;
  163. if (null != _cached_str)
  164. return _cached_str;
  165. // If we only have a half-full buffer we return a new string.
  166. if (_length < (_str.Length >> 1))
  167. {
  168. _cached_str = _str.Substring(0, _length);
  169. return _cached_str;
  170. }
  171. _cached_str = _str;
  172. _str.InternalSetLength(_length);
  173. return _str;
  174. }
  175. public string ToString (int startIndex, int length)
  176. {
  177. // re-ordered to avoid possible integer overflow
  178. if (startIndex < 0 || length < 0 || startIndex > _length - length)
  179. throw new ArgumentOutOfRangeException();
  180. return _str.Substring (startIndex, length);
  181. }
  182. public int EnsureCapacity (int capacity)
  183. {
  184. if (capacity < 0)
  185. throw new ArgumentOutOfRangeException ("Capacity must be greater than 0." );
  186. if( capacity <= _str.Length )
  187. return _str.Length;
  188. InternalEnsureCapacity (capacity);
  189. return _str.Length;
  190. }
  191. public bool Equals (StringBuilder sb)
  192. {
  193. if (((object)sb) == null)
  194. return false;
  195. if (_length == sb.Length && _str == sb._str )
  196. return true;
  197. return false;
  198. }
  199. public StringBuilder Remove (int startIndex, int length)
  200. {
  201. // re-ordered to avoid possible integer overflow
  202. if (startIndex < 0 || length < 0 || startIndex > _length - length)
  203. throw new ArgumentOutOfRangeException();
  204. if (null != _cached_str)
  205. InternalEnsureCapacity (_length);
  206. // Copy everything after the 'removed' part to the start
  207. // of the removed part and truncate the sLength
  208. if (_length - (startIndex + length) > 0)
  209. String.InternalStrcpy (_str, startIndex, _str, startIndex + length, _length - (startIndex + length));
  210. _length -= length;
  211. return this;
  212. }
  213. public StringBuilder Replace (char oldChar, char newChar)
  214. {
  215. return Replace( oldChar, newChar, 0, _length);
  216. }
  217. public StringBuilder Replace (char oldChar, char newChar, int startIndex, int count)
  218. {
  219. // re-ordered to avoid possible integer overflow
  220. if (startIndex > _length - count || startIndex < 0 || count < 0)
  221. throw new ArgumentOutOfRangeException();
  222. if (null != _cached_str)
  223. InternalEnsureCapacity (_str.Length);
  224. for (int replaceIterate = startIndex; replaceIterate < startIndex + count; replaceIterate++ ) {
  225. if( _str [replaceIterate] == oldChar )
  226. _str.InternalSetChar (replaceIterate, newChar);
  227. }
  228. return this;
  229. }
  230. public StringBuilder Replace( string oldValue, string newValue ) {
  231. return Replace (oldValue, newValue, 0, _length);
  232. }
  233. public StringBuilder Replace( string oldValue, string newValue, int startIndex, int count )
  234. {
  235. if (oldValue == null)
  236. throw new ArgumentNullException ("The old value cannot be null.");
  237. if (startIndex < 0 || count < 0 || startIndex > _length - count)
  238. throw new ArgumentOutOfRangeException ();
  239. if (oldValue.Length == 0)
  240. throw new ArgumentException ("The old value cannot be zero length.");
  241. // TODO: OPTIMIZE!
  242. string replace = _str.Substring(startIndex, count).Replace(oldValue, newValue);
  243. InternalEnsureCapacity (replace.Length + (_length - count));
  244. string end = _str.Substring (startIndex + count, _length - startIndex - count );
  245. String.InternalStrcpy (_str, startIndex, replace);
  246. String.InternalStrcpy (_str, startIndex + replace.Length, end);
  247. _length = replace.Length + (_length - count);
  248. return this;
  249. }
  250. /* The Append Methods */
  251. public StringBuilder Append (char[] value)
  252. {
  253. if (value == null)
  254. return this;
  255. int needed_cap = _length + value.Length;
  256. if (null != _cached_str || _str.Length < needed_cap)
  257. InternalEnsureCapacity (needed_cap);
  258. String.InternalStrcpy (_str, _length, value);
  259. _length = needed_cap;
  260. return this;
  261. }
  262. public StringBuilder Append (string value)
  263. {
  264. if (value == null)
  265. return this;
  266. if (_length == 0 && value.Length < _maxCapacity && value.Length > _str.Length) {
  267. _length = value.Length;
  268. _str = _cached_str = value;
  269. return this;
  270. }
  271. int needed_cap = _length + value.Length;
  272. if (null != _cached_str || _str.Length < needed_cap)
  273. InternalEnsureCapacity (needed_cap);
  274. String.InternalStrcpy (_str, _length, value);
  275. _length = needed_cap;
  276. return this;
  277. }
  278. public StringBuilder Append (bool value) {
  279. return Append (value.ToString());
  280. }
  281. public StringBuilder Append (byte value) {
  282. return Append (value.ToString());
  283. }
  284. public StringBuilder Append (decimal value) {
  285. return Append (value.ToString());
  286. }
  287. public StringBuilder Append (double value) {
  288. return Append (value.ToString());
  289. }
  290. public StringBuilder Append (short value) {
  291. return Append (value.ToString());
  292. }
  293. public StringBuilder Append (int value) {
  294. return Append (value.ToString());
  295. }
  296. public StringBuilder Append (long value) {
  297. return Append (value.ToString());
  298. }
  299. public StringBuilder Append (object value) {
  300. if (value == null)
  301. return this;
  302. return Append (value.ToString());
  303. }
  304. [CLSCompliant(false)]
  305. public StringBuilder Append (sbyte value) {
  306. return Append (value.ToString());
  307. }
  308. public StringBuilder Append (float value) {
  309. return Append (value.ToString());
  310. }
  311. [CLSCompliant(false)]
  312. public StringBuilder Append (ushort value) {
  313. return Append (value.ToString());
  314. }
  315. [CLSCompliant(false)]
  316. public StringBuilder Append (uint value) {
  317. return Append (value.ToString());
  318. }
  319. [CLSCompliant(false)]
  320. public StringBuilder Append (ulong value) {
  321. return Append (value.ToString());
  322. }
  323. public StringBuilder Append (char value)
  324. {
  325. int needed_cap = _length + 1;
  326. if (null != _cached_str || _str.Length < needed_cap)
  327. InternalEnsureCapacity (needed_cap);
  328. _str.InternalSetChar(_length, value);
  329. _length = needed_cap;
  330. return this;
  331. }
  332. public StringBuilder Append (char value, int repeatCount)
  333. {
  334. if( repeatCount < 0 )
  335. throw new ArgumentOutOfRangeException();
  336. InternalEnsureCapacity (_length + repeatCount);
  337. for (int i = 0; i < repeatCount; i++)
  338. _str.InternalSetChar (_length++, value);
  339. return this;
  340. }
  341. public StringBuilder Append( char[] value, int startIndex, int charCount )
  342. {
  343. if (value == null) {
  344. if (!(startIndex == 0 && charCount == 0))
  345. throw new ArgumentNullException ("value");
  346. return this;
  347. }
  348. if ((charCount < 0 || startIndex < 0) || (startIndex > value.Length - charCount))
  349. throw new ArgumentOutOfRangeException();
  350. int needed_cap = _length + charCount;
  351. InternalEnsureCapacity (needed_cap);
  352. String.InternalStrcpy (_str, _length, value, startIndex, charCount);
  353. _length = needed_cap;
  354. return this;
  355. }
  356. public StringBuilder Append (string value, int startIndex, int count)
  357. {
  358. if (value == null) {
  359. if (startIndex != 0 && count != 0)
  360. throw new ArgumentNullException ("value");
  361. return this;
  362. }
  363. if ((count < 0 || startIndex < 0) || (startIndex > value.Length - count))
  364. throw new ArgumentOutOfRangeException();
  365. int needed_cap = _length + count;
  366. if (null != _cached_str || _str.Length < needed_cap)
  367. InternalEnsureCapacity (needed_cap);
  368. String.InternalStrcpy (_str, _length, value, startIndex, count);
  369. _length = needed_cap;
  370. return this;
  371. }
  372. #if NET_2_0
  373. [ComVisible (false)]
  374. public StringBuilder AppendLine ()
  375. {
  376. return Append (System.Environment.NewLine);
  377. }
  378. [ComVisible (false)]
  379. public StringBuilder AppendLine (string value)
  380. {
  381. return Append (value).Append (System.Environment.NewLine);
  382. }
  383. #endif
  384. public StringBuilder AppendFormat (string format, params object[] args)
  385. {
  386. return AppendFormat (null, format, args);
  387. }
  388. public StringBuilder AppendFormat (IFormatProvider provider,
  389. string format,
  390. params object[] args)
  391. {
  392. String.FormatHelper (this, provider, format, args);
  393. return this;
  394. }
  395. #if NET_2_1
  396. internal
  397. #else
  398. public
  399. #endif
  400. StringBuilder AppendFormat (string format, object arg0)
  401. {
  402. return AppendFormat (null, format, new object [] { arg0 });
  403. }
  404. #if NET_2_1
  405. internal
  406. #else
  407. public
  408. #endif
  409. StringBuilder AppendFormat (string format, object arg0, object arg1)
  410. {
  411. return AppendFormat (null, format, new object [] { arg0, arg1 });
  412. }
  413. #if NET_2_1
  414. internal
  415. #else
  416. public
  417. #endif
  418. StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2)
  419. {
  420. return AppendFormat (null, format, new object [] { arg0, arg1, arg2 });
  421. }
  422. /* The Insert Functions */
  423. public StringBuilder Insert (int index, char[] value)
  424. {
  425. return Insert (index, new string (value));
  426. }
  427. public StringBuilder Insert (int index, string value)
  428. {
  429. if( index > _length || index < 0)
  430. throw new ArgumentOutOfRangeException();
  431. if (value == null || value.Length == 0)
  432. return this;
  433. InternalEnsureCapacity (_length + value.Length);
  434. // Move everything to the right of the insert point across
  435. String.InternalStrcpy (_str, index + value.Length, _str, index, _length - index);
  436. // Copy in stuff from the insert buffer
  437. String.InternalStrcpy (_str, index, value);
  438. _length += value.Length;
  439. return this;
  440. }
  441. public StringBuilder Insert( int index, bool value ) {
  442. return Insert (index, value.ToString());
  443. }
  444. public StringBuilder Insert( int index, byte value ) {
  445. return Insert (index, value.ToString());
  446. }
  447. public StringBuilder Insert( int index, char value)
  448. {
  449. if (index > _length || index < 0)
  450. throw new ArgumentOutOfRangeException ("index");
  451. InternalEnsureCapacity (_length + 1);
  452. // Move everything to the right of the insert point across
  453. String.InternalStrcpy (_str, index + 1, _str, index, _length - index);
  454. _str.InternalSetChar (index, value);
  455. _length++;
  456. return this;
  457. }
  458. public StringBuilder Insert( int index, decimal value ) {
  459. return Insert (index, value.ToString());
  460. }
  461. public StringBuilder Insert( int index, double value ) {
  462. return Insert (index, value.ToString());
  463. }
  464. public StringBuilder Insert( int index, short value ) {
  465. return Insert (index, value.ToString());
  466. }
  467. public StringBuilder Insert( int index, int value ) {
  468. return Insert (index, value.ToString());
  469. }
  470. public StringBuilder Insert( int index, long value ) {
  471. return Insert (index, value.ToString());
  472. }
  473. public StringBuilder Insert( int index, object value ) {
  474. return Insert (index, value.ToString());
  475. }
  476. [CLSCompliant(false)]
  477. public StringBuilder Insert( int index, sbyte value ) {
  478. return Insert (index, value.ToString() );
  479. }
  480. public StringBuilder Insert (int index, float value) {
  481. return Insert (index, value.ToString() );
  482. }
  483. [CLSCompliant(false)]
  484. public StringBuilder Insert (int index, ushort value) {
  485. return Insert (index, value.ToString() );
  486. }
  487. [CLSCompliant(false)]
  488. public StringBuilder Insert (int index, uint value) {
  489. return Insert ( index, value.ToString() );
  490. }
  491. [CLSCompliant(false)]
  492. public StringBuilder Insert (int index, ulong value) {
  493. return Insert ( index, value.ToString() );
  494. }
  495. public StringBuilder Insert (int index, string value, int count)
  496. {
  497. // LAMESPEC: The spec says to throw an exception if
  498. // count < 0, while MS throws even for count < 1!
  499. if ( count < 0 )
  500. throw new ArgumentOutOfRangeException();
  501. if (value != null && value != String.Empty)
  502. for (int insertCount = 0; insertCount < count; insertCount++)
  503. Insert( index, value );
  504. return this;
  505. }
  506. public StringBuilder Insert (int index, char [] value, int startIndex, int charCount)
  507. {
  508. if (value == null) {
  509. if (startIndex == 0 && charCount == 0)
  510. return this;
  511. throw new ArgumentNullException ("value");
  512. }
  513. if (charCount < 0 || startIndex < 0 || startIndex > value.Length - charCount)
  514. throw new ArgumentOutOfRangeException ();
  515. return Insert (index, new String (value, startIndex, charCount));
  516. }
  517. private void InternalEnsureCapacity (int size)
  518. {
  519. if (size > _str.Length || (object) _cached_str == (object) _str) {
  520. int capacity = _str.Length;
  521. // Try double buffer, if that doesn't work, set the length as capacity
  522. if (size > capacity) {
  523. // The first time a string is appended, we just set _cached_str
  524. // and _str to it. This allows us to do some optimizations.
  525. // Below, we take this into account.
  526. if ((object) _cached_str == (object) _str && capacity < constDefaultCapacity)
  527. capacity = constDefaultCapacity;
  528. capacity = capacity << 1;
  529. if (size > capacity)
  530. capacity = size;
  531. if (capacity >= Int32.MaxValue || capacity < 0)
  532. capacity = Int32.MaxValue;
  533. if (capacity > _maxCapacity && size <= _maxCapacity)
  534. capacity = _maxCapacity;
  535. if (capacity > _maxCapacity)
  536. throw new ArgumentOutOfRangeException ("size", "capacity was less than the current size.");
  537. }
  538. string tmp = String.InternalAllocateStr (capacity);
  539. if (_length > 0)
  540. String.InternalStrcpy (tmp, 0, _str, 0, _length);
  541. _str = tmp;
  542. }
  543. _cached_str = null;
  544. }
  545. #if NET_2_0
  546. [ComVisible (false)]
  547. public void CopyTo (int sourceIndex, char [] destination, int destinationIndex, int count)
  548. {
  549. if (destination == null)
  550. throw new ArgumentNullException ("destination");
  551. if ((Length - count < sourceIndex) ||
  552. (destination.Length -count < destinationIndex) ||
  553. (sourceIndex < 0 || destinationIndex < 0 || count < 0))
  554. throw new ArgumentOutOfRangeException ();
  555. for (int i = 0; i < count; i++)
  556. destination [destinationIndex+i] = _str [sourceIndex+i];
  557. }
  558. void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
  559. {
  560. info.AddValue ("m_MaxCapacity", _maxCapacity);
  561. info.AddValue ("Capacity", Capacity);
  562. info.AddValue ("m_StringValue", ToString ());
  563. info.AddValue ("m_currentThread", 0);
  564. }
  565. StringBuilder (SerializationInfo info, StreamingContext context)
  566. {
  567. string s = info.GetString ("m_StringValue");
  568. if (s == null)
  569. s = "";
  570. _length = s.Length;
  571. _str = _cached_str = s;
  572. _maxCapacity = info.GetInt32 ("m_MaxCapacity");
  573. if (_maxCapacity < 0)
  574. _maxCapacity = Int32.MaxValue;
  575. Capacity = info.GetInt32 ("Capacity");
  576. }
  577. #endif
  578. }
  579. }