StringBuilder.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. // -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
  2. //
  3. // System.Text.StringBuilder
  4. //
  5. // Author: Marcin Szczepanski ([email protected])
  6. //
  7. // TODO: Make sure the coding complies to the ECMA draft, there's some
  8. // variable names that probably don't (like sString)
  9. //
  10. using System.Runtime.CompilerServices;
  11. namespace System.Text {
  12. [Serializable]
  13. public sealed class StringBuilder {
  14. private const int defaultCapacity = 16;
  15. private int sCapacity;
  16. private int sLength;
  17. private char[] sString;
  18. private int sMaxCapacity = Int32.MaxValue;
  19. public StringBuilder(string value, int startIndex, int length, int capacity) {
  20. // first, check the parameters and throw appropriate exceptions if needed
  21. if(null==value) {
  22. throw new System.ArgumentNullException("value");
  23. }
  24. // make sure startIndex is zero or positive
  25. if(startIndex < 0) {
  26. throw new System.ArgumentOutOfRangeException("startIndex", startIndex, "StartIndex cannot be less than zero.");
  27. }
  28. // make sure length is zero or positive
  29. if(length < 0) {
  30. throw new System.ArgumentOutOfRangeException("length", length, "Length cannot be less than zero.");
  31. }
  32. // make sure startIndex and length give a valid substring of value
  33. if(startIndex + (length -1) > (value.Length - 1) ) {
  34. throw new System.ArgumentOutOfRangeException("startIndex", startIndex, "StartIndex and length must refer to a location within the string.");
  35. }
  36. // the capacity must be at least as big as the default capacity
  37. sCapacity = Math.Max(capacity, defaultCapacity);
  38. // LAMESPEC: what to do if capacity is too small to hold the substring?
  39. // Like the MS implementation, double the capacity until it is large enough
  40. while (sCapacity < length) {
  41. // However, take care not to double if that would make the number
  42. // larger than what an int can hold
  43. if (sCapacity <= Int32.MaxValue / 2) {
  44. sCapacity *= 2;
  45. }
  46. else{
  47. sCapacity = Int32.MaxValue;
  48. }
  49. }
  50. sString = new char[sCapacity];
  51. sLength = length;
  52. // if the length is not zero, then we have to copy some characters
  53. if (sLength > 0) {
  54. // Copy the correct number of characters into the internal array
  55. char[] tString = value.ToCharArray(startIndex, sLength);
  56. Array.Copy( tString, sString, sLength);
  57. }
  58. }
  59. public StringBuilder() : this(String.Empty, 0, 0, 0) {}
  60. public StringBuilder( int capacity ) : this("", 0, 0, capacity) {}
  61. public StringBuilder( int capacity, int maxCapacity ) : this("", 0, 0, capacity) {
  62. if(capacity > maxCapacity) {
  63. throw new System.ArgumentOutOfRangeException("capacity", "Capacity exceeds maximum capacity.");
  64. }
  65. sMaxCapacity = maxCapacity;
  66. }
  67. public StringBuilder( string value ) : this(value, 0, value == null ? 0 : value.Length, value == null? 0 : value.Length) {
  68. }
  69. public StringBuilder( string value, int capacity) : this(value, 0, value.Length, capacity) {}
  70. public int MaxCapacity {
  71. get {
  72. // MS runtime always returns Int32.MaxValue.
  73. return sMaxCapacity;
  74. }
  75. }
  76. public int Capacity {
  77. get {
  78. return sCapacity;
  79. }
  80. set {
  81. if( value < sLength ) {
  82. throw new ArgumentException( "Capacity must be > length" );
  83. } else {
  84. char[] tString = new char[value];
  85. Array.Copy( sString, tString, sLength );
  86. sString = tString;
  87. sCapacity = sString.Length;
  88. }
  89. }
  90. }
  91. public int Length {
  92. get {
  93. return sLength;
  94. }
  95. set {
  96. if( value < 0 || value > MaxCapacity) {
  97. throw new ArgumentOutOfRangeException();
  98. } else {
  99. if( value < sLength ) {
  100. // Truncate current string at value
  101. // LAMESPEC: The spec is unclear as to what to do
  102. // with the capacity when truncating the string.
  103. //
  104. // Don't change the capacity, as this is what
  105. // the MS implementation does.
  106. sLength = value;
  107. } else {
  108. // Expand the capacity to the new length and
  109. // pad the string with spaces.
  110. // LAMESPEC: The spec says to put the spaces on the
  111. // left of the string however the MS implementation
  112. // puts them on the right. We'll do that for
  113. // compatibility (!)
  114. char[] tString = new char[ value ];
  115. int padLength = value - sLength;
  116. string padding = new String( ' ', padLength );
  117. Array.Copy( sString, tString, sLength );
  118. Array.Copy( padding.ToCharArray(), 0, tString, sLength, padLength );
  119. sString = tString;
  120. sLength = sString.Length;
  121. sCapacity = value;
  122. }
  123. }
  124. }
  125. }
  126. [IndexerName("Chars")]
  127. public char this[ int index ] {
  128. get {
  129. if( index >= sLength || index < 0 ) {
  130. throw new IndexOutOfRangeException();
  131. }
  132. return sString[ index ];
  133. }
  134. set {
  135. if( index >= sLength || index < 0 ) {
  136. throw new IndexOutOfRangeException();
  137. }
  138. sString[ index ] = value;
  139. }
  140. }
  141. public override string ToString() {
  142. return ToString(0, sLength);
  143. }
  144. public string ToString( int startIndex, int length ) {
  145. if( startIndex < 0 || length < 0 || startIndex + length > sLength ) {
  146. throw new ArgumentOutOfRangeException();
  147. }
  148. return new String( sString, startIndex, length );
  149. }
  150. public int EnsureCapacity( int capacity ) {
  151. if( capacity < 0 ) {
  152. throw new ArgumentOutOfRangeException(
  153. "Capacity must be greater than 0." );
  154. }
  155. if( capacity <= sCapacity ) {
  156. return sCapacity;
  157. } else {
  158. Capacity = capacity;
  159. return sCapacity;
  160. }
  161. }
  162. public bool Equals( StringBuilder sb ) {
  163. if( this.ToString() == sb.ToString() ) {
  164. return true;
  165. } else {
  166. return false;
  167. }
  168. }
  169. public StringBuilder Remove( int startIndex, int length ) {
  170. if( startIndex < 0 || length < 0 || startIndex + length > sLength ) {
  171. throw new ArgumentOutOfRangeException();
  172. }
  173. // Copy everything after the 'removed' part to the start
  174. // of the removed part and truncate the sLength
  175. Array.Copy( sString, startIndex + length, sString,
  176. startIndex, length );
  177. sLength -= length;
  178. return this;
  179. }
  180. public StringBuilder Replace( char oldChar, char newChar ) {
  181. return Replace( oldChar, newChar, 0, sLength);
  182. }
  183. public StringBuilder Replace( char oldChar, char newChar, int startIndex, int count ) {
  184. if( startIndex + count > sLength || startIndex < 0 || count < 0 ) {
  185. throw new ArgumentOutOfRangeException();
  186. }
  187. for( int replaceIterate = startIndex; replaceIterate < startIndex + count; replaceIterate++ ) {
  188. if( this[replaceIterate] == oldChar ) {
  189. this[replaceIterate] = newChar;
  190. }
  191. }
  192. return this;
  193. }
  194. public StringBuilder Replace( string oldValue, string newValue ) {
  195. return Replace( oldValue, newValue, 0, sLength );
  196. }
  197. public StringBuilder Replace( string oldValue, string newValue, int startIndex, int count ) {
  198. string startString = this.ToString();
  199. StringBuilder newStringB = new StringBuilder();
  200. string newString;
  201. if( oldValue == null ) {
  202. throw new ArgumentNullException(
  203. "The old value cannot be null.");
  204. }
  205. if( startIndex < 0 || count < 0 || startIndex + count > sLength ) {
  206. throw new ArgumentOutOfRangeException();
  207. }
  208. if( oldValue.Length == 0 ) {
  209. throw new ArgumentException(
  210. "The old value cannot be zero length.");
  211. }
  212. int nextIndex = startIndex; // Where to start the next search
  213. int lastIndex = nextIndex; // Where the last search finished
  214. while( nextIndex != -1 ) {
  215. nextIndex = startString.IndexOf( oldValue, lastIndex);
  216. if( nextIndex != -1 ) {
  217. // The MS implementation won't replace a substring
  218. // if that substring goes over the "count"
  219. // boundary, so we'll make sure the behaviour
  220. // here is the same.
  221. if( nextIndex + oldValue.Length <= startIndex + count ) {
  222. // Add everything to the left of the old
  223. // string
  224. newStringB.Append( startString.Substring( lastIndex, nextIndex - lastIndex ) );
  225. // Add the replacement string
  226. newStringB.Append( newValue );
  227. // Set the next start point to the
  228. // end of the last match
  229. lastIndex = nextIndex + oldValue.Length;
  230. } else {
  231. // We're past the "count" we're supposed to replace within
  232. nextIndex = -1;
  233. newStringB.Append(
  234. startString.Substring( lastIndex ) );
  235. }
  236. } else {
  237. // Append everything left over
  238. newStringB.Append( startString.Substring( lastIndex ) );
  239. }
  240. }
  241. newString = newStringB.ToString();
  242. EnsureCapacity( newString.Length );
  243. sString = newString.ToCharArray();
  244. sLength = newString.Length;
  245. return this;
  246. }
  247. /* The Append Methods */
  248. // TODO: Currently most of these methods convert the
  249. // parameter to a CharArray (via a String) and then pass
  250. // it to Append( char[] ). There might be a faster way
  251. // of doing this, but it's probably adequate and anything else
  252. // would make it too messy.
  253. //
  254. // As an example, a sample test run of appending a 100 character
  255. // string to the StringBuilder, and loooping this 50,000 times
  256. // results in an elapsed time of 2.4s using the MS StringBuilder
  257. // and 2.7s using this StringBuilder. Note that this results
  258. // in a 5 million character string. I believe MS uses a lot
  259. // of "native" DLLs for the "meat" of the base classes.
  260. [MonoTODO ("Look at all Append methods and complete them if necessary")]
  261. public StringBuilder Append( char[] value ) {
  262. if( sLength + value.Length > sCapacity ) {
  263. // Need more capacity, double the capacity StringBuilder
  264. // and make sure we have at least enough for the value
  265. // if that's going to go over double.
  266. Capacity = value.Length + ( sCapacity + sCapacity);
  267. }
  268. Array.Copy( value, 0, sString, sLength, value.Length );
  269. sLength += value.Length;
  270. return this;
  271. }
  272. public StringBuilder Append( string value ) {
  273. if( value != null ) {
  274. return Append( value.ToCharArray() );
  275. } else {
  276. return null;
  277. }
  278. }
  279. public StringBuilder Append( bool value ) {
  280. return Append( value.ToString().ToCharArray() );
  281. }
  282. public StringBuilder Append( byte value ) {
  283. return Append( value.ToString().ToCharArray() );
  284. }
  285. public StringBuilder Append( decimal value ) {
  286. return Append( value.ToString().ToCharArray() );
  287. }
  288. public StringBuilder Append( double value ) {
  289. return Append( value.ToString().ToCharArray() );
  290. }
  291. public StringBuilder Append( short value ) {
  292. return Append( value.ToString().ToCharArray() );
  293. }
  294. public StringBuilder Append( int value ) {
  295. return Append( value.ToString().ToCharArray() );
  296. }
  297. public StringBuilder Append( long value ) {
  298. return Append( value.ToString().ToCharArray() );
  299. }
  300. public StringBuilder Append( object value ) {
  301. return Append( value.ToString().ToCharArray() );
  302. }
  303. [CLSCompliant(false)]
  304. public StringBuilder Append( sbyte value ) {
  305. return Append( value.ToString().ToCharArray() );
  306. }
  307. public StringBuilder Append( float value ) {
  308. return Append( value.ToString().ToCharArray() );
  309. }
  310. [CLSCompliant(false)]
  311. public StringBuilder Append( ushort value ) {
  312. return Append( value.ToString().ToCharArray() );
  313. }
  314. [CLSCompliant(false)]
  315. public StringBuilder Append( uint value ) {
  316. return Append( value.ToString().ToCharArray() );
  317. }
  318. [CLSCompliant(false)]
  319. public StringBuilder Append( ulong value ) {
  320. return Append( value.ToString().ToCharArray() );
  321. }
  322. public StringBuilder Append( char value ) {
  323. if( sLength + 1 > sCapacity ) {
  324. // Need more capacity, double the capacity StringBuilder
  325. // and make sure we have at least enough for the value
  326. // if that's going to go over double.
  327. Capacity = 1 + ( sCapacity + sCapacity);
  328. }
  329. sString [sLength] = value;
  330. sLength++;
  331. return this;
  332. }
  333. public StringBuilder Append( char value, int repeatCount ) {
  334. if( repeatCount < 0 ) {
  335. throw new ArgumentOutOfRangeException();
  336. }
  337. return Append( new String( value, repeatCount) );
  338. }
  339. public StringBuilder Append( char[] value, int startIndex, int charCount ) {
  340. if( (charCount < 0 || startIndex < 0) ||
  341. ( charCount + startIndex > value.Length ) ) {
  342. throw new ArgumentOutOfRangeException();
  343. }
  344. if( value == null ) {
  345. if( !(startIndex == 0 && charCount == 0) ) {
  346. throw new ArgumentNullException();
  347. } else {
  348. return this;
  349. }
  350. } else {
  351. char[] appendChars = new char[ charCount ];
  352. Array.Copy( value, startIndex, appendChars, 0, charCount );
  353. return Append( appendChars );
  354. }
  355. }
  356. public StringBuilder Append( string value, int startIndex, int count ) {
  357. if( (count < 0 || startIndex < 0) ||
  358. ( startIndex + count > value.Length ) ) {
  359. throw new ArgumentOutOfRangeException();
  360. }
  361. return Append( value.Substring( startIndex, count ).ToCharArray() );
  362. }
  363. public StringBuilder AppendFormat (string format, object arg0 )
  364. {
  365. string result = String.Format (format, arg0);
  366. return Append (result);
  367. }
  368. public StringBuilder AppendFormat (string format, params object[] args )
  369. {
  370. string result = String.Format (format, args);
  371. return Append (result);
  372. }
  373. public StringBuilder AppendFormat (IFormatProvider provider,
  374. string format,
  375. params object[] args)
  376. {
  377. string result = String.Format (provider, format, args);
  378. return Append (result);
  379. }
  380. public StringBuilder AppendFormat (string format, object arg0, object arg1 )
  381. {
  382. string result = String.Format (format, arg0, arg1);
  383. return Append (result);
  384. }
  385. public StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2 )
  386. {
  387. string result = String.Format (format, arg0, arg1, arg2);
  388. return Append (result);
  389. }
  390. /* The Insert Functions */
  391. // Similarly to the Append functions, get everything down to a CharArray
  392. // and insert that.
  393. public StringBuilder Insert( int index, char[] value ) {
  394. if( index > sLength || index < 0) {
  395. throw new ArgumentOutOfRangeException();
  396. }
  397. if( value == null || value.Length == 0 ) {
  398. return this;
  399. } else {
  400. // Check we have the capacity to insert this array
  401. if( sCapacity < sLength + value.Length ) {
  402. Capacity = value.Length + ( sCapacity + sCapacity );
  403. }
  404. // Move everything to the right of the insert point across
  405. Array.Copy( sString, index, sString, index + value.Length, sLength - index);
  406. // Copy in stuff from the insert buffer
  407. Array.Copy( value, 0, sString, index, value.Length );
  408. sLength += value.Length;
  409. return this;
  410. }
  411. }
  412. public StringBuilder Insert( int index, string value ) {
  413. return Insert( index, value.ToCharArray() );
  414. }
  415. public StringBuilder Insert( int index, bool value ) {
  416. return Insert( index, value.ToString().ToCharArray() );
  417. }
  418. public StringBuilder Insert( int index, byte value ) {
  419. return Insert( index, value.ToString().ToCharArray() );
  420. }
  421. public StringBuilder Insert( int index, char value) {
  422. char[] insertChar = new char[1];
  423. insertChar[0] = value;
  424. return Insert( index, insertChar );
  425. }
  426. public StringBuilder Insert( int index, decimal value ) {
  427. return Insert( index, value.ToString().ToCharArray() );
  428. }
  429. public StringBuilder Insert( int index, double value ) {
  430. return Insert( index, value.ToString().ToCharArray() );
  431. }
  432. public StringBuilder Insert( int index, short value ) {
  433. return Insert( index, value.ToString().ToCharArray() );
  434. }
  435. public StringBuilder Insert( int index, int value ) {
  436. return Insert( index, value.ToString().ToCharArray() );
  437. }
  438. public StringBuilder Insert( int index, long value ) {
  439. return Insert( index, value.ToString().ToCharArray() );
  440. }
  441. public StringBuilder Insert( int index, object value ) {
  442. return Insert( index, value.ToString().ToCharArray() );
  443. }
  444. [CLSCompliant(false)]
  445. public StringBuilder Insert( int index, sbyte value ) {
  446. return Insert( index, value.ToString().ToCharArray() );
  447. }
  448. public StringBuilder Insert( int index, float value ) {
  449. return Insert( index, value.ToString().ToCharArray() );
  450. }
  451. [CLSCompliant(false)]
  452. public StringBuilder Insert( int index, ushort value ) {
  453. return Insert( index, value.ToString().ToCharArray() );
  454. }
  455. [CLSCompliant(false)]
  456. public StringBuilder Insert( int index, uint value ) {
  457. return Insert( index, value.ToString().ToCharArray() );
  458. }
  459. [CLSCompliant(false)]
  460. public StringBuilder Insert( int index, ulong value ) {
  461. return Insert( index, value.ToString().ToCharArray() );
  462. }
  463. public StringBuilder Insert( int index, string value, int count ) {
  464. if ( count < 0 ) {
  465. throw new ArgumentOutOfRangeException();
  466. }
  467. if( value != null ) {
  468. if( value != "" ) {
  469. for( int insertCount = 0; insertCount < count;
  470. insertCount++ ) {
  471. Insert( index, value.ToCharArray() );
  472. }
  473. }
  474. }
  475. return this;
  476. }
  477. public StringBuilder Insert( int index, char[] value, int startIndex,
  478. int charCount ) {
  479. if( value != null ) {
  480. if( charCount < 0 || startIndex < 0 || startIndex + charCount > value.Length ) {
  481. throw new ArgumentOutOfRangeException();
  482. }
  483. char[] insertChars = new char[ charCount ];
  484. Array.Copy( value, startIndex, insertChars, 0, charCount );
  485. return Insert( index, insertChars );
  486. } else {
  487. return this;
  488. }
  489. }
  490. }
  491. }