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
36 using System.Threading.Tasks;
\r
39 namespace System.IO {
\r
43 public class StreamWriter : TextWriter {
\r
45 private Encoding internalEncoding;
\r
47 private Stream internalStream;
\r
49 private const int DefaultBufferSize = 1024;
\r
50 private const int DefaultFileBufferSize = 4096;
\r
51 private const int MinimumBufferSize = 256;
\r
53 private byte[] byte_buf;
\r
54 private char[] decode_buf;
\r
55 private int byte_pos;
\r
56 private int decode_pos;
\r
58 private bool iflush;
\r
59 private bool preamble_done;
\r
62 readonly bool leave_open;
\r
63 IDecoupledTask async_task;
\r
66 public new static readonly StreamWriter Null = new StreamWriter (Stream.Null, Encoding.UTF8Unmarked, 1);
\r
68 public StreamWriter (Stream stream)
\r
69 : this (stream, Encoding.UTF8Unmarked, DefaultBufferSize) {}
\r
71 public StreamWriter (Stream stream, Encoding encoding)
\r
72 : this (stream, encoding, DefaultBufferSize) {}
\r
74 internal void Initialize(Encoding encoding, int bufferSize) {
\r
75 internalEncoding = encoding;
\r
76 decode_pos = byte_pos = 0;
\r
77 int BufferSize = Math.Max(bufferSize, MinimumBufferSize);
\r
78 decode_buf = new char [BufferSize];
\r
79 byte_buf = new byte [encoding.GetMaxByteCount (BufferSize)];
\r
81 // Fixes bug http://bugzilla.ximian.com/show_bug.cgi?id=74513
\r
82 if (internalStream.CanSeek && internalStream.Position > 0)
\r
83 preamble_done = true;
\r
87 public StreamWriter (Stream stream, Encoding encoding, int bufferSize)
\r
88 : this (stream, encoding, bufferSize, false)
\r
92 public StreamWriter (Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
\r
94 const bool leave_open = false;
\r
96 public StreamWriter (Stream stream, Encoding encoding, int bufferSize)
\r
100 throw new ArgumentNullException("stream");
\r
101 if (null == encoding)
\r
102 throw new ArgumentNullException("encoding");
\r
103 if (bufferSize <= 0)
\r
104 throw new ArgumentOutOfRangeException("bufferSize");
\r
105 if (!stream.CanWrite)
\r
106 throw new ArgumentException ("Can not write to stream");
\r
109 leave_open = leaveOpen;
\r
111 internalStream = stream;
\r
113 Initialize(encoding, bufferSize);
\r
116 public StreamWriter (string path)
\r
117 : this (path, false, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}
\r
119 public StreamWriter (string path, bool append)
\r
120 : this (path, append, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}
\r
122 public StreamWriter (string path, bool append, Encoding encoding)
\r
123 : this (path, append, encoding, DefaultFileBufferSize) {}
\r
125 public StreamWriter (string path, bool append, Encoding encoding, int bufferSize)
\r
127 if (null == encoding)
\r
128 throw new ArgumentNullException("encoding");
\r
129 if (bufferSize <= 0)
\r
130 throw new ArgumentOutOfRangeException("bufferSize");
\r
135 mode = FileMode.Append;
\r
137 mode = FileMode.Create;
\r
139 internalStream = new FileStream (path, mode, FileAccess.Write, FileShare.Read);
\r
142 internalStream.Position = internalStream.Length;
\r
144 internalStream.SetLength (0);
\r
146 Initialize(encoding, bufferSize);
\r
149 public virtual bool AutoFlush {
\r
160 public virtual Stream BaseStream {
\r
162 return internalStream;
\r
166 public override Encoding Encoding {
\r
168 return internalEncoding;
\r
172 protected override void Dispose (bool disposing)
\r
174 if (byte_buf == null || !disposing)
\r
181 internalEncoding = null;
\r
185 internalStream.Close ();
\r
188 internalStream = null;
\r
192 public override void Flush ()
\r
198 // Keep in sync with FlushCoreAsync
\r
202 if (byte_pos > 0) {
\r
204 internalStream.Flush ();
\r
208 // how the speedup works:
\r
209 // the Write () methods simply copy the characters in a buffer of chars (decode_buf)
\r
210 // Decode () is called when the buffer is full or we need to flash.
\r
211 // Decode () will use the encoding to get the bytes and but them inside
\r
212 // byte_buf. From byte_buf the data is finally outputted to the stream.
\r
213 void FlushBytes ()
\r
215 // write the encoding preamble only at the start of the stream
\r
216 if (!preamble_done && byte_pos > 0) {
\r
217 byte[] preamble = internalEncoding.GetPreamble ();
\r
218 if (preamble.Length > 0)
\r
219 internalStream.Write (preamble, 0, preamble.Length);
\r
220 preamble_done = true;
\r
222 internalStream.Write (byte_buf, 0, byte_pos);
\r
230 if (decode_pos > 0) {
\r
231 int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);
\r
237 void LowLevelWrite (char[] buffer, int index, int count)
\r
239 while (count > 0) {
\r
240 int todo = decode_buf.Length - decode_pos;
\r
243 todo = decode_buf.Length;
\r
247 Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);
\r
250 decode_pos += todo;
\r
254 void LowLevelWrite (string s)
\r
256 int count = s.Length;
\r
258 while (count > 0) {
\r
259 int todo = decode_buf.Length - decode_pos;
\r
262 todo = decode_buf.Length;
\r
267 for (int i = 0; i < todo; i ++)
\r
268 decode_buf [i + decode_pos] = s [i + index];
\r
272 decode_pos += todo;
\r
277 async Task FlushCoreAsync ()
\r
279 await DecodeAsync ().ConfigureAwait (false);
\r
280 if (byte_pos > 0) {
\r
281 await FlushBytesAsync ().ConfigureAwait (false);
\r
282 await internalStream.FlushAsync ().ConfigureAwait (false);
\r
286 async Task FlushBytesAsync ()
\r
288 // write the encoding preamble only at the start of the stream
\r
289 if (!preamble_done && byte_pos > 0) {
\r
290 byte[] preamble = internalEncoding.GetPreamble ();
\r
291 if (preamble.Length > 0)
\r
292 await internalStream.WriteAsync (preamble, 0, preamble.Length).ConfigureAwait (false);
\r
293 preamble_done = true;
\r
296 await internalStream.WriteAsync (byte_buf, 0, byte_pos).ConfigureAwait (false);
\r
300 async Task DecodeAsync ()
\r
303 await FlushBytesAsync ().ConfigureAwait (false);
\r
304 if (decode_pos > 0) {
\r
305 int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);
\r
311 async Task LowLevelWriteAsync (char[] buffer, int index, int count)
\r
313 while (count > 0) {
\r
314 int todo = decode_buf.Length - decode_pos;
\r
316 await DecodeAsync ().ConfigureAwait (false);
\r
317 todo = decode_buf.Length;
\r
321 Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);
\r
324 decode_pos += todo;
\r
328 async Task LowLevelWriteAsync (string s)
\r
330 int count = s.Length;
\r
332 while (count > 0) {
\r
333 int todo = decode_buf.Length - decode_pos;
\r
335 await DecodeAsync ().ConfigureAwait (false);
\r
336 todo = decode_buf.Length;
\r
341 for (int i = 0; i < todo; i ++)
\r
342 decode_buf [i + decode_pos] = s [i + index];
\r
346 decode_pos += todo;
\r
351 public override void Write (char[] buffer, int index, int count)
\r
353 if (buffer == null)
\r
354 throw new ArgumentNullException ("buffer");
\r
356 throw new ArgumentOutOfRangeException ("index", "< 0");
\r
358 throw new ArgumentOutOfRangeException ("count", "< 0");
\r
359 // re-ordered to avoid possible integer overflow
\r
360 if (index > buffer.Length - count)
\r
361 throw new ArgumentException ("index + count > buffer.Length");
\r
365 LowLevelWrite (buffer, index, count);
\r
370 public override void Write (char value)
\r
374 // the size of decode_buf is always > 0 and
\r
375 // we check for overflow right away
\r
376 if (decode_pos >= decode_buf.Length)
\r
378 decode_buf [decode_pos++] = value;
\r
383 public override void Write (char[] buffer)
\r
387 if (buffer != null)
\r
388 LowLevelWrite (buffer, 0, buffer.Length);
\r
393 public override void Write (string value)
\r
400 LowLevelWrite (value);
\r
406 public override void Close()
\r
413 if (byte_buf == null)
\r
414 throw new ObjectDisposedException ("StreamWriter");
\r
417 if (async_task != null && !async_task.IsCompleted)
\r
418 throw new InvalidOperationException ();
\r
423 public override Task FlushAsync ()
\r
427 async_task = res = new DecoupledTask (FlushCoreAsync ());
\r
431 public override Task WriteAsync (char value)
\r
436 async_task = res = new DecoupledTask (WriteAsyncCore (value));
\r
440 async Task WriteAsyncCore (char value)
\r
442 // the size of decode_buf is always > 0 and
\r
443 // we check for overflow right away
\r
444 if (decode_pos >= decode_buf.Length)
\r
445 await DecodeAsync ().ConfigureAwait (false);
\r
446 decode_buf [decode_pos++] = value;
\r
449 await FlushCoreAsync ().ConfigureAwait (false);
\r
452 public override Task WriteAsync (char[] buffer, int index, int count)
\r
455 if (buffer == null)
\r
456 return TaskConstants.Finished;
\r
459 async_task = res = new DecoupledTask (WriteAsyncCore (buffer, index, count));
\r
463 async Task WriteAsyncCore (char[] buffer, int index, int count)
\r
465 // Debug.Assert (buffer == null);
\r
467 await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false);
\r
470 await FlushCoreAsync ().ConfigureAwait (false);
\r
473 public override Task WriteAsync (string value)
\r
478 return TaskConstants.Finished;
\r
480 DecoupledTask res;
\r
481 async_task = res = new DecoupledTask (WriteAsyncCore (value, false));
\r
485 async Task WriteAsyncCore (string value, bool appendNewLine)
\r
487 // Debug.Assert (value == null);
\r
489 await LowLevelWriteAsync (value).ConfigureAwait (false);
\r
491 await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);
\r
494 await FlushCoreAsync ().ConfigureAwait (false);
\r
497 public override Task WriteLineAsync ()
\r
502 async_task = res = new DecoupledTask (WriteAsyncCore (CoreNewLine, 0, CoreNewLine.Length));
\r
506 public override Task WriteLineAsync (char value)
\r
510 async_task = res = new DecoupledTask (WriteLineAsyncCore (value));
\r
514 async Task WriteLineAsyncCore (char value)
\r
516 await WriteAsyncCore (value).ConfigureAwait (false);
\r
517 await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);
\r
520 await FlushCoreAsync ().ConfigureAwait (false);
\r
523 public override Task WriteLineAsync (char[] buffer, int index, int count)
\r
525 if (buffer == null)
\r
526 throw new ArgumentNullException ("buffer");
\r
528 throw new ArgumentOutOfRangeException ("index", "< 0");
\r
530 throw new ArgumentOutOfRangeException ("count", "< 0");
\r
531 // re-ordered to avoid possible integer overflow
\r
532 if (index > buffer.Length - count)
\r
533 throw new ArgumentException ("index + count > buffer.Length");
\r
537 async_task = res = new DecoupledTask (WriteLineAsyncCore (buffer, index, count));
\r
541 async Task WriteLineAsyncCore (char[] buffer, int index, int count)
\r
543 // Debug.Assert (buffer == null);
\r
545 await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false);
\r
546 await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);
\r
549 await FlushCoreAsync ().ConfigureAwait (false);
\r
552 public override Task WriteLineAsync (string value)
\r
555 return WriteLineAsync ();
\r
558 DecoupledTask res;
\r
559 async_task = res = new DecoupledTask (WriteAsyncCore (value, true));
\r