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
238 async Task FlushCoreAsync ()
\r
240 await DecodeAsync ().ConfigureAwait (false);
\r
241 if (byte_pos > 0) {
\r
242 await FlushBytesAsync ().ConfigureAwait (false);
\r
243 await internalStream.FlushAsync ().ConfigureAwait (false);
\r
247 async Task FlushBytesAsync ()
\r
249 // write the encoding preamble only at the start of the stream
\r
250 if (!preamble_done && byte_pos > 0) {
\r
251 byte[] preamble = internalEncoding.GetPreamble ();
\r
252 if (preamble.Length > 0)
\r
253 await internalStream.WriteAsync (preamble, 0, preamble.Length).ConfigureAwait (false);
\r
254 preamble_done = true;
\r
257 await internalStream.WriteAsync (byte_buf, 0, byte_pos).ConfigureAwait (false);
\r
261 async Task DecodeAsync ()
\r
264 await FlushBytesAsync ().ConfigureAwait (false);
\r
265 if (decode_pos > 0) {
\r
266 int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);
\r
273 public override void Write (char[] buffer, int index, int count)
\r
275 if (buffer == null)
\r
276 throw new ArgumentNullException ("buffer");
\r
278 throw new ArgumentOutOfRangeException ("index", "< 0");
\r
280 throw new ArgumentOutOfRangeException ("count", "< 0");
\r
281 // re-ordered to avoid possible integer overflow
\r
282 if (index > buffer.Length - count)
\r
283 throw new ArgumentException ("index + count > buffer.Length");
\r
287 LowLevelWrite (buffer, index, count);
\r
292 void LowLevelWrite (char[] buffer, int index, int count)
\r
294 while (count > 0) {
\r
295 int todo = decode_buf.Length - decode_pos;
\r
298 todo = decode_buf.Length;
\r
302 Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);
\r
305 decode_pos += todo;
\r
309 void LowLevelWrite (string s)
\r
311 int count = s.Length;
\r
313 while (count > 0) {
\r
314 int todo = decode_buf.Length - decode_pos;
\r
317 todo = decode_buf.Length;
\r
322 for (int i = 0; i < todo; i ++)
\r
323 decode_buf [i + decode_pos] = s [i + index];
\r
327 decode_pos += todo;
\r
331 public override void Write (char value)
\r
335 // the size of decode_buf is always > 0 and
\r
336 // we check for overflow right away
\r
337 if (decode_pos >= decode_buf.Length)
\r
339 decode_buf [decode_pos++] = value;
\r
344 public override void Write (char[] buffer)
\r
348 if (buffer != null)
\r
349 LowLevelWrite (buffer, 0, buffer.Length);
\r
354 public override void Write (string value)
\r
359 LowLevelWrite (value);
\r
365 public override void Close()
\r
372 if (byte_buf == null)
\r
373 throw new ObjectDisposedException ("StreamWriter");
\r
376 if (async_task != null && !async_task.IsCompleted)
\r
377 throw new InvalidOperationException ();
\r
382 public override Task FlushAsync ()
\r
386 async_task = res = new DecoupledTask (FlushCoreAsync ());
\r
390 public override Task WriteAsync (char value)
\r
395 async_task = res = new DecoupledTask (WriteAsyncCore (value));
\r
399 async Task WriteAsyncCore (char value)
\r
401 // the size of decode_buf is always > 0 and
\r
402 // we check for overflow right away
\r
403 if (decode_pos >= decode_buf.Length)
\r
404 await DecodeAsync ().ConfigureAwait (false);
\r
405 decode_buf [decode_pos++] = value;
\r
408 await FlushCoreAsync ().ConfigureAwait (false);
\r
411 public override Task WriteAsync (char[] buffer, int index, int count)
\r
414 if (buffer == null)
\r
415 return TaskConstants.Finished;
\r
418 async_task = res = new DecoupledTask (WriteAsyncCore (buffer, index, count));
\r
422 async Task WriteAsyncCore (char[] buffer, int index, int count)
\r
424 // Debug.Assert (buffer == null);
\r
426 LowLevelWrite (buffer, 0, buffer.Length);
\r
429 await FlushCoreAsync ().ConfigureAwait (false);
\r
432 public override Task WriteAsync (string value)
\r
435 DecoupledTask res;
\r
436 async_task = res = new DecoupledTask(base.WriteAsync (value));
\r
440 public override Task WriteLineAsync ()
\r
443 DecoupledTask res;
\r
444 async_task = res = new DecoupledTask (base.WriteLineAsync ());
\r
448 public override Task WriteLineAsync (char value)
\r
452 async_task = res = new DecoupledTask (base.WriteLineAsync (value));
\r
456 public override Task WriteLineAsync (char[] buffer, int index, int count)
\r
460 async_task = res = new DecoupledTask (base.WriteLineAsync (buffer, index, count));
\r
464 public override Task WriteLineAsync (string value)
\r
467 DecoupledTask res;
\r
468 async_task = res = new DecoupledTask (base.WriteLineAsync (value));
\r