StringBuilder.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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. namespace System.Text {
  41. [Serializable]
  42. [MonoTODO ("Fix serialization compatibility with MS.NET")]
  43. public sealed class StringBuilder
  44. #if NET_2_0
  45. : ISerializable
  46. #endif
  47. {
  48. private int _length;
  49. private string _str;
  50. private string _cached_str;
  51. private int _maxCapacity = Int32.MaxValue;
  52. private const int constDefaultCapacity = 16;
  53. public StringBuilder(string value, int startIndex, int length, int capacity)
  54. {
  55. // first, check the parameters and throw appropriate exceptions if needed
  56. if (null == value)
  57. value = "";
  58. // make sure startIndex is zero or positive
  59. if (startIndex < 0)
  60. throw new System.ArgumentOutOfRangeException ("startIndex", startIndex, "StartIndex cannot be less than zero.");
  61. // make sure length is zero or positive
  62. if(length < 0)
  63. throw new System.ArgumentOutOfRangeException ("length", length, "Length cannot be less than zero.");
  64. if (capacity < 0)
  65. throw new System.ArgumentOutOfRangeException ("capacity", capacity, "capacity must be greater than zero.");
  66. // make sure startIndex and length give a valid substring of value
  67. // re-ordered to avoid possible integer overflow
  68. if (startIndex > value.Length - length)
  69. throw new System.ArgumentOutOfRangeException ("startIndex", startIndex, "StartIndex and length must refer to a location within the string.");
  70. if (capacity == 0)
  71. capacity = constDefaultCapacity;
  72. _str = String.InternalAllocateStr ((length > capacity) ? length : capacity);
  73. if (length > 0)
  74. String.InternalStrcpy(_str, 0, value, startIndex, length);
  75. _length = length;
  76. }
  77. public StringBuilder () : this (null) {}
  78. public StringBuilder(int capacity) : this (String.Empty, 0, 0, capacity) {}
  79. public StringBuilder(int capacity, int maxCapacity) : this (String.Empty, 0, 0, capacity) {
  80. if (maxCapacity < 1)
  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.");
  84. _maxCapacity = maxCapacity;
  85. }
  86. public StringBuilder (string value)
  87. {
  88. if (null == value)
  89. value = "";
  90. _length = value.Length;
  91. _str = _cached_str = value;
  92. }
  93. public StringBuilder( string value, int capacity) : this(value, 0, value.Length, capacity) {}
  94. public int MaxCapacity {
  95. get {
  96. // MS runtime always returns Int32.MaxValue.
  97. return _maxCapacity;
  98. }
  99. }
  100. public int Capacity {
  101. get {
  102. if (_str.Length == 0)
  103. return constDefaultCapacity;
  104. return _str.Length;
  105. }
  106. set {
  107. if (value < _length)
  108. throw new ArgumentException( "Capacity must be larger than length" );
  109. InternalEnsureCapacity(value);
  110. }
  111. }
  112. public int Length {
  113. get {
  114. return _length;
  115. }
  116. set {
  117. if( value < 0 || value > _maxCapacity)
  118. throw new ArgumentOutOfRangeException();
  119. if (value == _length)
  120. return;
  121. if (value < _length) {
  122. // LAMESPEC: The spec is unclear as to what to do
  123. // with the capacity when truncating the string.
  124. // Do as MS, keep the capacity
  125. // Make sure that we invalidate any cached string.
  126. InternalEnsureCapacity (value);
  127. _length = value;
  128. } else {
  129. // Expand the capacity to the new length and
  130. // pad the string with spaces.
  131. // LAMESPEC: The spec says to put the spaces on the
  132. // left of the string however the MS implementation
  133. // puts them on the right. We'll do that for
  134. // compatibility (!)
  135. Append(' ', value - _length);
  136. }
  137. }
  138. }
  139. [IndexerName("Chars")]
  140. public char this [int index] {
  141. get {
  142. if (index >= _length || index < 0)
  143. throw new IndexOutOfRangeException();
  144. return _str [index];
  145. }
  146. set {
  147. if (index >= _length || index < 0)
  148. throw new IndexOutOfRangeException();
  149. if (null != _cached_str)
  150. InternalEnsureCapacity (_length);
  151. _str.InternalSetChar (index, value);
  152. }
  153. }
  154. public override string ToString ()
  155. {
  156. if (_length == 0)
  157. return String.Empty;
  158. if (null != _cached_str)
  159. return _cached_str;
  160. // If we only have a half-full buffer we return a new string.
  161. if (_length < (_str.Length >> 1))
  162. {
  163. _cached_str = _str.Substring(0, _length);
  164. return _cached_str;
  165. }
  166. _cached_str = _str;
  167. _str.InternalSetLength(_length);
  168. return _str;
  169. }
  170. public string ToString (int startIndex, int length)
  171. {
  172. // re-ordered to avoid possible integer overflow
  173. if (startIndex < 0 || length < 0 || startIndex > _length - length)
  174. throw new ArgumentOutOfRangeException();
  175. return _str.Substring (startIndex, length);
  176. }
  177. public int EnsureCapacity (int capacity)
  178. {
  179. if (capacity < 0)
  180. throw new ArgumentOutOfRangeException ("Capacity must be greater than 0." );
  181. if( capacity <= _str.Length )
  182. return _str.Length;
  183. InternalEnsureCapacity (capacity);
  184. return _str.Length;
  185. }
  186. public bool Equals (StringBuilder sb)
  187. {
  188. if (_length == sb.Length && _str == sb._str )
  189. return true;
  190. return false;
  191. }
  192. public StringBuilder Remove (int startIndex, int length)
  193. {
  194. // re-ordered to avoid possible integer overflow
  195. if (startIndex < 0 || length < 0 || startIndex > _length - length)
  196. throw new ArgumentOutOfRangeException();
  197. if (null != _cached_str)
  198. InternalEnsureCapacity (_length);
  199. // Copy everything after the 'removed' part to the start
  200. // of the removed part and truncate the sLength
  201. if (_length - (startIndex + length) > 0)
  202. String.InternalStrcpy (_str, startIndex, _str, startIndex + length, _length - (startIndex + length));
  203. _length -= length;
  204. return this;
  205. }
  206. public StringBuilder Replace (char oldChar, char newChar)
  207. {
  208. return Replace( oldChar, newChar, 0, _length);
  209. }
  210. public StringBuilder Replace (char oldChar, char newChar, int startIndex, int count)
  211. {
  212. // re-ordered to avoid possible integer overflow
  213. if (startIndex > _length - count || startIndex < 0 || count < 0)
  214. throw new ArgumentOutOfRangeException();
  215. if (null != _cached_str)
  216. InternalEnsureCapacity (_str.Length);
  217. for (int replaceIterate = startIndex; replaceIterate < startIndex + count; replaceIterate++ ) {
  218. if( _str [replaceIterate] == oldChar )
  219. _str.InternalSetChar (replaceIterate, newChar);
  220. }
  221. return this;
  222. }
  223. public StringBuilder Replace( string oldValue, string newValue ) {
  224. return Replace (oldValue, newValue, 0, _length);
  225. }
  226. public StringBuilder Replace( string oldValue, string newValue, int startIndex, int count )
  227. {
  228. if (oldValue == null)
  229. throw new ArgumentNullException ("The old value cannot be null.");
  230. if (startIndex < 0 || count < 0 || startIndex > _length - count)
  231. throw new ArgumentOutOfRangeException ();
  232. if (oldValue.Length == 0)
  233. throw new ArgumentException ("The old value cannot be zero length.");
  234. // TODO: OPTIMIZE!
  235. string replace = _str.Substring(startIndex, count).Replace(oldValue, newValue);
  236. InternalEnsureCapacity (replace.Length + (_length - count));
  237. string end = _str.Substring (startIndex + count, _length - startIndex - count );
  238. String.InternalStrcpy (_str, startIndex, replace);
  239. String.InternalStrcpy (_str, startIndex + replace.Length, end);
  240. _length = replace.Length + (_length - count);
  241. return this;
  242. }
  243. /* The Append Methods */
  244. public StringBuilder Append (char[] value)
  245. {
  246. if (value == null)
  247. return this;
  248. int needed_cap = _length + value.Length;
  249. if (null != _cached_str || _str.Length < needed_cap)
  250. InternalEnsureCapacity (needed_cap);
  251. String.InternalStrcpy (_str, _length, value);
  252. _length += value.Length;
  253. return this;
  254. }
  255. public StringBuilder Append (string value)
  256. {
  257. if (value == null)
  258. return this;
  259. if (_length == 0 && value.Length < _maxCapacity && value.Length > _str.Length) {
  260. _length = value.Length;
  261. _str = _cached_str = value;
  262. return this;
  263. }
  264. int needed_cap = _length + value.Length;
  265. if (null != _cached_str || _str.Length < needed_cap)
  266. InternalEnsureCapacity (needed_cap);
  267. String.InternalStrcpy (_str, _length, value);
  268. _length += value.Length;
  269. return this;
  270. }
  271. public StringBuilder Append (bool value) {
  272. return Append (value.ToString());
  273. }
  274. public StringBuilder Append (byte value) {
  275. return Append (value.ToString());
  276. }
  277. public StringBuilder Append (decimal value) {
  278. return Append (value.ToString());
  279. }
  280. public StringBuilder Append (double value) {
  281. return Append (value.ToString());
  282. }
  283. public StringBuilder Append (short value) {
  284. return Append (value.ToString());
  285. }
  286. public StringBuilder Append (int value) {
  287. return Append (value.ToString());
  288. }
  289. public StringBuilder Append (long value) {
  290. return Append (value.ToString());
  291. }
  292. public StringBuilder Append (object value) {
  293. if (value == null)
  294. return this;
  295. return Append (value.ToString());
  296. }
  297. [CLSCompliant(false)]
  298. public StringBuilder Append (sbyte value) {
  299. return Append (value.ToString());
  300. }
  301. public StringBuilder Append (float value) {
  302. return Append (value.ToString());
  303. }
  304. [CLSCompliant(false)]
  305. public StringBuilder Append (ushort value) {
  306. return Append (value.ToString());
  307. }
  308. [CLSCompliant(false)]
  309. public StringBuilder Append (uint value) {
  310. return Append (value.ToString());
  311. }
  312. [CLSCompliant(false)]
  313. public StringBuilder Append (ulong value) {
  314. return Append (value.ToString());
  315. }
  316. public StringBuilder Append (char value)
  317. {
  318. int needed_cap = _length + 1;
  319. if (null != _cached_str || _str.Length < needed_cap)
  320. InternalEnsureCapacity (needed_cap);
  321. _str.InternalSetChar(_length, value);
  322. _length++;
  323. return this;
  324. }
  325. public StringBuilder Append (char value, int repeatCount)
  326. {
  327. if( repeatCount < 0 )
  328. throw new ArgumentOutOfRangeException();
  329. InternalEnsureCapacity (_length + repeatCount);
  330. for (int i = 0; i < repeatCount; i++)
  331. _str.InternalSetChar (_length++, value);
  332. return this;
  333. }
  334. public StringBuilder Append( char[] value, int startIndex, int charCount )
  335. {
  336. if (value == null) {
  337. if (!(startIndex == 0 && charCount == 0))
  338. throw new ArgumentNullException ("value");
  339. return this;
  340. }
  341. if ((charCount < 0 || startIndex < 0) || (startIndex > value.Length - charCount))
  342. throw new ArgumentOutOfRangeException();
  343. InternalEnsureCapacity (_length + charCount);
  344. String.InternalStrcpy (_str, _length, value, startIndex, charCount);
  345. _length += charCount;
  346. return this;
  347. }
  348. public StringBuilder Append (string value, int startIndex, int count)
  349. {
  350. if (value == null) {
  351. if (startIndex != 0 && count != 0)
  352. throw new ArgumentNullException ("value");
  353. return this;
  354. }
  355. if ((count < 0 || startIndex < 0) || (startIndex > value.Length - count))
  356. throw new ArgumentOutOfRangeException();
  357. int needed_cap = _length + count;
  358. if (null != _cached_str || _str.Length < needed_cap)
  359. InternalEnsureCapacity (needed_cap);
  360. String.InternalStrcpy (_str, _length, value, startIndex, count);
  361. _length += count;
  362. return this;
  363. }
  364. #if NET_2_0
  365. public StringBuilder AppendLine ()
  366. {
  367. return Append (System.Environment.NewLine);
  368. }
  369. public StringBuilder AppendLine (string value)
  370. {
  371. return Append (value).Append (System.Environment.NewLine);
  372. }
  373. #endif
  374. public StringBuilder AppendFormat (string format, object arg0)
  375. {
  376. return AppendFormat (null, format, new object [] { arg0 });
  377. }
  378. public StringBuilder AppendFormat (string format, params object[] args)
  379. {
  380. return AppendFormat (null, format, args);
  381. }
  382. public StringBuilder AppendFormat (IFormatProvider provider,
  383. string format,
  384. params object[] args)
  385. {
  386. String.FormatHelper (this, provider, format, args);
  387. return this;
  388. }
  389. public StringBuilder AppendFormat (string format, object arg0, object arg1)
  390. {
  391. return AppendFormat (null, format, new object [] { arg0, arg1 });
  392. }
  393. public StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2)
  394. {
  395. return AppendFormat (null, format, new object [] { arg0, arg1, arg2 });
  396. }
  397. /* The Insert Functions */
  398. public StringBuilder Insert (int index, char[] value)
  399. {
  400. return Insert (index, new string (value));
  401. }
  402. public StringBuilder Insert (int index, string value)
  403. {
  404. if( index > _length || index < 0)
  405. throw new ArgumentOutOfRangeException();
  406. if (value == null || value.Length == 0)
  407. return this;
  408. InternalEnsureCapacity (_length + value.Length);
  409. // Move everything to the right of the insert point across
  410. String.InternalStrcpy (_str, index + value.Length, _str, index, _length - index);
  411. // Copy in stuff from the insert buffer
  412. String.InternalStrcpy (_str, index, value);
  413. _length += value.Length;
  414. return this;
  415. }
  416. public StringBuilder Insert( int index, bool value ) {
  417. return Insert (index, value.ToString());
  418. }
  419. public StringBuilder Insert( int index, byte value ) {
  420. return Insert (index, value.ToString());
  421. }
  422. public StringBuilder Insert( int index, char value)
  423. {
  424. if (index > _length || index < 0)
  425. throw new ArgumentOutOfRangeException ("index");
  426. InternalEnsureCapacity (_length + 1);
  427. // Move everything to the right of the insert point across
  428. String.InternalStrcpy (_str, index + 1, _str, index, _length - index);
  429. _str.InternalSetChar (index, value);
  430. _length++;
  431. return this;
  432. }
  433. public StringBuilder Insert( int index, decimal value ) {
  434. return Insert (index, value.ToString());
  435. }
  436. public StringBuilder Insert( int index, double value ) {
  437. return Insert (index, value.ToString());
  438. }
  439. public StringBuilder Insert( int index, short value ) {
  440. return Insert (index, value.ToString());
  441. }
  442. public StringBuilder Insert( int index, int value ) {
  443. return Insert (index, value.ToString());
  444. }
  445. public StringBuilder Insert( int index, long value ) {
  446. return Insert (index, value.ToString());
  447. }
  448. public StringBuilder Insert( int index, object value ) {
  449. return Insert (index, value.ToString());
  450. }
  451. [CLSCompliant(false)]
  452. public StringBuilder Insert( int index, sbyte value ) {
  453. return Insert (index, value.ToString() );
  454. }
  455. public StringBuilder Insert (int index, float value) {
  456. return Insert (index, value.ToString() );
  457. }
  458. [CLSCompliant(false)]
  459. public StringBuilder Insert (int index, ushort value) {
  460. return Insert (index, value.ToString() );
  461. }
  462. [CLSCompliant(false)]
  463. public StringBuilder Insert (int index, uint value) {
  464. return Insert ( index, value.ToString() );
  465. }
  466. [CLSCompliant(false)]
  467. public StringBuilder Insert (int index, ulong value) {
  468. return Insert ( index, value.ToString() );
  469. }
  470. public StringBuilder Insert (int index, string value, int count)
  471. {
  472. // LAMESPEC: The spec says to throw an exception if
  473. // count < 0, while MS throws even for count < 1!
  474. if ( count < 0 )
  475. throw new ArgumentOutOfRangeException();
  476. if (value != null && value != String.Empty)
  477. for (int insertCount = 0; insertCount < count; insertCount++)
  478. Insert( index, value );
  479. return this;
  480. }
  481. public StringBuilder Insert (int index, char [] value, int startIndex, int charCount)
  482. {
  483. if (value == null) {
  484. if (startIndex == 0 && charCount == 0)
  485. return this;
  486. throw new ArgumentNullException ("value");
  487. }
  488. if (charCount < 0 || startIndex < 0 || startIndex > value.Length - charCount)
  489. throw new ArgumentOutOfRangeException ();
  490. return Insert (index, new String (value, startIndex, charCount));
  491. }
  492. private void InternalEnsureCapacity (int size)
  493. {
  494. if (size > _str.Length || (object) _cached_str == (object) _str) {
  495. int capacity = _str.Length;
  496. // Try double buffer, if that doesn't work, set the length as capacity
  497. if (size > capacity) {
  498. // The first time a string is appended, we just set _cached_str
  499. // and _str to it. This allows us to do some optimizations.
  500. // Below, we take this into account.
  501. if ((object) _cached_str == (object) _str && capacity < constDefaultCapacity)
  502. capacity = constDefaultCapacity;
  503. capacity = capacity << 1;
  504. if (size > capacity)
  505. capacity = size;
  506. if (capacity >= Int32.MaxValue || capacity < 0)
  507. capacity = Int32.MaxValue;
  508. if (capacity > _maxCapacity && size <= _maxCapacity)
  509. capacity = _maxCapacity;
  510. if (capacity > _maxCapacity)
  511. throw new ArgumentOutOfRangeException ("size", "capacity was less than the current size.");
  512. }
  513. string tmp = String.InternalAllocateStr (capacity);
  514. if (_length > 0)
  515. String.InternalStrcpy (tmp, 0, _str, 0, _length);
  516. _str = tmp;
  517. }
  518. _cached_str = null;
  519. }
  520. #if NET_2_0
  521. public void CopyTo (int sourceIndex, char [] destination, int destinationIndex, int count)
  522. {
  523. if (destination == null)
  524. throw new ArgumentNullException ("destination");
  525. if ((Length - count < sourceIndex) ||
  526. (destination.Length -count < destinationIndex) ||
  527. (sourceIndex < 0 || destinationIndex < 0 || count < 0))
  528. throw new ArgumentOutOfRangeException ();
  529. for (int i = 0; i < count; i++)
  530. destination [destinationIndex+i] = _str [sourceIndex+i];
  531. }
  532. void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
  533. {
  534. info.AddValue ("m_MaxCapacity", _maxCapacity);
  535. info.AddValue ("Capacity", Capacity);
  536. info.AddValue ("m_StringValue", ToString ());
  537. info.AddValue ("m_currentThread", 0);
  538. }
  539. StringBuilder (SerializationInfo info, StreamingContext context)
  540. {
  541. string s = info.GetString ("m_StringValue");
  542. if (s == null)
  543. s = "";
  544. _length = s.Length;
  545. _str = _cached_str = s;
  546. _maxCapacity = info.GetInt32 ("m_MaxCapacity");
  547. if (_maxCapacity < 0)
  548. _maxCapacity = Int32.MaxValue;
  549. Capacity = info.GetInt32 ("Capacity");
  550. }
  551. #endif
  552. }
  553. }