Merge branch 'msbuilddll2'
[mono.git] / mcs / class / corlib / System.IO / StreamWriter.cs
index c3eac0a994f16078f05a0a3ddc19fd21f5ecb6d8..fe3a606261730cd522bea0648a95c3deb600117e 100644 (file)
@@ -4,61 +4,66 @@
 // Authors:\r
 //   Dietmar Maurer (dietmar@ximian.com)\r
 //   Paolo Molaro (lupus@ximian.com)\r
+//   Marek Safar (marek.safar@gmail.com)\r
 //\r
 // (C) Ximian, Inc.  http://www.ximian.com\r
+// Copyright (C) 2004 Novell, Inc (http://www.novell.com)\r
+// Copyright 2011, 2013 Xamarin Inc.\r
+//\r
+// Permission is hereby granted, free of charge, to any person obtaining\r
+// a copy of this software and associated documentation files (the\r
+// "Software"), to deal in the Software without restriction, including\r
+// without limitation the rights to use, copy, modify, merge, publish,\r
+// distribute, sublicense, and/or sell copies of the Software, and to\r
+// permit persons to whom the Software is furnished to do so, subject to\r
+// the following conditions:\r
+// \r
+// The above copyright notice and this permission notice shall be\r
+// included in all copies or substantial portions of the Software.\r
+// \r
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\r
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\r
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\r
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
 //\r
-
-//
-// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
 \r
 using System.Text;\r
-using System;\r
+using System.Runtime.InteropServices;\r
+#if NET_4_5\r
+using System.Threading.Tasks;\r
+#endif\r
 \r
 namespace System.IO {\r
        \r
        [Serializable]\r
+       [ComVisible (true)]\r
        public class StreamWriter : TextWriter {\r
 \r
                private Encoding internalEncoding;\r
 \r
                private Stream internalStream;\r
-               private bool closed = false;\r
 \r
-               private bool iflush;\r
-               \r
                private const int DefaultBufferSize = 1024;\r
                private const int DefaultFileBufferSize = 4096;\r
                private const int MinimumBufferSize = 256;\r
 \r
                private byte[] byte_buf;\r
-               private int byte_pos;\r
                private char[] decode_buf;\r
+               private int byte_pos;\r
                private int decode_pos;\r
 \r
-               private bool DisposedAlready = false;\r
-               private bool preamble_done = false;\r
+               private bool iflush;\r
+               private bool preamble_done;\r
+\r
+#if NET_4_5\r
+               readonly bool leave_open;\r
+               IDecoupledTask async_task;\r
+#endif\r
 \r
-               public new static readonly StreamWriter Null = new StreamWriter (Stream.Null, Encoding.UTF8Unmarked, 0);\r
+               public new static readonly StreamWriter Null = new StreamWriter (Stream.Null, Encoding.UTF8Unmarked, 1);\r
 \r
                public StreamWriter (Stream stream)\r
                        : this (stream, Encoding.UTF8Unmarked, DefaultBufferSize) {}\r
@@ -72,23 +77,37 @@ namespace System.IO {
                        int BufferSize = Math.Max(bufferSize, MinimumBufferSize);\r
                        decode_buf = new char [BufferSize];\r
                        byte_buf = new byte [encoding.GetMaxByteCount (BufferSize)];\r
-
-                       // Fixes bug http://bugzilla.ximian.com/show_bug.cgi?id=74513
-                       if (internalStream.CanSeek && internalStream.Position > 0)
-                               preamble_done = true;
+\r
+                       // Fixes bug http://bugzilla.ximian.com/show_bug.cgi?id=74513\r
+                       if (internalStream.CanSeek && internalStream.Position > 0)\r
+                               preamble_done = true;\r
+               }\r
+\r
+#if NET_4_5\r
+               public StreamWriter (Stream stream, Encoding encoding, int bufferSize)\r
+                       : this (stream, encoding, bufferSize, false)\r
+               {\r
                }\r
+               \r
+               public StreamWriter (Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)\r
+#else\r
+               const bool leave_open = false;\r
 \r
-               //[MonoTODO("Nothing is done with bufferSize")]\r
-               public StreamWriter (Stream stream, Encoding encoding, int bufferSize) {\r
+               public StreamWriter (Stream stream, Encoding encoding, int bufferSize)\r
+#endif\r
+               {\r
                        if (null == stream)\r
                                throw new ArgumentNullException("stream");\r
                        if (null == encoding)\r
                                throw new ArgumentNullException("encoding");\r
-                       if (bufferSize < 0)\r
+                       if (bufferSize <= 0)\r
                                throw new ArgumentOutOfRangeException("bufferSize");\r
                        if (!stream.CanWrite)\r
-                               throw new ArgumentException("Can not write to stream", "stream");\r
+                               throw new ArgumentException ("Can not write to stream");\r
 \r
+#if NET_4_5\r
+                       leave_open = leaveOpen;\r
+#endif\r
                        internalStream = stream;\r
 \r
                        Initialize(encoding, bufferSize);\r
@@ -102,24 +121,14 @@ namespace System.IO {
 \r
                public StreamWriter (string path, bool append, Encoding encoding)\r
                        : this (path, append, encoding, DefaultFileBufferSize) {}\r
-               \r
-               public StreamWriter (string path, bool append, Encoding encoding, int bufferSize) {\r
-                       if (null == path)\r
-                               throw new ArgumentNullException("path");\r
-                       if (String.Empty == path)\r
-                               throw new ArgumentException("path cannot be empty string");\r
-                       if (path.IndexOfAny (Path.InvalidPathChars) != -1)\r
-                               throw new ArgumentException("path contains invalid characters");\r
 \r
+               public StreamWriter (string path, bool append, Encoding encoding, int bufferSize)\r
+               {\r
                        if (null == encoding)\r
                                throw new ArgumentNullException("encoding");\r
-                       if (bufferSize < 0)\r
+                       if (bufferSize <= 0)\r
                                throw new ArgumentOutOfRangeException("bufferSize");\r
 \r
-                       string DirName = Path.GetDirectoryName(path);\r
-                       if (DirName != String.Empty && !Directory.Exists(DirName))\r
-                               throw new DirectoryNotFoundException();\r
-\r
                        FileMode mode;\r
 \r
                        if (append)\r
@@ -141,16 +150,12 @@ namespace System.IO {
                        get {\r
                                return iflush;\r
                        }\r
-                       set {
-                               if (DisposedAlready)
-                                       throw new ObjectDisposedException("StreamWriter");
-                               iflush = value;
-
-                               if (iflush) {
-                                       Flush ();
-                               }
-                       }
-               }
+                       set {\r
+                               iflush = value;\r
+                               if (iflush)\r
+                                       Flush ();\r
+                       }\r
+               }\r
 \r
                public virtual Stream BaseStream {\r
                        get {\r
@@ -166,23 +171,33 @@ namespace System.IO {
 \r
                protected override void Dispose (bool disposing) \r
                {\r
-                       if (!DisposedAlready && disposing && internalStream != null) {\r
-                               Flush();\r
-                               DisposedAlready = true;\r
-                               internalStream.Close ();\r
-                       }\r
+                       if (byte_buf == null || !disposing)\r
+                               return;\r
 \r
-                       internalStream = null;\r
-                       byte_buf = null;\r
-                       internalEncoding = null;\r
-                       decode_buf = null;\r
+                       try {\r
+                               Flush ();\r
+                       } finally {\r
+                               byte_buf = null;\r
+                               internalEncoding = null;\r
+                               decode_buf = null;\r
+\r
+                               if (!leave_open) {\r
+                                       internalStream.Close ();\r
+                               }\r
+\r
+                               internalStream = null;\r
+                       }\r
                }\r
 \r
                public override void Flush ()\r
                {\r
-                       if (DisposedAlready)\r
-                               throw new ObjectDisposedException("StreamWriter");\r
+                       CheckState ();\r
+                       FlushCore ();\r
+               }\r
 \r
+               // Keep in sync with FlushCoreAsync\r
+               void FlushCore ()\r
+               {\r
                        Decode ();\r
                        if (byte_pos > 0) {\r
                                FlushBytes ();\r
@@ -207,7 +222,7 @@ namespace System.IO {
                        internalStream.Write (byte_buf, 0, byte_pos);\r
                        byte_pos = 0;\r
                }\r
-               \r
+\r
                void Decode () \r
                {\r
                        if (byte_pos > 0)\r
@@ -218,34 +233,89 @@ namespace System.IO {
                                decode_pos = 0;\r
                        }\r
                }\r
-               \r
-               public override void Write (char[] buffer, int index, int count) \r
-               {\r
-                       if (DisposedAlready)\r
-                               throw new ObjectDisposedException("StreamWriter");\r
-                       if (buffer == null)\r
-                               throw new ArgumentNullException ("buffer");\r
-                       if (index < 0)\r
-                               throw new ArgumentOutOfRangeException ("index", "< 0");\r
-                       if (count < 0)\r
-                               throw new ArgumentOutOfRangeException ("count", "< 0");\r
-                       // re-ordered to avoid possible integer overflow\r
-                       if (index > buffer.Length - count)\r
-                               throw new ArgumentException ("index + count > buffer.Length");\r
 \r
-                       LowLevelWrite (buffer, index, count);\r
-                       if (iflush)\r
-                               Flush();\r
+               void LowLevelWrite (char[] buffer, int index, int count)\r
+               {\r
+                       while (count > 0) {\r
+                               int todo = decode_buf.Length - decode_pos;\r
+                               if (todo == 0) {\r
+                                       Decode ();\r
+                                       todo = decode_buf.Length;\r
+                               }\r
+                               if (todo > count)\r
+                                       todo = count;\r
+                               Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);\r
+                               count -= todo;\r
+                               index += todo;\r
+                               decode_pos += todo;\r
+                       }\r
                }\r
                \r
-               void LowLevelWrite (char[] buffer, int index, int count)\r
+               void LowLevelWrite (string s)\r
                {\r
+                       int count = s.Length;\r
+                       int index = 0;\r
                        while (count > 0) {\r
                                int todo = decode_buf.Length - decode_pos;\r
                                if (todo == 0) {\r
                                        Decode ();\r
                                        todo = decode_buf.Length;\r
                                }\r
+                               if (todo > count)\r
+                                       todo = count;\r
+                               \r
+                               for (int i = 0; i < todo; i ++)\r
+                                       decode_buf [i + decode_pos] = s [i + index];\r
+                               \r
+                               count -= todo;\r
+                               index += todo;\r
+                               decode_pos += todo;\r
+                       }\r
+               }               \r
+\r
+#if NET_4_5\r
+               async Task FlushCoreAsync ()\r
+               {\r
+                       await DecodeAsync ().ConfigureAwait (false);\r
+                       if (byte_pos > 0) {\r
+                               await FlushBytesAsync ().ConfigureAwait (false);\r
+                               await internalStream.FlushAsync ().ConfigureAwait (false);\r
+                       }\r
+               }\r
+\r
+               async Task FlushBytesAsync ()\r
+               {\r
+                       // write the encoding preamble only at the start of the stream\r
+                       if (!preamble_done && byte_pos > 0) {\r
+                               byte[] preamble = internalEncoding.GetPreamble ();\r
+                               if (preamble.Length > 0)\r
+                                       await internalStream.WriteAsync (preamble, 0, preamble.Length).ConfigureAwait (false);\r
+                               preamble_done = true;\r
+                       }\r
+\r
+                       await internalStream.WriteAsync (byte_buf, 0, byte_pos).ConfigureAwait (false);\r
+                       byte_pos = 0;\r
+               }\r
+\r
+               async Task DecodeAsync () \r
+               {\r
+                       if (byte_pos > 0)\r
+                               await FlushBytesAsync ().ConfigureAwait (false);\r
+                       if (decode_pos > 0) {\r
+                               int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);\r
+                               byte_pos += len;\r
+                               decode_pos = 0;\r
+                       }\r
+               }               \r
+\r
+               async Task LowLevelWriteAsync (char[] buffer, int index, int count)\r
+               {\r
+                       while (count > 0) {\r
+                               int todo = decode_buf.Length - decode_pos;\r
+                               if (todo == 0) {\r
+                                       await DecodeAsync ().ConfigureAwait (false);\r
+                                       todo = decode_buf.Length;\r
+                               }\r
                                if (todo > count)\r
                                        todo = count;\r
                                Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);\r
@@ -253,34 +323,53 @@ namespace System.IO {
                                index += todo;\r
                                decode_pos += todo;\r
                        }\r
-               }
-               
-               void LowLevelWrite (string s)
-               {
-                       int count = s.Length;
-                       int index = 0;
-                       while (count > 0) {
-                               int todo = decode_buf.Length - decode_pos;
-                               if (todo == 0) {
-                                       Decode ();
-                                       todo = decode_buf.Length;
-                               }
-                               if (todo > count)
-                                       todo = count;
-                               
-                               for (int i = 0; i < todo; i ++)
-                                       decode_buf [i + decode_pos] = s [i + index];
-                               
-                               count -= todo;
-                               index += todo;
-                               decode_pos += todo;
-                       }
                }\r
+               \r
+               async Task LowLevelWriteAsync (string s)\r
+               {\r
+                       int count = s.Length;\r
+                       int index = 0;\r
+                       while (count > 0) {\r
+                               int todo = decode_buf.Length - decode_pos;\r
+                               if (todo == 0) {\r
+                                       await DecodeAsync ().ConfigureAwait (false);\r
+                                       todo = decode_buf.Length;\r
+                               }\r
+                               if (todo > count)\r
+                                       todo = count;\r
+                               \r
+                               for (int i = 0; i < todo; i ++)\r
+                                       decode_buf [i + decode_pos] = s [i + index];\r
+                               \r
+                               count -= todo;\r
+                               index += todo;\r
+                               decode_pos += todo;\r
+                       }\r
+               }       \r
+#endif\r
 \r
+               public override void Write (char[] buffer, int index, int count) \r
+               {\r
+                       if (buffer == null)\r
+                               throw new ArgumentNullException ("buffer");\r
+                       if (index < 0)\r
+                               throw new ArgumentOutOfRangeException ("index", "< 0");\r
+                       if (count < 0)\r
+                               throw new ArgumentOutOfRangeException ("count", "< 0");\r
+                       // re-ordered to avoid possible integer overflow\r
+                       if (index > buffer.Length - count)\r
+                               throw new ArgumentException ("index + count > buffer.Length");\r
+\r
+                       CheckState ();\r
+\r
+                       LowLevelWrite (buffer, index, count);\r
+                       if (iflush)\r
+                               FlushCore ();\r
+               }\r
+               \r
                public override void Write (char value)\r
                {\r
-                       if (DisposedAlready)\r
-                               throw new ObjectDisposedException("StreamWriter");\r
+                       CheckState ();\r
 \r
                        // the size of decode_buf is always > 0 and\r
                        // we check for overflow right away\r
@@ -288,41 +377,188 @@ namespace System.IO {
                                Decode ();\r
                        decode_buf [decode_pos++] = value;\r
                        if (iflush)\r
-                               Flush ();\r
+                               FlushCore ();\r
                }\r
 \r
-               public override void Write (char[] value)\r
+               public override void Write (char[] buffer)\r
                {\r
-                       if (DisposedAlready)\r
-                               throw new ObjectDisposedException("StreamWriter");\r
+                       CheckState ();\r
 \r
-                       if (value != null)\r
-                               LowLevelWrite (value, 0, value.Length);\r
+                       if (buffer != null)\r
+                               LowLevelWrite (buffer, 0, buffer.Length);\r
                        if (iflush)\r
-                               Flush ();\r
+                               FlushCore ();\r
                }\r
 \r
                public override void Write (string value) \r
                {\r
-                       if (DisposedAlready)\r
-                               throw new ObjectDisposedException("StreamWriter");\r
+                       CheckState ();\r
 \r
-                       if (value != null)\r
-                               LowLevelWrite (value);
+                       if (value == null)\r
+                               return;\r
+                       \r
+                       LowLevelWrite (value);\r
                        \r
                        if (iflush)\r
-                               Flush ();\r
+                               FlushCore ();\r
                }\r
 \r
                public override void Close()\r
                {\r
-                        closed = true;\r
                        Dispose (true);\r
                }\r
 \r
-               ~StreamWriter ()\r
+               void CheckState ()\r
+               {\r
+                       if (byte_buf == null)\r
+                               throw new ObjectDisposedException ("StreamWriter");\r
+\r
+#if NET_4_5\r
+                       if (async_task != null && !async_task.IsCompleted)\r
+                               throw new InvalidOperationException ();\r
+#endif\r
+               }\r
+\r
+#if NET_4_5\r
+               public override Task FlushAsync ()\r
+               {\r
+                       CheckState ();\r
+                       DecoupledTask res;\r
+                       async_task = res = new DecoupledTask (FlushCoreAsync ());\r
+                       return res.Task;\r
+               }\r
+\r
+               public override Task WriteAsync (char value)\r
+               {\r
+                       CheckState ();\r
+\r
+                       DecoupledTask res;\r
+                       async_task = res = new DecoupledTask (WriteAsyncCore (value));\r
+                       return res.Task;\r
+               }\r
+\r
+               async Task WriteAsyncCore (char value)\r
+               {\r
+                       // the size of decode_buf is always > 0 and\r
+                       // we check for overflow right away\r
+                       if (decode_pos >= decode_buf.Length)\r
+                               await DecodeAsync ().ConfigureAwait (false);\r
+                       decode_buf [decode_pos++] = value;\r
+\r
+                       if (iflush)\r
+                               await FlushCoreAsync ().ConfigureAwait (false);\r
+               }\r
+\r
+               public override Task WriteAsync (char[] buffer, int index, int count)\r
+               {\r
+                       CheckState ();\r
+                       if (buffer == null)\r
+                               return TaskConstants.Finished;\r
+\r
+                       DecoupledTask res;\r
+                       async_task = res = new DecoupledTask (WriteAsyncCore (buffer, index, count));\r
+                       return res.Task;\r
+               }\r
+\r
+               async Task WriteAsyncCore (char[] buffer, int index, int count)\r
+               {\r
+                       // Debug.Assert (buffer == null);\r
+\r
+                       await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false);\r
+\r
+                       if (iflush)\r
+                               await FlushCoreAsync ().ConfigureAwait (false);\r
+               }\r
+\r
+               public override Task WriteAsync (string value)\r
+               {\r
+                       CheckState ();\r
+\r
+                       if (value == null)\r
+                               return TaskConstants.Finished;\r
+\r
+                       DecoupledTask res;                      \r
+                       async_task = res = new DecoupledTask (WriteAsyncCore (value, false));\r
+                       return res.Task;\r
+               }\r
+\r
+               async Task WriteAsyncCore (string value, bool appendNewLine)\r
+               {\r
+                       // Debug.Assert (value == null);\r
+\r
+                       await LowLevelWriteAsync (value).ConfigureAwait (false);\r
+                       if (appendNewLine)\r
+                               await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);\r
+                       \r
+                       if (iflush)\r
+                               await FlushCoreAsync ().ConfigureAwait (false);\r
+               }               \r
+\r
+               public override Task WriteLineAsync ()\r
+               {\r
+                       CheckState ();\r
+\r
+                       DecoupledTask res;\r
+                       async_task = res = new DecoupledTask (WriteAsyncCore (CoreNewLine, 0, CoreNewLine.Length));\r
+                       return res.Task;\r
+               }\r
+\r
+               public override Task WriteLineAsync (char value)\r
+               {\r
+                       CheckState ();\r
+                       DecoupledTask res;\r
+                       async_task = res = new DecoupledTask (WriteLineAsyncCore (value));\r
+                       return res.Task;\r
+               }\r
+\r
+               async Task WriteLineAsyncCore (char value)\r
                {\r
-                       Dispose(false);\r
+                       await WriteAsyncCore (value).ConfigureAwait (false);\r
+                       await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);\r
+                       \r
+                       if (iflush)\r
+                               await FlushCoreAsync ().ConfigureAwait (false);\r
+               }               \r
+\r
+               public override Task WriteLineAsync (char[] buffer, int index, int count)\r
+               {\r
+                       if (buffer == null)\r
+                               throw new ArgumentNullException ("buffer");\r
+                       if (index < 0)\r
+                               throw new ArgumentOutOfRangeException ("index", "< 0");\r
+                       if (count < 0)\r
+                               throw new ArgumentOutOfRangeException ("count", "< 0");\r
+                       // re-ordered to avoid possible integer overflow\r
+                       if (index > buffer.Length - count)\r
+                               throw new ArgumentException ("index + count > buffer.Length");\r
+\r
+                       CheckState ();\r
+                       DecoupledTask res;\r
+                       async_task = res = new DecoupledTask (WriteLineAsyncCore (buffer, index, count));\r
+                       return res.Task;\r
+               }\r
+\r
+               async Task WriteLineAsyncCore (char[] buffer, int index, int count)\r
+               {\r
+                       // Debug.Assert (buffer == null);\r
+\r
+                       await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false);\r
+                       await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);\r
+                       \r
+                       if (iflush)\r
+                               await FlushCoreAsync ().ConfigureAwait (false);\r
+               }               \r
+\r
+               public override Task WriteLineAsync (string value)\r
+               {\r
+                       if (value == null)\r
+                               return WriteLineAsync ();\r
+\r
+                       CheckState ();\r
+                       DecoupledTask res;                      \r
+                       async_task = res = new DecoupledTask (WriteAsyncCore (value, true));\r
+                       return res.Task;\r
                }\r
+#endif\r
        }\r
 }\r