PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/mcs/class/corlib/System.Text/StringBuilder.cs

http://github.com/mono/mono
C# | 774 lines | 525 code | 171 blank | 78 comment | 172 complexity | 3ef06f0d7a9d15f615946346c1683cef MD5 | raw file
Possible License(s): GPL-2.0, CC-BY-SA-3.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, LGPL-2.1, Unlicense, Apache-2.0
  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 (marcins@zipworld.com.au)
  7. // Paolo Molaro (lupus@ximian.com)
  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. // Copyright 2011 Xamarin Inc
  19. //
  20. // Permission is hereby granted, free of charge, to any person obtaining
  21. // a copy of this software and associated documentation files (the
  22. // "Software"), to deal in the Software without restriction, including
  23. // without limitation the rights to use, copy, modify, merge, publish,
  24. // distribute, sublicense, and/or sell copies of the Software, and to
  25. // permit persons to whom the Software is furnished to do so, subject to
  26. // the following conditions:
  27. //
  28. // The above copyright notice and this permission notice shall be
  29. // included in all copies or substantial portions of the Software.
  30. //
  31. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  32. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  33. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  34. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  35. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  36. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  37. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  38. //
  39. using System.Runtime.Serialization;
  40. using System.Runtime.CompilerServices;
  41. using System.Runtime.InteropServices;
  42. namespace System.Text {
  43. [Serializable]
  44. [ComVisible (true)]
  45. [MonoLimitation ("Serialization format not compatible with .NET")]
  46. [StructLayout (LayoutKind.Sequential)]
  47. public sealed class StringBuilder : ISerializable
  48. {
  49. private int _length;
  50. private string _str;
  51. private string _cached_str;
  52. private int _maxCapacity;
  53. private const int constDefaultCapacity = 16;
  54. public StringBuilder(string value, int startIndex, int length, int capacity)
  55. : this (value, startIndex, length, capacity, Int32.MaxValue)
  56. {
  57. }
  58. private StringBuilder(string value, int startIndex, int length, int capacity, int maxCapacity)
  59. {
  60. // first, check the parameters and throw appropriate exceptions if needed
  61. if (null == value)
  62. value = "";
  63. // make sure startIndex is zero or positive
  64. if (startIndex < 0)
  65. throw new System.ArgumentOutOfRangeException ("startIndex", startIndex, "StartIndex cannot be less than zero.");
  66. // make sure length is zero or positive
  67. if(length < 0)
  68. throw new System.ArgumentOutOfRangeException ("length", length, "Length cannot be less than zero.");
  69. if (capacity < 0)
  70. throw new System.ArgumentOutOfRangeException ("capacity", capacity, "capacity must be greater than zero.");
  71. if (maxCapacity < 1)
  72. throw new System.ArgumentOutOfRangeException ("maxCapacity", "maxCapacity is less than one.");
  73. if (capacity > maxCapacity)
  74. throw new System.ArgumentOutOfRangeException ("capacity", "Capacity exceeds maximum capacity.");
  75. // make sure startIndex and length give a valid substring of value
  76. // re-ordered to avoid possible integer overflow
  77. if (startIndex > value.Length - length)
  78. throw new System.ArgumentOutOfRangeException ("startIndex", startIndex, "StartIndex and length must refer to a location within the string.");
  79. if (capacity == 0) {
  80. if (maxCapacity > constDefaultCapacity)
  81. capacity = constDefaultCapacity;
  82. else
  83. _str = _cached_str = String.Empty;
  84. }
  85. _maxCapacity = maxCapacity;
  86. if (_str == null)
  87. _str = String.InternalAllocateStr ((length > capacity) ? length : capacity);
  88. if (length > 0)
  89. String.CharCopy (_str, 0, value, startIndex, length);
  90. _length = length;
  91. }
  92. public StringBuilder () : this (null) {}
  93. public StringBuilder(int capacity) : this (String.Empty, 0, 0, capacity) {}
  94. public StringBuilder(int capacity, int maxCapacity) : this (String.Empty, 0, 0, capacity, maxCapacity) { }
  95. public StringBuilder (string value)
  96. {
  97. /*
  98. * This is an optimization to avoid allocating the internal string
  99. * until the first Append () call.
  100. * The runtime pinvoke marshalling code needs to be aware of this.
  101. */
  102. if (null == value)
  103. value = "";
  104. _length = value.Length;
  105. _str = _cached_str = value;
  106. _maxCapacity = Int32.MaxValue;
  107. }
  108. public StringBuilder( string value, int capacity) : this(value == null ? "" : value, 0, value == null ? 0 : value.Length, capacity) {}
  109. public int MaxCapacity {
  110. get {
  111. return _maxCapacity;
  112. }
  113. }
  114. public int Capacity {
  115. get {
  116. if (_str.Length == 0)
  117. return Math.Min (_maxCapacity, constDefaultCapacity);
  118. return _str.Length;
  119. }
  120. set {
  121. if (value < _length)
  122. throw new ArgumentException( "Capacity must be larger than length" );
  123. if (value > _maxCapacity)
  124. throw new ArgumentOutOfRangeException ("value", "Should be less than or equal to MaxCapacity");
  125. InternalEnsureCapacity(value);
  126. }
  127. }
  128. public int Length {
  129. get {
  130. return _length;
  131. }
  132. set {
  133. if( value < 0 || value > _maxCapacity)
  134. throw new ArgumentOutOfRangeException();
  135. if (value == _length)
  136. return;
  137. if (value < _length) {
  138. // LAMESPEC: The spec is unclear as to what to do
  139. // with the capacity when truncating the string.
  140. // Do as MS, keep the capacity
  141. // Make sure that we invalidate any cached string.
  142. InternalEnsureCapacity (value);
  143. _length = value;
  144. } else {
  145. // Expand the capacity to the new length and
  146. // pad the string with NULL characters.
  147. Append('\0', value - _length);
  148. }
  149. }
  150. }
  151. [IndexerName("Chars")]
  152. public char this [int index] {
  153. get {
  154. if (index >= _length || index < 0)
  155. throw new IndexOutOfRangeException();
  156. return _str [index];
  157. }
  158. set {
  159. if (index >= _length || index < 0)
  160. throw new IndexOutOfRangeException();
  161. if (null != _cached_str)
  162. InternalEnsureCapacity (_length);
  163. _str.InternalSetChar (index, value);
  164. }
  165. }
  166. public override string ToString ()
  167. {
  168. if (_length == 0)
  169. return String.Empty;
  170. if (null != _cached_str)
  171. return _cached_str;
  172. // If we only have a half-full buffer we return a new string.
  173. if (_length < (_str.Length >> 1) || (_str.Length > string.LOS_limit && _length <= string.LOS_limit))
  174. {
  175. // use String.SubstringUnchecked instead of String.Substring
  176. // as the former is guaranteed to create a new string object
  177. _cached_str = _str.SubstringUnchecked (0, _length);
  178. return _cached_str;
  179. }
  180. _cached_str = _str;
  181. _str.InternalSetLength(_length);
  182. return _str;
  183. }
  184. public string ToString (int startIndex, int length)
  185. {
  186. // re-ordered to avoid possible integer overflow
  187. if (startIndex < 0 || length < 0 || startIndex > _length - length)
  188. throw new ArgumentOutOfRangeException();
  189. // use String.SubstringUnchecked instead of String.Substring
  190. // as the former is guaranteed to create a new string object
  191. if (startIndex == 0 && length == _length)
  192. return ToString ();
  193. else
  194. return _str.SubstringUnchecked (startIndex, length);
  195. }
  196. public int EnsureCapacity (int capacity)
  197. {
  198. if (capacity < 0)
  199. throw new ArgumentOutOfRangeException ("Capacity must be greater than 0." );
  200. if( capacity <= _str.Length )
  201. return _str.Length;
  202. InternalEnsureCapacity (capacity);
  203. return _str.Length;
  204. }
  205. public bool Equals (StringBuilder sb)
  206. {
  207. if (((object)sb) == null)
  208. return false;
  209. if (_length == sb.Length && _str == sb._str )
  210. return true;
  211. return false;
  212. }
  213. public StringBuilder Remove (int startIndex, int length)
  214. {
  215. // re-ordered to avoid possible integer overflow
  216. if (startIndex < 0 || length < 0 || startIndex > _length - length)
  217. throw new ArgumentOutOfRangeException();
  218. if (null != _cached_str)
  219. InternalEnsureCapacity (_length);
  220. // Copy everything after the 'removed' part to the start
  221. // of the removed part and truncate the sLength
  222. if (_length - (startIndex + length) > 0)
  223. String.CharCopy (_str, startIndex, _str, startIndex + length, _length - (startIndex + length));
  224. _length -= length;
  225. return this;
  226. }
  227. public StringBuilder Replace (char oldChar, char newChar)
  228. {
  229. return Replace( oldChar, newChar, 0, _length);
  230. }
  231. public StringBuilder Replace (char oldChar, char newChar, int startIndex, int count)
  232. {
  233. // re-ordered to avoid possible integer overflow
  234. if (startIndex > _length - count || startIndex < 0 || count < 0)
  235. throw new ArgumentOutOfRangeException();
  236. if (null != _cached_str)
  237. InternalEnsureCapacity (_str.Length);
  238. for (int replaceIterate = startIndex; replaceIterate < startIndex + count; replaceIterate++ ) {
  239. if( _str [replaceIterate] == oldChar )
  240. _str.InternalSetChar (replaceIterate, newChar);
  241. }
  242. return this;
  243. }
  244. public StringBuilder Replace( string oldValue, string newValue ) {
  245. return Replace (oldValue, newValue, 0, _length);
  246. }
  247. public StringBuilder Replace( string oldValue, string newValue, int startIndex, int count )
  248. {
  249. if (oldValue == null)
  250. throw new ArgumentNullException ("The old value cannot be null.");
  251. if (startIndex < 0 || count < 0 || startIndex > _length - count)
  252. throw new ArgumentOutOfRangeException ();
  253. if (oldValue.Length == 0)
  254. throw new ArgumentException ("The old value cannot be zero length.");
  255. string substr = _str.Substring(startIndex, count);
  256. string replace = substr.Replace(oldValue, newValue);
  257. // return early if no oldValue was found
  258. if ((object) replace == (object) substr)
  259. return this;
  260. InternalEnsureCapacity (replace.Length + (_length - count));
  261. // shift end part
  262. if (replace.Length < count)
  263. String.CharCopy (_str, startIndex + replace.Length, _str, startIndex + count, _length - startIndex - count);
  264. else if (replace.Length > count)
  265. String.CharCopyReverse (_str, startIndex + replace.Length, _str, startIndex + count, _length - startIndex - count);
  266. // copy middle part back into _str
  267. String.CharCopy (_str, startIndex, replace, 0, replace.Length);
  268. _length = replace.Length + (_length - count);
  269. return this;
  270. }
  271. /* The Append Methods */
  272. public StringBuilder Append (char[] value)
  273. {
  274. if (value == null)
  275. return this;
  276. int needed_cap = _length + value.Length;
  277. if (null != _cached_str || _str.Length < needed_cap)
  278. InternalEnsureCapacity (needed_cap);
  279. String.CharCopy (_str, _length, value, 0, value.Length);
  280. _length = needed_cap;
  281. return this;
  282. }
  283. public StringBuilder Append (string value)
  284. {
  285. if (value == null)
  286. return this;
  287. if (_length == 0 && value.Length < _maxCapacity && value.Length > _str.Length) {
  288. _length = value.Length;
  289. _str = _cached_str = value;
  290. return this;
  291. }
  292. int needed_cap = _length + value.Length;
  293. if (null != _cached_str || _str.Length < needed_cap)
  294. InternalEnsureCapacity (needed_cap);
  295. String.CharCopy (_str, _length, value, 0, value.Length);
  296. _length = needed_cap;
  297. return this;
  298. }
  299. public StringBuilder Append (bool value) {
  300. return Append (value.ToString());
  301. }
  302. public StringBuilder Append (byte value) {
  303. return Append (value.ToString());
  304. }
  305. public StringBuilder Append (decimal value) {
  306. return Append (value.ToString());
  307. }
  308. public StringBuilder Append (double value) {
  309. return Append (value.ToString());
  310. }
  311. public StringBuilder Append (short value) {
  312. return Append (value.ToString());
  313. }
  314. public StringBuilder Append (int value) {
  315. return Append (value.ToString());
  316. }
  317. public StringBuilder Append (long value) {
  318. return Append (value.ToString());
  319. }
  320. public StringBuilder Append (object value) {
  321. if (value == null)
  322. return this;
  323. return Append (value.ToString());
  324. }
  325. [CLSCompliant(false)]
  326. public StringBuilder Append (sbyte value) {
  327. return Append (value.ToString());
  328. }
  329. public StringBuilder Append (float value) {
  330. return Append (value.ToString());
  331. }
  332. [CLSCompliant(false)]
  333. public StringBuilder Append (ushort value) {
  334. return Append (value.ToString());
  335. }
  336. [CLSCompliant(false)]
  337. public StringBuilder Append (uint value) {
  338. return Append (value.ToString());
  339. }
  340. [CLSCompliant(false)]
  341. public StringBuilder Append (ulong value) {
  342. return Append (value.ToString());
  343. }
  344. public StringBuilder Append (char value)
  345. {
  346. int needed_cap = _length + 1;
  347. if (null != _cached_str || _str.Length < needed_cap)
  348. InternalEnsureCapacity (needed_cap);
  349. _str.InternalSetChar(_length, value);
  350. _length = needed_cap;
  351. return this;
  352. }
  353. public StringBuilder Append (char value, int repeatCount)
  354. {
  355. if( repeatCount < 0 )
  356. throw new ArgumentOutOfRangeException();
  357. InternalEnsureCapacity (_length + repeatCount);
  358. for (int i = 0; i < repeatCount; i++)
  359. _str.InternalSetChar (_length++, value);
  360. return this;
  361. }
  362. public StringBuilder Append( char[] value, int startIndex, int charCount )
  363. {
  364. if (value == null) {
  365. if (!(startIndex == 0 && charCount == 0))
  366. throw new ArgumentNullException ("value");
  367. return this;
  368. }
  369. if ((charCount < 0 || startIndex < 0) || (startIndex > value.Length - charCount))
  370. throw new ArgumentOutOfRangeException();
  371. int needed_cap = _length + charCount;
  372. InternalEnsureCapacity (needed_cap);
  373. String.CharCopy (_str, _length, value, startIndex, charCount);
  374. _length = needed_cap;
  375. return this;
  376. }
  377. public StringBuilder Append (string value, int startIndex, int count)
  378. {
  379. if (value == null) {
  380. if (startIndex != 0 && count != 0)
  381. throw new ArgumentNullException ("value");
  382. return this;
  383. }
  384. if ((count < 0 || startIndex < 0) || (startIndex > value.Length - count))
  385. throw new ArgumentOutOfRangeException();
  386. int needed_cap = _length + count;
  387. if (null != _cached_str || _str.Length < needed_cap)
  388. InternalEnsureCapacity (needed_cap);
  389. String.CharCopy (_str, _length, value, startIndex, count);
  390. _length = needed_cap;
  391. return this;
  392. }
  393. #if NET_4_0 || MOONLIGHT || MOBILE
  394. public StringBuilder Clear ()
  395. {
  396. Length = 0;
  397. return this;
  398. }
  399. #endif
  400. [ComVisible (false)]
  401. public StringBuilder AppendLine ()
  402. {
  403. return Append (System.Environment.NewLine);
  404. }
  405. [ComVisible (false)]
  406. public StringBuilder AppendLine (string value)
  407. {
  408. return Append (value).Append (System.Environment.NewLine);
  409. }
  410. public StringBuilder AppendFormat (string format, params object[] args)
  411. {
  412. return AppendFormat (null, format, args);
  413. }
  414. public StringBuilder AppendFormat (IFormatProvider provider,
  415. string format,
  416. params object[] args)
  417. {
  418. String.FormatHelper (this, provider, format, args);
  419. return this;
  420. }
  421. #if MOONLIGHT
  422. internal
  423. #else
  424. public
  425. #endif
  426. StringBuilder AppendFormat (string format, object arg0)
  427. {
  428. return AppendFormat (null, format, new object [] { arg0 });
  429. }
  430. #if MOONLIGHT
  431. internal
  432. #else
  433. public
  434. #endif
  435. StringBuilder AppendFormat (string format, object arg0, object arg1)
  436. {
  437. return AppendFormat (null, format, new object [] { arg0, arg1 });
  438. }
  439. #if MOONLIGHT
  440. internal
  441. #else
  442. public
  443. #endif
  444. StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2)
  445. {
  446. return AppendFormat (null, format, new object [] { arg0, arg1, arg2 });
  447. }
  448. /* The Insert Functions */
  449. public StringBuilder Insert (int index, char[] value)
  450. {
  451. return Insert (index, new string (value));
  452. }
  453. public StringBuilder Insert (int index, string value)
  454. {
  455. if( index > _length || index < 0)
  456. throw new ArgumentOutOfRangeException();
  457. if (value == null || value.Length == 0)
  458. return this;
  459. InternalEnsureCapacity (_length + value.Length);
  460. // Move everything to the right of the insert point across
  461. String.CharCopyReverse (_str, index + value.Length, _str, index, _length - index);
  462. // Copy in stuff from the insert buffer
  463. String.CharCopy (_str, index, value, 0, value.Length);
  464. _length += value.Length;
  465. return this;
  466. }
  467. public StringBuilder Insert( int index, bool value ) {
  468. return Insert (index, value.ToString());
  469. }
  470. public StringBuilder Insert( int index, byte value ) {
  471. return Insert (index, value.ToString());
  472. }
  473. public StringBuilder Insert( int index, char value)
  474. {
  475. if (index > _length || index < 0)
  476. throw new ArgumentOutOfRangeException ("index");
  477. InternalEnsureCapacity (_length + 1);
  478. // Move everything to the right of the insert point across
  479. String.CharCopyReverse (_str, index + 1, _str, index, _length - index);
  480. _str.InternalSetChar (index, value);
  481. _length++;
  482. return this;
  483. }
  484. public StringBuilder Insert( int index, decimal value ) {
  485. return Insert (index, value.ToString());
  486. }
  487. public StringBuilder Insert( int index, double value ) {
  488. return Insert (index, value.ToString());
  489. }
  490. public StringBuilder Insert( int index, short value ) {
  491. return Insert (index, value.ToString());
  492. }
  493. public StringBuilder Insert( int index, int value ) {
  494. return Insert (index, value.ToString());
  495. }
  496. public StringBuilder Insert( int index, long value ) {
  497. return Insert (index, value.ToString());
  498. }
  499. public StringBuilder Insert( int index, object value ) {
  500. return Insert (index, value.ToString());
  501. }
  502. [CLSCompliant(false)]
  503. public StringBuilder Insert( int index, sbyte value ) {
  504. return Insert (index, value.ToString() );
  505. }
  506. public StringBuilder Insert (int index, float value) {
  507. return Insert (index, value.ToString() );
  508. }
  509. [CLSCompliant(false)]
  510. public StringBuilder Insert (int index, ushort value) {
  511. return Insert (index, value.ToString() );
  512. }
  513. [CLSCompliant(false)]
  514. public StringBuilder Insert (int index, uint value) {
  515. return Insert ( index, value.ToString() );
  516. }
  517. [CLSCompliant(false)]
  518. public StringBuilder Insert (int index, ulong value) {
  519. return Insert ( index, value.ToString() );
  520. }
  521. public StringBuilder Insert (int index, string value, int count)
  522. {
  523. // LAMESPEC: The spec says to throw an exception if
  524. // count < 0, while MS throws even for count < 1!
  525. if ( count < 0 )
  526. throw new ArgumentOutOfRangeException();
  527. if (value != null && value != String.Empty)
  528. for (int insertCount = 0; insertCount < count; insertCount++)
  529. Insert( index, value );
  530. return this;
  531. }
  532. public StringBuilder Insert (int index, char [] value, int startIndex, int charCount)
  533. {
  534. if (value == null) {
  535. if (startIndex == 0 && charCount == 0)
  536. return this;
  537. throw new ArgumentNullException ("value");
  538. }
  539. if (charCount < 0 || startIndex < 0 || startIndex > value.Length - charCount)
  540. throw new ArgumentOutOfRangeException ();
  541. return Insert (index, new String (value, startIndex, charCount));
  542. }
  543. private void InternalEnsureCapacity (int size)
  544. {
  545. if (size > _str.Length || (object) _cached_str == (object) _str) {
  546. int capacity = _str.Length;
  547. // Try double buffer, if that doesn't work, set the length as capacity
  548. if (size > capacity) {
  549. // The first time a string is appended, we just set _cached_str
  550. // and _str to it. This allows us to do some optimizations.
  551. // Below, we take this into account.
  552. if ((object) _cached_str == (object) _str && capacity < constDefaultCapacity)
  553. capacity = constDefaultCapacity;
  554. capacity = capacity << 1;
  555. if (size > capacity)
  556. capacity = size;
  557. if (capacity >= Int32.MaxValue || capacity < 0)
  558. capacity = Int32.MaxValue;
  559. if (capacity > _maxCapacity && size <= _maxCapacity)
  560. capacity = _maxCapacity;
  561. if (capacity > _maxCapacity)
  562. throw new ArgumentOutOfRangeException ("size", "capacity was less than the current size.");
  563. }
  564. string tmp = String.InternalAllocateStr (capacity);
  565. if (_length > 0)
  566. String.CharCopy (tmp, 0, _str, 0, _length);
  567. _str = tmp;
  568. }
  569. _cached_str = null;
  570. }
  571. [ComVisible (false)]
  572. public void CopyTo (int sourceIndex, char [] destination, int destinationIndex, int count)
  573. {
  574. if (destination == null)
  575. throw new ArgumentNullException ("destination");
  576. if ((Length - count < sourceIndex) ||
  577. (destination.Length -count < destinationIndex) ||
  578. (sourceIndex < 0 || destinationIndex < 0 || count < 0))
  579. throw new ArgumentOutOfRangeException ();
  580. for (int i = 0; i < count; i++)
  581. destination [destinationIndex+i] = _str [sourceIndex+i];
  582. }
  583. void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
  584. {
  585. info.AddValue ("m_MaxCapacity", _maxCapacity);
  586. info.AddValue ("Capacity", Capacity);
  587. info.AddValue ("m_StringValue", ToString ());
  588. info.AddValue ("m_currentThread", 0);
  589. }
  590. StringBuilder (SerializationInfo info, StreamingContext context)
  591. {
  592. string s = info.GetString ("m_StringValue");
  593. if (s == null)
  594. s = "";
  595. _length = s.Length;
  596. _str = _cached_str = s;
  597. _maxCapacity = info.GetInt32 ("m_MaxCapacity");
  598. if (_maxCapacity < 0)
  599. _maxCapacity = Int32.MaxValue;
  600. Capacity = info.GetInt32 ("Capacity");
  601. }
  602. }
  603. }