StringBuilder.cs 18 KB

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