StringBuilder.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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 (_length == sb.Length && _str == sb._str )
  194. return true;
  195. return false;
  196. }
  197. public StringBuilder Remove (int startIndex, int length)
  198. {
  199. // re-ordered to avoid possible integer overflow
  200. if (startIndex < 0 || length < 0 || startIndex > _length - length)
  201. throw new ArgumentOutOfRangeException();
  202. if (null != _cached_str)
  203. InternalEnsureCapacity (_length);
  204. // Copy everything after the 'removed' part to the start
  205. // of the removed part and truncate the sLength
  206. if (_length - (startIndex + length) > 0)
  207. String.InternalStrcpy (_str, startIndex, _str, startIndex + length, _length - (startIndex + length));
  208. _length -= length;
  209. return this;
  210. }
  211. public StringBuilder Replace (char oldChar, char newChar)
  212. {
  213. return Replace( oldChar, newChar, 0, _length);
  214. }
  215. public StringBuilder Replace (char oldChar, char newChar, int startIndex, int count)
  216. {
  217. // re-ordered to avoid possible integer overflow
  218. if (startIndex > _length - count || startIndex < 0 || count < 0)
  219. throw new ArgumentOutOfRangeException();
  220. if (null != _cached_str)
  221. InternalEnsureCapacity (_str.Length);
  222. for (int replaceIterate = startIndex; replaceIterate < startIndex + count; replaceIterate++ ) {
  223. if( _str [replaceIterate] == oldChar )
  224. _str.InternalSetChar (replaceIterate, newChar);
  225. }
  226. return this;
  227. }
  228. public StringBuilder Replace( string oldValue, string newValue ) {
  229. return Replace (oldValue, newValue, 0, _length);
  230. }
  231. public StringBuilder Replace( string oldValue, string newValue, int startIndex, int count )
  232. {
  233. if (oldValue == null)
  234. throw new ArgumentNullException ("The old value cannot be null.");
  235. if (startIndex < 0 || count < 0 || startIndex > _length - count)
  236. throw new ArgumentOutOfRangeException ();
  237. if (oldValue.Length == 0)
  238. throw new ArgumentException ("The old value cannot be zero length.");
  239. // TODO: OPTIMIZE!
  240. string replace = _str.Substring(startIndex, count).Replace(oldValue, newValue);
  241. InternalEnsureCapacity (replace.Length + (_length - count));
  242. string end = _str.Substring (startIndex + count, _length - startIndex - count );
  243. String.InternalStrcpy (_str, startIndex, replace);
  244. String.InternalStrcpy (_str, startIndex + replace.Length, end);
  245. _length = replace.Length + (_length - count);
  246. return this;
  247. }
  248. /* The Append Methods */
  249. public StringBuilder Append (char[] value)
  250. {
  251. if (value == null)
  252. return this;
  253. int needed_cap = _length + value.Length;
  254. if (null != _cached_str || _str.Length < needed_cap)
  255. InternalEnsureCapacity (needed_cap);
  256. String.InternalStrcpy (_str, _length, value);
  257. _length = needed_cap;
  258. return this;
  259. }
  260. public StringBuilder Append (string value)
  261. {
  262. if (value == null)
  263. return this;
  264. if (_length == 0 && value.Length < _maxCapacity && value.Length > _str.Length) {
  265. _length = value.Length;
  266. _str = _cached_str = value;
  267. return this;
  268. }
  269. int needed_cap = _length + value.Length;
  270. if (null != _cached_str || _str.Length < needed_cap)
  271. InternalEnsureCapacity (needed_cap);
  272. String.InternalStrcpy (_str, _length, value);
  273. _length = needed_cap;
  274. return this;
  275. }
  276. public StringBuilder Append (bool value) {
  277. return Append (value.ToString());
  278. }
  279. public StringBuilder Append (byte value) {
  280. return Append (value.ToString());
  281. }
  282. public StringBuilder Append (decimal value) {
  283. return Append (value.ToString());
  284. }
  285. public StringBuilder Append (double value) {
  286. return Append (value.ToString());
  287. }
  288. public StringBuilder Append (short value) {
  289. return Append (value.ToString());
  290. }
  291. public StringBuilder Append (int value) {
  292. return Append (value.ToString());
  293. }
  294. public StringBuilder Append (long value) {
  295. return Append (value.ToString());
  296. }
  297. public StringBuilder Append (object value) {
  298. if (value == null)
  299. return this;
  300. return Append (value.ToString());
  301. }
  302. [CLSCompliant(false)]
  303. public StringBuilder Append (sbyte value) {
  304. return Append (value.ToString());
  305. }
  306. public StringBuilder Append (float value) {
  307. return Append (value.ToString());
  308. }
  309. [CLSCompliant(false)]
  310. public StringBuilder Append (ushort value) {
  311. return Append (value.ToString());
  312. }
  313. [CLSCompliant(false)]
  314. public StringBuilder Append (uint value) {
  315. return Append (value.ToString());
  316. }
  317. [CLSCompliant(false)]
  318. public StringBuilder Append (ulong value) {
  319. return Append (value.ToString());
  320. }
  321. public StringBuilder Append (char value)
  322. {
  323. int needed_cap = _length + 1;
  324. if (null != _cached_str || _str.Length < needed_cap)
  325. InternalEnsureCapacity (needed_cap);
  326. _str.InternalSetChar(_length, value);
  327. _length = needed_cap;
  328. return this;
  329. }
  330. public StringBuilder Append (char value, int repeatCount)
  331. {
  332. if( repeatCount < 0 )
  333. throw new ArgumentOutOfRangeException();
  334. InternalEnsureCapacity (_length + repeatCount);
  335. for (int i = 0; i < repeatCount; i++)
  336. _str.InternalSetChar (_length++, value);
  337. return this;
  338. }
  339. public StringBuilder Append( char[] value, int startIndex, int charCount )
  340. {
  341. if (value == null) {
  342. if (!(startIndex == 0 && charCount == 0))
  343. throw new ArgumentNullException ("value");
  344. return this;
  345. }
  346. if ((charCount < 0 || startIndex < 0) || (startIndex > value.Length - charCount))
  347. throw new ArgumentOutOfRangeException();
  348. int needed_cap = _length + charCount;
  349. InternalEnsureCapacity (needed_cap);
  350. String.InternalStrcpy (_str, _length, value, startIndex, charCount);
  351. _length = needed_cap;
  352. return this;
  353. }
  354. public StringBuilder Append (string value, int startIndex, int count)
  355. {
  356. if (value == null) {
  357. if (startIndex != 0 && count != 0)
  358. throw new ArgumentNullException ("value");
  359. return this;
  360. }
  361. if ((count < 0 || startIndex < 0) || (startIndex > value.Length - count))
  362. throw new ArgumentOutOfRangeException();
  363. int needed_cap = _length + count;
  364. if (null != _cached_str || _str.Length < needed_cap)
  365. InternalEnsureCapacity (needed_cap);
  366. String.InternalStrcpy (_str, _length, value, startIndex, count);
  367. _length = needed_cap;
  368. return this;
  369. }
  370. #if NET_2_0
  371. [ComVisible (false)]
  372. public StringBuilder AppendLine ()
  373. {
  374. return Append (System.Environment.NewLine);
  375. }
  376. [ComVisible (false)]
  377. public StringBuilder AppendLine (string value)
  378. {
  379. return Append (value).Append (System.Environment.NewLine);
  380. }
  381. #endif
  382. public StringBuilder AppendFormat (string format, object arg0)
  383. {
  384. return AppendFormat (null, format, new object [] { arg0 });
  385. }
  386. public StringBuilder AppendFormat (string format, params object[] args)
  387. {
  388. return AppendFormat (null, format, args);
  389. }
  390. public StringBuilder AppendFormat (IFormatProvider provider,
  391. string format,
  392. params object[] args)
  393. {
  394. String.FormatHelper (this, provider, format, args);
  395. return this;
  396. }
  397. public StringBuilder AppendFormat (string format, object arg0, object arg1)
  398. {
  399. return AppendFormat (null, format, new object [] { arg0, arg1 });
  400. }
  401. public StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2)
  402. {
  403. return AppendFormat (null, format, new object [] { arg0, arg1, arg2 });
  404. }
  405. /* The Insert Functions */
  406. public StringBuilder Insert (int index, char[] value)
  407. {
  408. return Insert (index, new string (value));
  409. }
  410. public StringBuilder Insert (int index, string value)
  411. {
  412. if( index > _length || index < 0)
  413. throw new ArgumentOutOfRangeException();
  414. if (value == null || value.Length == 0)
  415. return this;
  416. InternalEnsureCapacity (_length + value.Length);
  417. // Move everything to the right of the insert point across
  418. String.InternalStrcpy (_str, index + value.Length, _str, index, _length - index);
  419. // Copy in stuff from the insert buffer
  420. String.InternalStrcpy (_str, index, value);
  421. _length += value.Length;
  422. return this;
  423. }
  424. public StringBuilder Insert( int index, bool value ) {
  425. return Insert (index, value.ToString());
  426. }
  427. public StringBuilder Insert( int index, byte value ) {
  428. return Insert (index, value.ToString());
  429. }
  430. public StringBuilder Insert( int index, char value)
  431. {
  432. if (index > _length || index < 0)
  433. throw new ArgumentOutOfRangeException ("index");
  434. InternalEnsureCapacity (_length + 1);
  435. // Move everything to the right of the insert point across
  436. String.InternalStrcpy (_str, index + 1, _str, index, _length - index);
  437. _str.InternalSetChar (index, value);
  438. _length++;
  439. return this;
  440. }
  441. public StringBuilder Insert( int index, decimal value ) {
  442. return Insert (index, value.ToString());
  443. }
  444. public StringBuilder Insert( int index, double value ) {
  445. return Insert (index, value.ToString());
  446. }
  447. public StringBuilder Insert( int index, short value ) {
  448. return Insert (index, value.ToString());
  449. }
  450. public StringBuilder Insert( int index, int value ) {
  451. return Insert (index, value.ToString());
  452. }
  453. public StringBuilder Insert( int index, long value ) {
  454. return Insert (index, value.ToString());
  455. }
  456. public StringBuilder Insert( int index, object value ) {
  457. return Insert (index, value.ToString());
  458. }
  459. [CLSCompliant(false)]
  460. public StringBuilder Insert( int index, sbyte value ) {
  461. return Insert (index, value.ToString() );
  462. }
  463. public StringBuilder Insert (int index, float value) {
  464. return Insert (index, value.ToString() );
  465. }
  466. [CLSCompliant(false)]
  467. public StringBuilder Insert (int index, ushort value) {
  468. return Insert (index, value.ToString() );
  469. }
  470. [CLSCompliant(false)]
  471. public StringBuilder Insert (int index, uint value) {
  472. return Insert ( index, value.ToString() );
  473. }
  474. [CLSCompliant(false)]
  475. public StringBuilder Insert (int index, ulong value) {
  476. return Insert ( index, value.ToString() );
  477. }
  478. public StringBuilder Insert (int index, string value, int count)
  479. {
  480. // LAMESPEC: The spec says to throw an exception if
  481. // count < 0, while MS throws even for count < 1!
  482. if ( count < 0 )
  483. throw new ArgumentOutOfRangeException();
  484. if (value != null && value != String.Empty)
  485. for (int insertCount = 0; insertCount < count; insertCount++)
  486. Insert( index, value );
  487. return this;
  488. }
  489. public StringBuilder Insert (int index, char [] value, int startIndex, int charCount)
  490. {
  491. if (value == null) {
  492. if (startIndex == 0 && charCount == 0)
  493. return this;
  494. throw new ArgumentNullException ("value");
  495. }
  496. if (charCount < 0 || startIndex < 0 || startIndex > value.Length - charCount)
  497. throw new ArgumentOutOfRangeException ();
  498. return Insert (index, new String (value, startIndex, charCount));
  499. }
  500. private void InternalEnsureCapacity (int size)
  501. {
  502. if (size > _str.Length || (object) _cached_str == (object) _str) {
  503. int capacity = _str.Length;
  504. // Try double buffer, if that doesn't work, set the length as capacity
  505. if (size > capacity) {
  506. // The first time a string is appended, we just set _cached_str
  507. // and _str to it. This allows us to do some optimizations.
  508. // Below, we take this into account.
  509. if ((object) _cached_str == (object) _str && capacity < constDefaultCapacity)
  510. capacity = constDefaultCapacity;
  511. capacity = capacity << 1;
  512. if (size > capacity)
  513. capacity = size;
  514. if (capacity >= Int32.MaxValue || capacity < 0)
  515. capacity = Int32.MaxValue;
  516. if (capacity > _maxCapacity && size <= _maxCapacity)
  517. capacity = _maxCapacity;
  518. if (capacity > _maxCapacity)
  519. throw new ArgumentOutOfRangeException ("size", "capacity was less than the current size.");
  520. }
  521. string tmp = String.InternalAllocateStr (capacity);
  522. if (_length > 0)
  523. String.InternalStrcpy (tmp, 0, _str, 0, _length);
  524. _str = tmp;
  525. }
  526. _cached_str = null;
  527. }
  528. #if NET_2_0
  529. [ComVisible (false)]
  530. public void CopyTo (int sourceIndex, char [] destination, int destinationIndex, int count)
  531. {
  532. if (destination == null)
  533. throw new ArgumentNullException ("destination");
  534. if ((Length - count < sourceIndex) ||
  535. (destination.Length -count < destinationIndex) ||
  536. (sourceIndex < 0 || destinationIndex < 0 || count < 0))
  537. throw new ArgumentOutOfRangeException ();
  538. for (int i = 0; i < count; i++)
  539. destination [destinationIndex+i] = _str [sourceIndex+i];
  540. }
  541. void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
  542. {
  543. info.AddValue ("m_MaxCapacity", _maxCapacity);
  544. info.AddValue ("Capacity", Capacity);
  545. info.AddValue ("m_StringValue", ToString ());
  546. info.AddValue ("m_currentThread", 0);
  547. }
  548. StringBuilder (SerializationInfo info, StreamingContext context)
  549. {
  550. string s = info.GetString ("m_StringValue");
  551. if (s == null)
  552. s = "";
  553. _length = s.Length;
  554. _str = _cached_str = s;
  555. _maxCapacity = info.GetInt32 ("m_MaxCapacity");
  556. if (_maxCapacity < 0)
  557. _maxCapacity = Int32.MaxValue;
  558. Capacity = info.GetInt32 ("Capacity");
  559. }
  560. #endif
  561. }
  562. }