StringBuilder.cs 17 KB

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