StreamWriter.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. using System.Threading.Tasks;
  35. namespace System.IO {
  36. [Serializable]
  37. [ComVisible (true)]
  38. public class StreamWriter : TextWriter {
  39. private Encoding internalEncoding;
  40. private Stream internalStream;
  41. private const int DefaultBufferSize = 1024;
  42. private const int DefaultFileBufferSize = 4096;
  43. private const int MinimumBufferSize = 256;
  44. private byte[] byte_buf;
  45. private char[] decode_buf;
  46. private int byte_pos;
  47. private int decode_pos;
  48. private bool iflush;
  49. private bool preamble_done;
  50. readonly bool leave_open;
  51. IDecoupledTask async_task;
  52. public new static readonly StreamWriter Null = new StreamWriter (Stream.Null, EncodingHelper.UTF8Unmarked, 1);
  53. public StreamWriter (Stream stream)
  54. : this (stream, EncodingHelper.UTF8Unmarked, DefaultBufferSize) {}
  55. public StreamWriter (Stream stream, Encoding encoding)
  56. : this (stream, encoding, DefaultBufferSize) {}
  57. internal void Initialize(Encoding encoding, int bufferSize) {
  58. internalEncoding = encoding;
  59. decode_pos = byte_pos = 0;
  60. int BufferSize = Math.Max(bufferSize, MinimumBufferSize);
  61. decode_buf = new char [BufferSize];
  62. byte_buf = new byte [encoding.GetMaxByteCount (BufferSize)];
  63. // Fixes bug http://bugzilla.ximian.com/show_bug.cgi?id=74513
  64. if (internalStream.CanSeek && internalStream.Position > 0)
  65. preamble_done = true;
  66. }
  67. public StreamWriter (Stream stream, Encoding encoding, int bufferSize)
  68. : this (stream, encoding, bufferSize, false)
  69. {
  70. }
  71. public StreamWriter (Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
  72. {
  73. if (null == stream)
  74. throw new ArgumentNullException("stream");
  75. if (null == encoding)
  76. throw new ArgumentNullException("encoding");
  77. if (bufferSize <= 0)
  78. throw new ArgumentOutOfRangeException("bufferSize");
  79. if (!stream.CanWrite)
  80. throw new ArgumentException ("Can not write to stream");
  81. leave_open = leaveOpen;
  82. internalStream = stream;
  83. Initialize(encoding, bufferSize);
  84. }
  85. public StreamWriter (string path)
  86. : this (path, false, EncodingHelper.UTF8Unmarked, DefaultFileBufferSize) {}
  87. public StreamWriter (string path, bool append)
  88. : this (path, append, EncodingHelper.UTF8Unmarked, DefaultFileBufferSize) {}
  89. public StreamWriter (string path, bool append, Encoding encoding)
  90. : this (path, append, encoding, DefaultFileBufferSize) {}
  91. public StreamWriter (string path, bool append, Encoding encoding, int bufferSize)
  92. {
  93. if (null == encoding)
  94. throw new ArgumentNullException("encoding");
  95. if (bufferSize <= 0)
  96. throw new ArgumentOutOfRangeException("bufferSize");
  97. FileMode mode;
  98. if (append)
  99. mode = FileMode.Append;
  100. else
  101. mode = FileMode.Create;
  102. internalStream = new FileStream (path, mode, FileAccess.Write, FileShare.Read);
  103. if (append)
  104. internalStream.Position = internalStream.Length;
  105. else
  106. internalStream.SetLength (0);
  107. Initialize(encoding, bufferSize);
  108. }
  109. public virtual bool AutoFlush {
  110. get {
  111. return iflush;
  112. }
  113. set {
  114. iflush = value;
  115. if (iflush)
  116. Flush ();
  117. }
  118. }
  119. public virtual Stream BaseStream {
  120. get {
  121. return internalStream;
  122. }
  123. }
  124. public override Encoding Encoding {
  125. get {
  126. return internalEncoding;
  127. }
  128. }
  129. protected override void Dispose (bool disposing)
  130. {
  131. if (byte_buf == null || !disposing)
  132. return;
  133. try {
  134. Flush ();
  135. } finally {
  136. byte_buf = null;
  137. internalEncoding = null;
  138. decode_buf = null;
  139. if (!leave_open) {
  140. internalStream.Close ();
  141. }
  142. internalStream = null;
  143. }
  144. }
  145. public override void Flush ()
  146. {
  147. CheckState ();
  148. FlushCore ();
  149. }
  150. // Keep in sync with FlushCoreAsync
  151. void FlushCore ()
  152. {
  153. Decode ();
  154. if (byte_pos > 0) {
  155. FlushBytes ();
  156. internalStream.Flush ();
  157. }
  158. }
  159. // how the speedup works:
  160. // the Write () methods simply copy the characters in a buffer of chars (decode_buf)
  161. // Decode () is called when the buffer is full or we need to flash.
  162. // Decode () will use the encoding to get the bytes and but them inside
  163. // byte_buf. From byte_buf the data is finally outputted to the stream.
  164. void FlushBytes ()
  165. {
  166. // write the encoding preamble only at the start of the stream
  167. if (!preamble_done && byte_pos > 0) {
  168. byte[] preamble = internalEncoding.GetPreamble ();
  169. if (preamble.Length > 0)
  170. internalStream.Write (preamble, 0, preamble.Length);
  171. preamble_done = true;
  172. }
  173. internalStream.Write (byte_buf, 0, byte_pos);
  174. byte_pos = 0;
  175. }
  176. void Decode ()
  177. {
  178. if (byte_pos > 0)
  179. FlushBytes ();
  180. if (decode_pos > 0) {
  181. int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);
  182. byte_pos += len;
  183. decode_pos = 0;
  184. }
  185. }
  186. void LowLevelWrite (char[] buffer, int index, int count)
  187. {
  188. while (count > 0) {
  189. int todo = decode_buf.Length - decode_pos;
  190. if (todo == 0) {
  191. Decode ();
  192. todo = decode_buf.Length;
  193. }
  194. if (todo > count)
  195. todo = count;
  196. Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);
  197. count -= todo;
  198. index += todo;
  199. decode_pos += todo;
  200. }
  201. }
  202. void LowLevelWrite (string s)
  203. {
  204. int count = s.Length;
  205. int index = 0;
  206. while (count > 0) {
  207. int todo = decode_buf.Length - decode_pos;
  208. if (todo == 0) {
  209. Decode ();
  210. todo = decode_buf.Length;
  211. }
  212. if (todo > count)
  213. todo = count;
  214. for (int i = 0; i < todo; i ++)
  215. decode_buf [i + decode_pos] = s [i + index];
  216. count -= todo;
  217. index += todo;
  218. decode_pos += todo;
  219. }
  220. }
  221. async Task FlushCoreAsync ()
  222. {
  223. await DecodeAsync ().ConfigureAwait (false);
  224. if (byte_pos > 0) {
  225. await FlushBytesAsync ().ConfigureAwait (false);
  226. await internalStream.FlushAsync ().ConfigureAwait (false);
  227. }
  228. }
  229. async Task FlushBytesAsync ()
  230. {
  231. // write the encoding preamble only at the start of the stream
  232. if (!preamble_done && byte_pos > 0) {
  233. byte[] preamble = internalEncoding.GetPreamble ();
  234. if (preamble.Length > 0)
  235. await internalStream.WriteAsync (preamble, 0, preamble.Length).ConfigureAwait (false);
  236. preamble_done = true;
  237. }
  238. await internalStream.WriteAsync (byte_buf, 0, byte_pos).ConfigureAwait (false);
  239. byte_pos = 0;
  240. }
  241. async Task DecodeAsync ()
  242. {
  243. if (byte_pos > 0)
  244. await FlushBytesAsync ().ConfigureAwait (false);
  245. if (decode_pos > 0) {
  246. int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);
  247. byte_pos += len;
  248. decode_pos = 0;
  249. }
  250. }
  251. async Task LowLevelWriteAsync (char[] buffer, int index, int count)
  252. {
  253. while (count > 0) {
  254. int todo = decode_buf.Length - decode_pos;
  255. if (todo == 0) {
  256. await DecodeAsync ().ConfigureAwait (false);
  257. todo = decode_buf.Length;
  258. }
  259. if (todo > count)
  260. todo = count;
  261. Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);
  262. count -= todo;
  263. index += todo;
  264. decode_pos += todo;
  265. }
  266. }
  267. async Task LowLevelWriteAsync (string s)
  268. {
  269. int count = s.Length;
  270. int index = 0;
  271. while (count > 0) {
  272. int todo = decode_buf.Length - decode_pos;
  273. if (todo == 0) {
  274. await DecodeAsync ().ConfigureAwait (false);
  275. todo = decode_buf.Length;
  276. }
  277. if (todo > count)
  278. todo = count;
  279. for (int i = 0; i < todo; i ++)
  280. decode_buf [i + decode_pos] = s [i + index];
  281. count -= todo;
  282. index += todo;
  283. decode_pos += todo;
  284. }
  285. }
  286. public override void Write (char[] buffer, int index, int count)
  287. {
  288. if (buffer == null)
  289. throw new ArgumentNullException ("buffer");
  290. if (index < 0)
  291. throw new ArgumentOutOfRangeException ("index", "< 0");
  292. if (count < 0)
  293. throw new ArgumentOutOfRangeException ("count", "< 0");
  294. // re-ordered to avoid possible integer overflow
  295. if (index > buffer.Length - count)
  296. throw new ArgumentException ("index + count > buffer.Length");
  297. CheckState ();
  298. LowLevelWrite (buffer, index, count);
  299. if (iflush)
  300. FlushCore ();
  301. }
  302. public override void Write (char value)
  303. {
  304. CheckState ();
  305. // the size of decode_buf is always > 0 and
  306. // we check for overflow right away
  307. if (decode_pos >= decode_buf.Length)
  308. Decode ();
  309. decode_buf [decode_pos++] = value;
  310. if (iflush)
  311. FlushCore ();
  312. }
  313. public override void Write (char[] buffer)
  314. {
  315. CheckState ();
  316. if (buffer != null)
  317. LowLevelWrite (buffer, 0, buffer.Length);
  318. if (iflush)
  319. FlushCore ();
  320. }
  321. public override void Write (string value)
  322. {
  323. CheckState ();
  324. if (value == null)
  325. return;
  326. LowLevelWrite (value);
  327. if (iflush)
  328. FlushCore ();
  329. }
  330. public override void Close()
  331. {
  332. Dispose (true);
  333. }
  334. void CheckState ()
  335. {
  336. if (byte_buf == null)
  337. throw new ObjectDisposedException ("StreamWriter");
  338. if (async_task != null && !async_task.IsCompleted)
  339. throw new InvalidOperationException ();
  340. }
  341. public override Task FlushAsync ()
  342. {
  343. CheckState ();
  344. DecoupledTask res;
  345. async_task = res = new DecoupledTask (FlushCoreAsync ());
  346. return res.Task;
  347. }
  348. public override Task WriteAsync (char value)
  349. {
  350. CheckState ();
  351. DecoupledTask res;
  352. async_task = res = new DecoupledTask (WriteAsyncCore (value));
  353. return res.Task;
  354. }
  355. async Task WriteAsyncCore (char value)
  356. {
  357. // the size of decode_buf is always > 0 and
  358. // we check for overflow right away
  359. if (decode_pos >= decode_buf.Length)
  360. await DecodeAsync ().ConfigureAwait (false);
  361. decode_buf [decode_pos++] = value;
  362. if (iflush)
  363. await FlushCoreAsync ().ConfigureAwait (false);
  364. }
  365. public override Task WriteAsync (char[] buffer, int index, int count)
  366. {
  367. CheckState ();
  368. if (buffer == null)
  369. return TaskConstants.Finished;
  370. DecoupledTask res;
  371. async_task = res = new DecoupledTask (WriteAsyncCore (buffer, index, count));
  372. return res.Task;
  373. }
  374. async Task WriteAsyncCore (char[] buffer, int index, int count)
  375. {
  376. // Debug.Assert (buffer == null);
  377. await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false);
  378. if (iflush)
  379. await FlushCoreAsync ().ConfigureAwait (false);
  380. }
  381. public override Task WriteAsync (string value)
  382. {
  383. CheckState ();
  384. if (value == null)
  385. return TaskConstants.Finished;
  386. DecoupledTask res;
  387. async_task = res = new DecoupledTask (WriteAsyncCore (value, false));
  388. return res.Task;
  389. }
  390. async Task WriteAsyncCore (string value, bool appendNewLine)
  391. {
  392. // Debug.Assert (value == null);
  393. await LowLevelWriteAsync (value).ConfigureAwait (false);
  394. if (appendNewLine)
  395. await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);
  396. if (iflush)
  397. await FlushCoreAsync ().ConfigureAwait (false);
  398. }
  399. public override Task WriteLineAsync ()
  400. {
  401. CheckState ();
  402. DecoupledTask res;
  403. async_task = res = new DecoupledTask (WriteAsyncCore (CoreNewLine, 0, CoreNewLine.Length));
  404. return res.Task;
  405. }
  406. public override Task WriteLineAsync (char value)
  407. {
  408. CheckState ();
  409. DecoupledTask res;
  410. async_task = res = new DecoupledTask (WriteLineAsyncCore (value));
  411. return res.Task;
  412. }
  413. async Task WriteLineAsyncCore (char value)
  414. {
  415. await WriteAsyncCore (value).ConfigureAwait (false);
  416. await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);
  417. if (iflush)
  418. await FlushCoreAsync ().ConfigureAwait (false);
  419. }
  420. public override Task WriteLineAsync (char[] buffer, int index, int count)
  421. {
  422. if (buffer == null)
  423. throw new ArgumentNullException ("buffer");
  424. if (index < 0)
  425. throw new ArgumentOutOfRangeException ("index", "< 0");
  426. if (count < 0)
  427. throw new ArgumentOutOfRangeException ("count", "< 0");
  428. // re-ordered to avoid possible integer overflow
  429. if (index > buffer.Length - count)
  430. throw new ArgumentException ("index + count > buffer.Length");
  431. CheckState ();
  432. DecoupledTask res;
  433. async_task = res = new DecoupledTask (WriteLineAsyncCore (buffer, index, count));
  434. return res.Task;
  435. }
  436. async Task WriteLineAsyncCore (char[] buffer, int index, int count)
  437. {
  438. // Debug.Assert (buffer == null);
  439. await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false);
  440. await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);
  441. if (iflush)
  442. await FlushCoreAsync ().ConfigureAwait (false);
  443. }
  444. public override Task WriteLineAsync (string value)
  445. {
  446. if (value == null)
  447. return WriteLineAsync ();
  448. CheckState ();
  449. DecoupledTask res;
  450. async_task = res = new DecoupledTask (WriteAsyncCore (value, true));
  451. return res.Task;
  452. }
  453. }
  454. }