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 = needed_cap;
  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 = needed_cap;
  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 = needed_cap;
  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. int needed_cap = _length + charCount;
  344. InternalEnsureCapacity (needed_cap);
  345. String.InternalStrcpy (_str, _length, value, startIndex, charCount);
  346. _length = needed_cap;
  347. return this;
  348. }
  349. public StringBuilder Append (string value, int startIndex, int count)
  350. {
  351. if (value == null) {
  352. if (startIndex != 0 && count != 0)
  353. throw new ArgumentNullException ("value");
  354. return this;
  355. }
  356. if ((count < 0 || startIndex < 0) || (startIndex > value.Length - count))
  357. throw new ArgumentOutOfRangeException();
  358. int needed_cap = _length + count;
  359. if (null != _cached_str || _str.Length < needed_cap)
  360. InternalEnsureCapacity (needed_cap);
  361. String.InternalStrcpy (_str, _length, value, startIndex, count);
  362. _length = needed_cap;
  363. return this;
  364. }
  365. #if NET_2_0
  366. public StringBuilder AppendLine ()
  367. {
  368. return Append (System.Environment.NewLine);
  369. }
  370. public StringBuilder AppendLine (string value)
  371. {
  372. return Append (value).Append (System.Environment.NewLine);
  373. }
  374. #endif
  375. public StringBuilder AppendFormat (string format, object arg0)
  376. {
  377. return AppendFormat (null, format, new object [] { arg0 });
  378. }
  379. public StringBuilder AppendFormat (string format, params object[] args)
  380. {
  381. return AppendFormat (null, format, args);
  382. }
  383. public StringBuilder AppendFormat (IFormatProvider provider,
  384. string format,
  385. params object[] args)
  386. {
  387. String.FormatHelper (this, provider, format, args);
  388. return this;
  389. }
  390. public StringBuilder AppendFormat (string format, object arg0, object arg1)
  391. {
  392. return AppendFormat (null, format, new object [] { arg0, arg1 });
  393. }
  394. public StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2)
  395. {
  396. return AppendFormat (null, format, new object [] { arg0, arg1, arg2 });
  397. }
  398. /* The Insert Functions */
  399. public StringBuilder Insert (int index, char[] value)
  400. {
  401. return Insert (index, new string (value));
  402. }
  403. public StringBuilder Insert (int index, string value)
  404. {
  405. if( index > _length || index < 0)
  406. throw new ArgumentOutOfRangeException();
  407. if (value == null || value.Length == 0)
  408. return this;
  409. InternalEnsureCapacity (_length + value.Length);
  410. // Move everything to the right of the insert point across
  411. String.InternalStrcpy (_str, index + value.Length, _str, index, _length - index);
  412. // Copy in stuff from the insert buffer
  413. String.InternalStrcpy (_str, index, value);
  414. _length += value.Length;
  415. return this;
  416. }
  417. public StringBuilder Insert( int index, bool value ) {
  418. return Insert (index, value.ToString());
  419. }
  420. public StringBuilder Insert( int index, byte value ) {
  421. return Insert (index, value.ToString());
  422. }
  423. public StringBuilder Insert( int index, char value)
  424. {
  425. if (index > _length || index < 0)
  426. throw new ArgumentOutOfRangeException ("index");
  427. InternalEnsureCapacity (_length + 1);
  428. // Move everything to the right of the insert point across
  429. String.InternalStrcpy (_str, index + 1, _str, index, _length - index);
  430. _str.InternalSetChar (index, value);
  431. _length++;
  432. return this;
  433. }
  434. public StringBuilder Insert( int index, decimal value ) {
  435. return Insert (index, value.ToString());
  436. }
  437. public StringBuilder Insert( int index, double value ) {
  438. return Insert (index, value.ToString());
  439. }
  440. public StringBuilder Insert( int index, short value ) {
  441. return Insert (index, value.ToString());
  442. }
  443. public StringBuilder Insert( int index, int value ) {
  444. return Insert (index, value.ToString());
  445. }
  446. public StringBuilder Insert( int index, long value ) {
  447. return Insert (index, value.ToString());
  448. }
  449. public StringBuilder Insert( int index, object value ) {
  450. return Insert (index, value.ToString());
  451. }
  452. [CLSCompliant(false)]
  453. public StringBuilder Insert( int index, sbyte value ) {
  454. return Insert (index, value.ToString() );
  455. }
  456. public StringBuilder Insert (int index, float value) {
  457. return Insert (index, value.ToString() );
  458. }
  459. [CLSCompliant(false)]
  460. public StringBuilder Insert (int index, ushort value) {
  461. return Insert (index, value.ToString() );
  462. }
  463. [CLSCompliant(false)]
  464. public StringBuilder Insert (int index, uint value) {
  465. return Insert ( index, value.ToString() );
  466. }
  467. [CLSCompliant(false)]
  468. public StringBuilder Insert (int index, ulong value) {
  469. return Insert ( index, value.ToString() );
  470. }
  471. public StringBuilder Insert (int index, string value, int count)
  472. {
  473. // LAMESPEC: The spec says to throw an exception if
  474. // count < 0, while MS throws even for count < 1!
  475. if ( count < 0 )
  476. throw new ArgumentOutOfRangeException();
  477. if (value != null && value != String.Empty)
  478. for (int insertCount = 0; insertCount < count; insertCount++)
  479. Insert( index, value );
  480. return this;
  481. }
  482. public StringBuilder Insert (int index, char [] value, int startIndex, int charCount)
  483. {
  484. if (value == null) {
  485. if (startIndex == 0 && charCount == 0)
  486. return this;
  487. throw new ArgumentNullException ("value");
  488. }
  489. if (charCount < 0 || startIndex < 0 || startIndex > value.Length - charCount)
  490. throw new ArgumentOutOfRangeException ();
  491. return Insert (index, new String (value, startIndex, charCount));
  492. }
  493. private void InternalEnsureCapacity (int size)
  494. {
  495. if (size > _str.Length || (object) _cached_str == (object) _str) {
  496. int capacity = _str.Length;
  497. // Try double buffer, if that doesn't work, set the length as capacity
  498. if (size > capacity) {
  499. // The first time a string is appended, we just set _cached_str
  500. // and _str to it. This allows us to do some optimizations.
  501. // Below, we take this into account.
  502. if ((object) _cached_str == (object) _str && capacity < constDefaultCapacity)
  503. capacity = constDefaultCapacity;
  504. capacity = capacity << 1;
  505. if (size > capacity)
  506. capacity = size;
  507. if (capacity >= Int32.MaxValue || capacity < 0)
  508. capacity = Int32.MaxValue;
  509. if (capacity > _maxCapacity && size <= _maxCapacity)
  510. capacity = _maxCapacity;
  511. if (capacity > _maxCapacity)
  512. throw new ArgumentOutOfRangeException ("size", "capacity was less than the current size.");
  513. }
  514. string tmp = String.InternalAllocateStr (capacity);
  515. if (_length > 0)
  516. String.InternalStrcpy (tmp, 0, _str, 0, _length);
  517. _str = tmp;
  518. }
  519. _cached_str = null;
  520. }
  521. #if NET_2_0
  522. public void CopyTo (int sourceIndex, char [] destination, int destinationIndex, int count)
  523. {
  524. if (destination == null)
  525. throw new ArgumentNullException ("destination");
  526. if ((Length - count < sourceIndex) ||
  527. (destination.Length -count < destinationIndex) ||
  528. (sourceIndex < 0 || destinationIndex < 0 || count < 0))
  529. throw new ArgumentOutOfRangeException ();
  530. for (int i = 0; i < count; i++)
  531. destination [destinationIndex+i] = _str [sourceIndex+i];
  532. }
  533. void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
  534. {
  535. info.AddValue ("m_MaxCapacity", _maxCapacity);
  536. info.AddValue ("Capacity", Capacity);
  537. info.AddValue ("m_StringValue", ToString ());
  538. info.AddValue ("m_currentThread", 0);
  539. }
  540. StringBuilder (SerializationInfo info, StreamingContext context)
  541. {
  542. string s = info.GetString ("m_StringValue");
  543. if (s == null)
  544. s = "";
  545. _length = s.Length;
  546. _str = _cached_str = s;
  547. _maxCapacity = info.GetInt32 ("m_MaxCapacity");
  548. if (_maxCapacity < 0)
  549. _maxCapacity = Int32.MaxValue;
  550. Capacity = info.GetInt32 ("Capacity");
  551. }
  552. #endif
  553. }
  554. }