StringBuilder.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  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 = null;
  46. private string _cached_str = null;
  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.InternalStrcpy (_str, startIndex, replace);
  234. _length = replace.Length + (_length - count);
  235. return this;
  236. }
  237. /* The Append Methods */
  238. public StringBuilder Append (char[] value)
  239. {
  240. if (value == null)
  241. return this;
  242. int needed_cap = _length + value.Length;
  243. if (null != _cached_str || _str.Length < needed_cap)
  244. InternalEnsureCapacity (needed_cap);
  245. String.InternalStrcpy (_str, _length, value);
  246. _length += value.Length;
  247. return this;
  248. }
  249. public StringBuilder Append (string value)
  250. {
  251. if (value == null)
  252. return this;
  253. if (_length == 0 && value.Length < _maxCapacity && value.Length > _str.Length) {
  254. _length = value.Length;
  255. _str = _cached_str = value;
  256. return this;
  257. }
  258. int needed_cap = _length + value.Length;
  259. if (null != _cached_str || _str.Length < needed_cap)
  260. InternalEnsureCapacity (needed_cap);
  261. String.InternalStrcpy (_str, _length, value);
  262. _length += value.Length;
  263. return this;
  264. }
  265. public StringBuilder Append (bool value) {
  266. return Append (value.ToString());
  267. }
  268. public StringBuilder Append (byte value) {
  269. return Append (value.ToString());
  270. }
  271. public StringBuilder Append (decimal value) {
  272. return Append (value.ToString());
  273. }
  274. public StringBuilder Append (double value) {
  275. return Append (value.ToString());
  276. }
  277. public StringBuilder Append (short value) {
  278. return Append (value.ToString());
  279. }
  280. public StringBuilder Append (int value) {
  281. return Append (value.ToString());
  282. }
  283. public StringBuilder Append (long value) {
  284. return Append (value.ToString());
  285. }
  286. public StringBuilder Append (object value) {
  287. if (value == null)
  288. return this;
  289. return Append (value.ToString());
  290. }
  291. [CLSCompliant(false)]
  292. public StringBuilder Append (sbyte value) {
  293. return Append (value.ToString());
  294. }
  295. public StringBuilder Append (float value) {
  296. return Append (value.ToString());
  297. }
  298. [CLSCompliant(false)]
  299. public StringBuilder Append (ushort value) {
  300. return Append (value.ToString());
  301. }
  302. [CLSCompliant(false)]
  303. public StringBuilder Append (uint value) {
  304. return Append (value.ToString());
  305. }
  306. [CLSCompliant(false)]
  307. public StringBuilder Append (ulong value) {
  308. return Append (value.ToString());
  309. }
  310. public StringBuilder Append (char value)
  311. {
  312. int needed_cap = _length + 1;
  313. if (null != _cached_str || _str.Length < needed_cap)
  314. InternalEnsureCapacity (needed_cap);
  315. _str.InternalSetChar(_length, value);
  316. _length++;
  317. return this;
  318. }
  319. public StringBuilder Append (char value, int repeatCount)
  320. {
  321. if( repeatCount < 0 )
  322. throw new ArgumentOutOfRangeException();
  323. InternalEnsureCapacity (_length + repeatCount);
  324. for (int i = 0; i < repeatCount; i++)
  325. _str.InternalSetChar (_length++, value);
  326. return this;
  327. }
  328. public StringBuilder Append( char[] value, int startIndex, int charCount )
  329. {
  330. if (value == null) {
  331. if (!(startIndex == 0 && charCount == 0))
  332. throw new ArgumentNullException ("value");
  333. return this;
  334. }
  335. if ((charCount < 0 || startIndex < 0) || (startIndex > value.Length - charCount))
  336. throw new ArgumentOutOfRangeException();
  337. InternalEnsureCapacity (_length + charCount);
  338. String.InternalStrcpy (_str, _length, value, startIndex, charCount);
  339. _length += charCount;
  340. return this;
  341. }
  342. public StringBuilder Append (string value, int startIndex, int count)
  343. {
  344. if (value == null) {
  345. if (startIndex != 0 && count != 0)
  346. throw new ArgumentNullException ("value");
  347. return this;
  348. }
  349. if ((count < 0 || startIndex < 0) || (startIndex > value.Length - count))
  350. throw new ArgumentOutOfRangeException();
  351. int needed_cap = _length + count;
  352. if (null != _cached_str || _str.Length < needed_cap)
  353. InternalEnsureCapacity (needed_cap);
  354. String.InternalStrcpy (_str, _length, value, startIndex, count);
  355. _length += count;
  356. return this;
  357. }
  358. #if NET_2_0
  359. public StringBuilder AppendLine ()
  360. {
  361. return Append (System.Environment.NewLine);
  362. }
  363. public StringBuilder AppendLine (string value)
  364. {
  365. return Append (value).Append (System.Environment.NewLine);
  366. }
  367. #endif
  368. public StringBuilder AppendFormat (string format, object arg0)
  369. {
  370. return AppendFormat (null, format, new object [] { arg0 });
  371. }
  372. public StringBuilder AppendFormat (string format, params object[] args)
  373. {
  374. return AppendFormat (null, format, args);
  375. }
  376. public StringBuilder AppendFormat (IFormatProvider provider,
  377. string format,
  378. params object[] args)
  379. {
  380. String.FormatHelper (this, provider, format, args);
  381. return this;
  382. }
  383. public StringBuilder AppendFormat (string format, object arg0, object arg1)
  384. {
  385. return AppendFormat (null, format, new object [] { arg0, arg1 });
  386. }
  387. public StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2)
  388. {
  389. return AppendFormat (null, format, new object [] { arg0, arg1, arg2 });
  390. }
  391. /* The Insert Functions */
  392. public StringBuilder Insert (int index, char[] value)
  393. {
  394. return Insert (index, new string (value));
  395. }
  396. public StringBuilder Insert (int index, string value)
  397. {
  398. if( index > _length || index < 0)
  399. throw new ArgumentOutOfRangeException();
  400. if (value == null || value.Length == 0)
  401. return this;
  402. InternalEnsureCapacity (_length + value.Length);
  403. // Move everything to the right of the insert point across
  404. String.InternalStrcpy (_str, index + value.Length, _str, index, _length - index);
  405. // Copy in stuff from the insert buffer
  406. String.InternalStrcpy (_str, index, value);
  407. _length += value.Length;
  408. return this;
  409. }
  410. public StringBuilder Insert( int index, bool value ) {
  411. return Insert (index, value.ToString());
  412. }
  413. public StringBuilder Insert( int index, byte value ) {
  414. return Insert (index, value.ToString());
  415. }
  416. public StringBuilder Insert( int index, char value)
  417. {
  418. if (index > _length || index < 0)
  419. throw new ArgumentOutOfRangeException ("index");
  420. InternalEnsureCapacity (_length + 1);
  421. // Move everything to the right of the insert point across
  422. String.InternalStrcpy (_str, index + 1, _str, index, _length - index);
  423. _str.InternalSetChar (index, value);
  424. _length++;
  425. return this;
  426. }
  427. public StringBuilder Insert( int index, decimal value ) {
  428. return Insert (index, value.ToString());
  429. }
  430. public StringBuilder Insert( int index, double value ) {
  431. return Insert (index, value.ToString());
  432. }
  433. public StringBuilder Insert( int index, short value ) {
  434. return Insert (index, value.ToString());
  435. }
  436. public StringBuilder Insert( int index, int value ) {
  437. return Insert (index, value.ToString());
  438. }
  439. public StringBuilder Insert( int index, long value ) {
  440. return Insert (index, value.ToString());
  441. }
  442. public StringBuilder Insert( int index, object value ) {
  443. return Insert (index, value.ToString());
  444. }
  445. [CLSCompliant(false)]
  446. public StringBuilder Insert( int index, sbyte value ) {
  447. return Insert (index, value.ToString() );
  448. }
  449. public StringBuilder Insert (int index, float value) {
  450. return Insert (index, value.ToString() );
  451. }
  452. [CLSCompliant(false)]
  453. public StringBuilder Insert (int index, ushort value) {
  454. return Insert (index, value.ToString() );
  455. }
  456. [CLSCompliant(false)]
  457. public StringBuilder Insert (int index, uint value) {
  458. return Insert ( index, value.ToString() );
  459. }
  460. [CLSCompliant(false)]
  461. public StringBuilder Insert (int index, ulong value) {
  462. return Insert ( index, value.ToString() );
  463. }
  464. public StringBuilder Insert (int index, string value, int count)
  465. {
  466. // LAMESPEC: The spec says to throw an exception if
  467. // count < 0, while MS throws even for count < 1!
  468. if ( count < 0 )
  469. throw new ArgumentOutOfRangeException();
  470. if (value != null && value != String.Empty)
  471. for (int insertCount = 0; insertCount < count; insertCount++)
  472. Insert( index, value );
  473. return this;
  474. }
  475. public StringBuilder Insert (int index, char [] value, int startIndex, int charCount)
  476. {
  477. if (value == null) {
  478. if (startIndex == 0 && charCount == 0)
  479. return this;
  480. throw new ArgumentNullException ("value");
  481. }
  482. if (charCount < 0 || startIndex < 0 || startIndex > value.Length - charCount)
  483. throw new ArgumentOutOfRangeException ();
  484. return Insert (index, new String (value, startIndex, charCount));
  485. }
  486. private void InternalEnsureCapacity (int size)
  487. {
  488. if (size > _str.Length || _cached_str == _str)
  489. {
  490. int capacity = _str.Length;
  491. // Try double buffer, if that doesn't work, set the length as capacity
  492. if (size > capacity) {
  493. // The first time a string is appended, we just set _cached_str
  494. // and _str to it. This allows us to do some optimizations.
  495. // Below, we take this into account.
  496. if (_cached_str == _str && capacity < constDefaultCapacity)
  497. capacity = constDefaultCapacity;
  498. capacity = capacity << 1;
  499. if (size > capacity)
  500. capacity = size;
  501. if (capacity >= Int32.MaxValue || capacity < 0)
  502. capacity = Int32.MaxValue;
  503. if (capacity > _maxCapacity && size <= _maxCapacity)
  504. capacity = _maxCapacity;
  505. if (capacity > _maxCapacity)
  506. throw new ArgumentOutOfRangeException ("size", "capacity was less than the current size.");
  507. }
  508. string tmp = String.InternalAllocateStr (capacity);
  509. if (_length > 0)
  510. String.InternalStrcpy (tmp, 0, _str, 0, _length);
  511. _str = tmp;
  512. }
  513. _cached_str = null;
  514. }
  515. }
  516. }