2 // System.IO.StreamWriter.cs
\r
5 // Dietmar Maurer (dietmar@ximian.com)
\r
6 // Paolo Molaro (lupus@ximian.com)
\r
7 // Marek Safar (marek.safar@gmail.com)
\r
9 // (C) Ximian, Inc. http://www.ximian.com
\r
10 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
\r
11 // Copyright 2011, 2013 Xamarin Inc.
\r
13 // Permission is hereby granted, free of charge, to any person obtaining
\r
14 // a copy of this software and associated documentation files (the
\r
15 // "Software"), to deal in the Software without restriction, including
\r
16 // without limitation the rights to use, copy, modify, merge, publish,
\r
17 // distribute, sublicense, and/or sell copies of the Software, and to
\r
18 // permit persons to whom the Software is furnished to do so, subject to
\r
19 // the following conditions:
\r
21 // The above copyright notice and this permission notice shall be
\r
22 // included in all copies or substantial portions of the Software.
\r
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
\r
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
\r
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
\r
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
\r
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
\r
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
\r
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\r
34 using System.Runtime.InteropServices;
\r
35 using System.Threading.Tasks;
\r
37 namespace System.IO {
\r
41 public class StreamWriter : TextWriter {
\r
43 private Encoding internalEncoding;
\r
45 private Stream internalStream;
\r
47 private const int DefaultBufferSize = 1024;
\r
48 private const int DefaultFileBufferSize = 4096;
\r
49 private const int MinimumBufferSize = 256;
\r
51 private byte[] byte_buf;
\r
52 private char[] decode_buf;
\r
53 private int byte_pos;
\r
54 private int decode_pos;
\r
56 private bool iflush;
\r
57 private bool preamble_done;
\r
59 readonly bool leave_open;
\r
60 IDecoupledTask async_task;
\r
62 public new static readonly StreamWriter Null = new StreamWriter (Stream.Null, EncodingHelper.UTF8Unmarked, 1);
\r
64 public StreamWriter (Stream stream)
\r
65 : this (stream, EncodingHelper.UTF8Unmarked, DefaultBufferSize) {}
\r
67 public StreamWriter (Stream stream, Encoding encoding)
\r
68 : this (stream, encoding, DefaultBufferSize) {}
\r
70 internal void Initialize(Encoding encoding, int bufferSize) {
\r
71 internalEncoding = encoding;
\r
72 decode_pos = byte_pos = 0;
\r
73 int BufferSize = Math.Max(bufferSize, MinimumBufferSize);
\r
74 decode_buf = new char [BufferSize];
\r
75 byte_buf = new byte [encoding.GetMaxByteCount (BufferSize)];
\r
77 // Fixes bug http://bugzilla.ximian.com/show_bug.cgi?id=74513
\r
78 if (internalStream.CanSeek && internalStream.Position > 0)
\r
79 preamble_done = true;
\r
82 public StreamWriter (Stream stream, Encoding encoding, int bufferSize)
\r
83 : this (stream, encoding, bufferSize, false)
\r
87 public StreamWriter (Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
\r
90 throw new ArgumentNullException("stream");
\r
91 if (null == encoding)
\r
92 throw new ArgumentNullException("encoding");
\r
93 if (bufferSize <= 0)
\r
94 throw new ArgumentOutOfRangeException("bufferSize");
\r
95 if (!stream.CanWrite)
\r
96 throw new ArgumentException ("Can not write to stream");
\r
98 leave_open = leaveOpen;
\r
99 internalStream = stream;
\r
101 Initialize(encoding, bufferSize);
\r
104 public StreamWriter (string path)
\r
105 : this (path, false, EncodingHelper.UTF8Unmarked, DefaultFileBufferSize) {}
\r
107 public StreamWriter (string path, bool append)
\r
108 : this (path, append, EncodingHelper.UTF8Unmarked, DefaultFileBufferSize) {}
\r
110 public StreamWriter (string path, bool append, Encoding encoding)
\r
111 : this (path, append, encoding, DefaultFileBufferSize) {}
\r
113 public StreamWriter (string path, bool append, Encoding encoding, int bufferSize)
\r
115 if (null == encoding)
\r
116 throw new ArgumentNullException("encoding");
\r
117 if (bufferSize <= 0)
\r
118 throw new ArgumentOutOfRangeException("bufferSize");
\r
123 mode = FileMode.Append;
\r
125 mode = FileMode.Create;
\r
127 internalStream = new FileStream (path, mode, FileAccess.Write, FileShare.Read);
\r
130 internalStream.Position = internalStream.Length;
\r
132 internalStream.SetLength (0);
\r
134 Initialize(encoding, bufferSize);
\r
137 public virtual bool AutoFlush {
\r
148 public virtual Stream BaseStream {
\r
150 return internalStream;
\r
154 public override Encoding Encoding {
\r
156 return internalEncoding;
\r
160 protected override void Dispose (bool disposing)
\r
162 if (byte_buf == null || !disposing)
\r
169 internalEncoding = null;
\r
173 internalStream.Close ();
\r
176 internalStream = null;
\r
180 public override void Flush ()
\r
186 // Keep in sync with FlushCoreAsync
\r
190 if (byte_pos > 0) {
\r
192 internalStream.Flush ();
\r
196 // how the speedup works:
\r
197 // the Write () methods simply copy the characters in a buffer of chars (decode_buf)
\r
198 // Decode () is called when the buffer is full or we need to flash.
\r
199 // Decode () will use the encoding to get the bytes and but them inside
\r
200 // byte_buf. From byte_buf the data is finally outputted to the stream.
\r
201 void FlushBytes ()
\r
203 // write the encoding preamble only at the start of the stream
\r
204 if (!preamble_done && byte_pos > 0) {
\r
205 byte[] preamble = internalEncoding.GetPreamble ();
\r
206 if (preamble.Length > 0)
\r
207 internalStream.Write (preamble, 0, preamble.Length);
\r
208 preamble_done = true;
\r
210 internalStream.Write (byte_buf, 0, byte_pos);
\r
218 if (decode_pos > 0) {
\r
219 int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);
\r
225 void LowLevelWrite (char[] buffer, int index, int count)
\r
227 while (count > 0) {
\r
228 int todo = decode_buf.Length - decode_pos;
\r
231 todo = decode_buf.Length;
\r
235 Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);
\r
238 decode_pos += todo;
\r
242 void LowLevelWrite (string s)
\r
244 int count = s.Length;
\r
246 while (count > 0) {
\r
247 int todo = decode_buf.Length - decode_pos;
\r
250 todo = decode_buf.Length;
\r
255 for (int i = 0; i < todo; i ++)
\r
256 decode_buf [i + decode_pos] = s [i + index];
\r
260 decode_pos += todo;
\r
264 async Task FlushCoreAsync ()
\r
266 await DecodeAsync ().ConfigureAwait (false);
\r
267 if (byte_pos > 0) {
\r
268 await FlushBytesAsync ().ConfigureAwait (false);
\r
269 await internalStream.FlushAsync ().ConfigureAwait (false);
\r
273 async Task FlushBytesAsync ()
\r
275 // write the encoding preamble only at the start of the stream
\r
276 if (!preamble_done && byte_pos > 0) {
\r
277 byte[] preamble = internalEncoding.GetPreamble ();
\r
278 if (preamble.Length > 0)
\r
279 await internalStream.WriteAsync (preamble, 0, preamble.Length).ConfigureAwait (false);
\r
280 preamble_done = true;
\r
283 await internalStream.WriteAsync (byte_buf, 0, byte_pos).ConfigureAwait (false);
\r
287 async Task DecodeAsync ()
\r
290 await FlushBytesAsync ().ConfigureAwait (false);
\r
291 if (decode_pos > 0) {
\r
292 int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);
\r
298 async Task LowLevelWriteAsync (char[] buffer, int index, int count)
\r
300 while (count > 0) {
\r
301 int todo = decode_buf.Length - decode_pos;
\r
303 await DecodeAsync ().ConfigureAwait (false);
\r
304 todo = decode_buf.Length;
\r
308 Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);
\r
311 decode_pos += todo;
\r
315 async Task LowLevelWriteAsync (string s)
\r
317 int count = s.Length;
\r
319 while (count > 0) {
\r
320 int todo = decode_buf.Length - decode_pos;
\r
322 await DecodeAsync ().ConfigureAwait (false);
\r
323 todo = decode_buf.Length;
\r
328 for (int i = 0; i < todo; i ++)
\r
329 decode_buf [i + decode_pos] = s [i + index];
\r
333 decode_pos += todo;
\r
337 public override void Write (char[] buffer, int index, int count)
\r
339 if (buffer == null)
\r
340 throw new ArgumentNullException ("buffer");
\r
342 throw new ArgumentOutOfRangeException ("index", "< 0");
\r
344 throw new ArgumentOutOfRangeException ("count", "< 0");
\r
345 // re-ordered to avoid possible integer overflow
\r
346 if (index > buffer.Length - count)
\r
347 throw new ArgumentException ("index + count > buffer.Length");
\r
351 LowLevelWrite (buffer, index, count);
\r
356 public override void Write (char value)
\r
360 // the size of decode_buf is always > 0 and
\r
361 // we check for overflow right away
\r
362 if (decode_pos >= decode_buf.Length)
\r
364 decode_buf [decode_pos++] = value;
\r
369 public override void Write (char[] buffer)
\r
373 if (buffer != null)
\r
374 LowLevelWrite (buffer, 0, buffer.Length);
\r
379 public override void Write (string value)
\r
386 LowLevelWrite (value);
\r
392 public override void Close()
\r
399 if (byte_buf == null)
\r
400 throw new ObjectDisposedException ("StreamWriter");
\r
402 if (async_task != null && !async_task.IsCompleted)
\r
403 throw new InvalidOperationException ();
\r
406 public override Task FlushAsync ()
\r
410 async_task = res = new DecoupledTask (FlushCoreAsync ());
\r
414 public override Task WriteAsync (char value)
\r
419 async_task = res = new DecoupledTask (WriteAsyncCore (value));
\r
423 async Task WriteAsyncCore (char value)
\r
425 // the size of decode_buf is always > 0 and
\r
426 // we check for overflow right away
\r
427 if (decode_pos >= decode_buf.Length)
\r
428 await DecodeAsync ().ConfigureAwait (false);
\r
429 decode_buf [decode_pos++] = value;
\r
432 await FlushCoreAsync ().ConfigureAwait (false);
\r
435 public override Task WriteAsync (char[] buffer, int index, int count)
\r
438 if (buffer == null)
\r
439 return TaskConstants.Finished;
\r
442 async_task = res = new DecoupledTask (WriteAsyncCore (buffer, index, count));
\r
446 async Task WriteAsyncCore (char[] buffer, int index, int count)
\r
448 // Debug.Assert (buffer == null);
\r
450 await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false);
\r
453 await FlushCoreAsync ().ConfigureAwait (false);
\r
456 public override Task WriteAsync (string value)
\r
461 return TaskConstants.Finished;
\r
463 DecoupledTask res;
\r
464 async_task = res = new DecoupledTask (WriteAsyncCore (value, false));
\r
468 async Task WriteAsyncCore (string value, bool appendNewLine)
\r
470 // Debug.Assert (value == null);
\r
472 await LowLevelWriteAsync (value).ConfigureAwait (false);
\r
474 await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);
\r
477 await FlushCoreAsync ().ConfigureAwait (false);
\r
480 public override Task WriteLineAsync ()
\r
485 async_task = res = new DecoupledTask (WriteAsyncCore (CoreNewLine, 0, CoreNewLine.Length));
\r
489 public override Task WriteLineAsync (char value)
\r
493 async_task = res = new DecoupledTask (WriteLineAsyncCore (value));
\r
497 async Task WriteLineAsyncCore (char value)
\r
499 await WriteAsyncCore (value).ConfigureAwait (false);
\r
500 await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);
\r
503 await FlushCoreAsync ().ConfigureAwait (false);
\r
506 public override Task WriteLineAsync (char[] buffer, int index, int count)
\r
508 if (buffer == null)
\r
509 throw new ArgumentNullException ("buffer");
\r
511 throw new ArgumentOutOfRangeException ("index", "< 0");
\r
513 throw new ArgumentOutOfRangeException ("count", "< 0");
\r
514 // re-ordered to avoid possible integer overflow
\r
515 if (index > buffer.Length - count)
\r
516 throw new ArgumentException ("index + count > buffer.Length");
\r
520 async_task = res = new DecoupledTask (WriteLineAsyncCore (buffer, index, count));
\r
524 async Task WriteLineAsyncCore (char[] buffer, int index, int count)
\r
526 // Debug.Assert (buffer == null);
\r
528 await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false);
\r
529 await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);
\r
532 await FlushCoreAsync ().ConfigureAwait (false);
\r
535 public override Task WriteLineAsync (string value)
\r
538 return WriteLineAsync ();
\r
541 DecoupledTask res;
\r
542 async_task = res = new DecoupledTask (WriteAsyncCore (value, true));
\r