StringBuilder.cs 16 KB

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