StreamWriter.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. //
  2. // System.IO.StreamWriter.cs
  3. //
  4. // Authors:
  5. // Dietmar Maurer ([email protected])
  6. // Paolo Molaro ([email protected])
  7. // Marek Safar ([email protected])
  8. //
  9. // (C) Ximian, Inc. http://www.ximian.com
  10. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  11. // Copyright 2011, 2013 Xamarin Inc.
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System.Text;
  33. using System.Runtime.InteropServices;
  34. #if NET_4_5
  35. using System.Threading.Tasks;
  36. #endif
  37. namespace System.IO {
  38. [Serializable]
  39. [ComVisible (true)]
  40. public class StreamWriter : TextWriter {
  41. private Encoding internalEncoding;
  42. private Stream internalStream;
  43. private const int DefaultBufferSize = 1024;
  44. private const int DefaultFileBufferSize = 4096;
  45. private const int MinimumBufferSize = 256;
  46. private byte[] byte_buf;
  47. private char[] decode_buf;
  48. private int byte_pos;
  49. private int decode_pos;
  50. private bool iflush;
  51. private bool preamble_done;
  52. #if NET_4_5
  53. readonly bool leave_open;
  54. IDecoupledTask async_task;
  55. #endif
  56. public new static readonly StreamWriter Null = new StreamWriter (Stream.Null, Encoding.UTF8Unmarked, 1);
  57. public StreamWriter (Stream stream)
  58. : this (stream, Encoding.UTF8Unmarked, DefaultBufferSize) {}
  59. public StreamWriter (Stream stream, Encoding encoding)
  60. : this (stream, encoding, DefaultBufferSize) {}
  61. internal void Initialize(Encoding encoding, int bufferSize) {
  62. internalEncoding = encoding;
  63. decode_pos = byte_pos = 0;
  64. int BufferSize = Math.Max(bufferSize, MinimumBufferSize);
  65. decode_buf = new char [BufferSize];
  66. byte_buf = new byte [encoding.GetMaxByteCount (BufferSize)];
  67. // Fixes bug http://bugzilla.ximian.com/show_bug.cgi?id=74513
  68. if (internalStream.CanSeek && internalStream.Position > 0)
  69. preamble_done = true;
  70. }
  71. #if NET_4_5
  72. public StreamWriter (Stream stream, Encoding encoding, int bufferSize)
  73. : this (stream, encoding, bufferSize, false)
  74. {
  75. }
  76. public StreamWriter (Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
  77. #else
  78. const bool leave_open = false;
  79. public StreamWriter (Stream stream, Encoding encoding, int bufferSize)
  80. #endif
  81. {
  82. if (null == stream)
  83. throw new ArgumentNullException("stream");
  84. if (null == encoding)
  85. throw new ArgumentNullException("encoding");
  86. if (bufferSize <= 0)
  87. throw new ArgumentOutOfRangeException("bufferSize");
  88. if (!stream.CanWrite)
  89. throw new ArgumentException ("Can not write to stream");
  90. #if NET_4_5
  91. leave_open = leaveOpen;
  92. #endif
  93. internalStream = stream;
  94. Initialize(encoding, bufferSize);
  95. }
  96. public StreamWriter (string path)
  97. : this (path, false, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}
  98. public StreamWriter (string path, bool append)
  99. : this (path, append, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}
  100. public StreamWriter (string path, bool append, Encoding encoding)
  101. : this (path, append, encoding, DefaultFileBufferSize) {}
  102. public StreamWriter (string path, bool append, Encoding encoding, int bufferSize)
  103. {
  104. if (null == encoding)
  105. throw new ArgumentNullException("encoding");
  106. if (bufferSize <= 0)
  107. throw new ArgumentOutOfRangeException("bufferSize");
  108. FileMode mode;
  109. if (append)
  110. mode = FileMode.Append;
  111. else
  112. mode = FileMode.Create;
  113. internalStream = new FileStream (path, mode, FileAccess.Write, FileShare.Read);
  114. if (append)
  115. internalStream.Position = internalStream.Length;
  116. else
  117. internalStream.SetLength (0);
  118. Initialize(encoding, bufferSize);
  119. }
  120. public virtual bool AutoFlush {
  121. get {
  122. return iflush;
  123. }
  124. set {
  125. iflush = value;
  126. if (iflush)
  127. Flush ();
  128. }
  129. }
  130. public virtual Stream BaseStream {
  131. get {
  132. return internalStream;
  133. }
  134. }
  135. public override Encoding Encoding {
  136. get {
  137. return internalEncoding;
  138. }
  139. }
  140. protected override void Dispose (bool disposing)
  141. {
  142. if (byte_buf == null || !disposing)
  143. return;
  144. try {
  145. Flush ();
  146. } finally {
  147. byte_buf = null;
  148. internalEncoding = null;
  149. decode_buf = null;
  150. if (!leave_open) {
  151. internalStream.Close ();
  152. }
  153. internalStream = null;
  154. }
  155. }
  156. public override void Flush ()
  157. {
  158. CheckState ();
  159. FlushCore ();
  160. }
  161. // Keep in sync with FlushCoreAsync
  162. void FlushCore ()
  163. {
  164. Decode ();
  165. if (byte_pos > 0) {
  166. FlushBytes ();
  167. internalStream.Flush ();
  168. }
  169. }
  170. // how the speedup works:
  171. // the Write () methods simply copy the characters in a buffer of chars (decode_buf)
  172. // Decode () is called when the buffer is full or we need to flash.
  173. // Decode () will use the encoding to get the bytes and but them inside
  174. // byte_buf. From byte_buf the data is finally outputted to the stream.
  175. void FlushBytes ()
  176. {
  177. // write the encoding preamble only at the start of the stream
  178. if (!preamble_done && byte_pos > 0) {
  179. byte[] preamble = internalEncoding.GetPreamble ();
  180. if (preamble.Length > 0)
  181. internalStream.Write (preamble, 0, preamble.Length);
  182. preamble_done = true;
  183. }
  184. internalStream.Write (byte_buf, 0, byte_pos);
  185. byte_pos = 0;
  186. }
  187. void Decode ()
  188. {
  189. if (byte_pos > 0)
  190. FlushBytes ();
  191. if (decode_pos > 0) {
  192. int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);
  193. byte_pos += len;
  194. decode_pos = 0;
  195. }
  196. }
  197. void LowLevelWrite (char[] buffer, int index, int count)
  198. {
  199. while (count > 0) {
  200. int todo = decode_buf.Length - decode_pos;
  201. if (todo == 0) {
  202. Decode ();
  203. todo = decode_buf.Length;
  204. }
  205. if (todo > count)
  206. todo = count;
  207. Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);
  208. count -= todo;
  209. index += todo;
  210. decode_pos += todo;
  211. }
  212. }
  213. void LowLevelWrite (string s)
  214. {
  215. int count = s.Length;
  216. int index = 0;
  217. while (count > 0) {
  218. int todo = decode_buf.Length - decode_pos;
  219. if (todo == 0) {
  220. Decode ();
  221. todo = decode_buf.Length;
  222. }
  223. if (todo > count)
  224. todo = count;
  225. for (int i = 0; i < todo; i ++)
  226. decode_buf [i + decode_pos] = s [i + index];
  227. count -= todo;
  228. index += todo;
  229. decode_pos += todo;
  230. }
  231. }
  232. #if NET_4_5
  233. async Task FlushCoreAsync ()
  234. {
  235. await DecodeAsync ().ConfigureAwait (false);
  236. if (byte_pos > 0) {
  237. await FlushBytesAsync ().ConfigureAwait (false);
  238. await internalStream.FlushAsync ().ConfigureAwait (false);
  239. }
  240. }
  241. async Task FlushBytesAsync ()
  242. {
  243. // write the encoding preamble only at the start of the stream
  244. if (!preamble_done && byte_pos > 0) {
  245. byte[] preamble = internalEncoding.GetPreamble ();
  246. if (preamble.Length > 0)
  247. await internalStream.WriteAsync (preamble, 0, preamble.Length).ConfigureAwait (false);
  248. preamble_done = true;
  249. }
  250. await internalStream.WriteAsync (byte_buf, 0, byte_pos).ConfigureAwait (false);
  251. byte_pos = 0;
  252. }
  253. async Task DecodeAsync ()
  254. {
  255. if (byte_pos > 0)
  256. await FlushBytesAsync ().ConfigureAwait (false);
  257. if (decode_pos > 0) {
  258. int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);
  259. byte_pos += len;
  260. decode_pos = 0;
  261. }
  262. }
  263. async Task LowLevelWriteAsync (char[] buffer, int index, int count)
  264. {
  265. while (count > 0) {
  266. int todo = decode_buf.Length - decode_pos;
  267. if (todo == 0) {
  268. await DecodeAsync ().ConfigureAwait (false);
  269. todo = decode_buf.Length;
  270. }
  271. if (todo > count)
  272. todo = count;
  273. Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);
  274. count -= todo;
  275. index += todo;
  276. decode_pos += todo;
  277. }
  278. }
  279. async Task LowLevelWriteAsync (string s)
  280. {
  281. int count = s.Length;
  282. int index = 0;
  283. while (count > 0) {
  284. int todo = decode_buf.Length - decode_pos;
  285. if (todo == 0) {
  286. await DecodeAsync ().ConfigureAwait (false);
  287. todo = decode_buf.Length;
  288. }
  289. if (todo > count)
  290. todo = count;
  291. for (int i = 0; i < todo; i ++)
  292. decode_buf [i + decode_pos] = s [i + index];
  293. count -= todo;
  294. index += todo;
  295. decode_pos += todo;
  296. }
  297. }
  298. #endif
  299. public override void Write (char[] buffer, int index, int count)
  300. {
  301. if (buffer == null)
  302. throw new ArgumentNullException ("buffer");
  303. if (index < 0)
  304. throw new ArgumentOutOfRangeException ("index", "< 0");
  305. if (count < 0)
  306. throw new ArgumentOutOfRangeException ("count", "< 0");
  307. // re-ordered to avoid possible integer overflow
  308. if (index > buffer.Length - count)
  309. throw new ArgumentException ("index + count > buffer.Length");
  310. CheckState ();
  311. LowLevelWrite (buffer, index, count);
  312. if (iflush)
  313. FlushCore ();
  314. }
  315. public override void Write (char value)
  316. {
  317. CheckState ();
  318. // the size of decode_buf is always > 0 and
  319. // we check for overflow right away
  320. if (decode_pos >= decode_buf.Length)
  321. Decode ();
  322. decode_buf [decode_pos++] = value;
  323. if (iflush)
  324. FlushCore ();
  325. }
  326. public override void Write (char[] buffer)
  327. {
  328. CheckState ();
  329. if (buffer != null)
  330. LowLevelWrite (buffer, 0, buffer.Length);
  331. if (iflush)
  332. FlushCore ();
  333. }
  334. public override void Write (string value)
  335. {
  336. CheckState ();
  337. if (value == null)
  338. return;
  339. LowLevelWrite (value);
  340. if (iflush)
  341. FlushCore ();
  342. }
  343. public override void Close()
  344. {
  345. Dispose (true);
  346. }
  347. void CheckState ()
  348. {
  349. if (byte_buf == null)
  350. throw new ObjectDisposedException ("StreamWriter");
  351. #if NET_4_5
  352. if (async_task != null && !async_task.IsCompleted)
  353. throw new InvalidOperationException ();
  354. #endif
  355. }
  356. #if NET_4_5
  357. public override Task FlushAsync ()
  358. {
  359. CheckState ();
  360. DecoupledTask res;
  361. async_task = res = new DecoupledTask (FlushCoreAsync ());
  362. return res.Task;
  363. }
  364. public override Task WriteAsync (char value)
  365. {
  366. CheckState ();
  367. DecoupledTask res;
  368. async_task = res = new DecoupledTask (WriteAsyncCore (value));
  369. return res.Task;
  370. }
  371. async Task WriteAsyncCore (char value)
  372. {
  373. // the size of decode_buf is always > 0 and
  374. // we check for overflow right away
  375. if (decode_pos >= decode_buf.Length)
  376. await DecodeAsync ().ConfigureAwait (false);
  377. decode_buf [decode_pos++] = value;
  378. if (iflush)
  379. await FlushCoreAsync ().ConfigureAwait (false);
  380. }
  381. public override Task WriteAsync (char[] buffer, int index, int count)
  382. {
  383. CheckState ();
  384. if (buffer == null)
  385. return TaskConstants.Finished;
  386. DecoupledTask res;
  387. async_task = res = new DecoupledTask (WriteAsyncCore (buffer, index, count));
  388. return res.Task;
  389. }
  390. async Task WriteAsyncCore (char[] buffer, int index, int count)
  391. {
  392. // Debug.Assert (buffer == null);
  393. await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false);
  394. if (iflush)
  395. await FlushCoreAsync ().ConfigureAwait (false);
  396. }
  397. public override Task WriteAsync (string value)
  398. {
  399. CheckState ();
  400. if (value == null)
  401. return TaskConstants.Finished;
  402. DecoupledTask res;
  403. async_task = res = new DecoupledTask (WriteAsyncCore (value, false));
  404. return res.Task;
  405. }
  406. async Task WriteAsyncCore (string value, bool appendNewLine)
  407. {
  408. // Debug.Assert (value == null);
  409. await LowLevelWriteAsync (value).ConfigureAwait (false);
  410. if (appendNewLine)
  411. await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);
  412. if (iflush)
  413. await FlushCoreAsync ().ConfigureAwait (false);
  414. }
  415. public override Task WriteLineAsync ()
  416. {
  417. CheckState ();
  418. DecoupledTask res;
  419. async_task = res = new DecoupledTask (WriteAsyncCore (CoreNewLine, 0, CoreNewLine.Length));
  420. return res.Task;
  421. }
  422. public override Task WriteLineAsync (char value)
  423. {
  424. CheckState ();
  425. DecoupledTask res;
  426. async_task = res = new DecoupledTask (WriteLineAsyncCore (value));
  427. return res.Task;
  428. }
  429. async Task WriteLineAsyncCore (char value)
  430. {
  431. await WriteAsyncCore (value).ConfigureAwait (false);
  432. await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);
  433. if (iflush)
  434. await FlushCoreAsync ().ConfigureAwait (false);
  435. }
  436. public override Task WriteLineAsync (char[] buffer, int index, int count)
  437. {
  438. if (buffer == null)
  439. throw new ArgumentNullException ("buffer");
  440. if (index < 0)
  441. throw new ArgumentOutOfRangeException ("index", "< 0");
  442. if (count < 0)
  443. throw new ArgumentOutOfRangeException ("count", "< 0");
  444. // re-ordered to avoid possible integer overflow
  445. if (index > buffer.Length - count)
  446. throw new ArgumentException ("index + count > buffer.Length");
  447. CheckState ();
  448. DecoupledTask res;
  449. async_task = res = new DecoupledTask (WriteLineAsyncCore (buffer, index, count));
  450. return res.Task;
  451. }
  452. async Task WriteLineAsyncCore (char[] buffer, int index, int count)
  453. {
  454. // Debug.Assert (buffer == null);
  455. await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false);
  456. await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);
  457. if (iflush)
  458. await FlushCoreAsync ().ConfigureAwait (false);
  459. }
  460. public override Task WriteLineAsync (string value)
  461. {
  462. if (value == null)
  463. return WriteLineAsync ();
  464. CheckState ();
  465. DecoupledTask res;
  466. async_task = res = new DecoupledTask (WriteAsyncCore (value, true));
  467. return res.Task;
  468. }
  469. #endif
  470. }
  471. }