Merge pull request #681 from tritao/dll-api
[mono.git] / mcs / class / corlib / System.IO / StreamWriter.cs
index 7587316f0394a0a6383e8dae57399009580cc57a..fe3a606261730cd522bea0648a95c3deb600117e 100644 (file)
 //\r
 // System.IO.StreamWriter.cs\r
 //\r
-// Author:\r
+// 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
 \r
 using System.Text;\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
-        public class StreamWriter : TextWriter {\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 const int DefaultBufferSize = 1024;\r
+               private const int DefaultFileBufferSize = 4096;\r
+               private const int MinimumBufferSize = 256;\r
+\r
+               private byte[] byte_buf;\r
+               private char[] decode_buf;\r
+               private int byte_pos;\r
+               private int decode_pos;\r
 \r
                private bool iflush;\r
-               \r
-                // new public static readonly StreamWriter Null;\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, 1);\r
 \r
                public StreamWriter (Stream stream)\r
-                       : this (stream, Encoding.UTF8, 0) {}\r
+                       : this (stream, Encoding.UTF8Unmarked, DefaultBufferSize) {}\r
 \r
                public StreamWriter (Stream stream, Encoding encoding)\r
-                       : this (stream, encoding, 0) {}\r
+                       : this (stream, encoding, DefaultBufferSize) {}\r
+\r
+               internal void Initialize(Encoding encoding, int bufferSize) {\r
+                       internalEncoding = encoding;\r
+                       decode_pos = byte_pos = 0;\r
+                       int BufferSize = Math.Max(bufferSize, MinimumBufferSize);\r
+                       decode_buf = new char [BufferSize];\r
+                       byte_buf = new byte [encoding.GetMaxByteCount (BufferSize)];\r
+\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
-               [MonoTODO("Nothing is done with bufferSize")]\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
+               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("bufferSize");\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
-                       internalEncoding = encoding;\r
+\r
+                       Initialize(encoding, bufferSize);\r
                }\r
 \r
                public StreamWriter (string path)\r
-                       : this (path, false, Encoding.UTF8, 0) {}\r
+                       : this (path, false, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}\r
 \r
                public StreamWriter (string path, bool append)\r
-                       : this (path, append, Encoding.UTF8, 0) {}\r
+                       : this (path, append, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}\r
 \r
                public StreamWriter (string path, bool append, Encoding encoding)\r
-                       : this (path, append, encoding, 0) {}\r
-               \r
+                       : this (path, append, encoding, DefaultFileBufferSize) {}\r
+\r
                public StreamWriter (string path, bool append, Encoding encoding, int bufferSize)\r
                {\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
                        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
@@ -79,84 +136,429 @@ namespace System.IO {
                        else\r
                                mode = FileMode.Create;\r
                        \r
-                       internalStream = new FileStream (path, mode, FileAccess.Write);\r
+                       internalStream = new FileStream (path, mode, FileAccess.Write, FileShare.Read);\r
 \r
                        if (append)\r
                                internalStream.Position = internalStream.Length;\r
                        else\r
                                internalStream.SetLength (0);\r
 \r
-                       internalEncoding = encoding;\r
-                       \r
+                       Initialize(encoding, bufferSize);\r
                }\r
 \r
-               public virtual bool AutoFlush\r
-               {\r
-\r
+               public virtual bool AutoFlush {\r
                        get {\r
                                return iflush;\r
                        }\r
-\r
                        set {\r
                                iflush = value;\r
+                               if (iflush)\r
+                                       Flush ();\r
                        }\r
                }\r
 \r
-               public virtual Stream BaseStream\r
-               {\r
+               public virtual Stream BaseStream {\r
                        get {\r
                                return internalStream;\r
                        }\r
                }\r
 \r
-               public override Encoding Encoding\r
-               {\r
+               public override Encoding Encoding {\r
                        get {\r
                                return internalEncoding;\r
                        }\r
                }\r
 \r
-               protected override void Dispose (bool disposing)\r
+               protected override void Dispose (bool disposing) \r
                {\r
-                       if (disposing && internalStream != null) {\r
-                               internalStream.Close ();\r
+                       if (byte_buf == null || !disposing)\r
+                               return;\r
+\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 (closed)\r
-                               throw new ObjectDisposedException("TextWriter");\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
+                               internalStream.Flush ();\r
+                       }\r
+               }\r
+\r
+               // how the speedup works:\r
+               // the Write () methods simply copy the characters in a buffer of chars (decode_buf)\r
+               // Decode () is called when the buffer is full or we need to flash.\r
+               // Decode () will use the encoding to get the bytes and but them inside\r
+               // byte_buf. From byte_buf the data is finally outputted to the stream.\r
+               void FlushBytes () \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
+                                       internalStream.Write (preamble, 0, preamble.Length);\r
+                               preamble_done = true;\r
+                       }\r
+                       internalStream.Write (byte_buf, 0, byte_pos);\r
+                       byte_pos = 0;\r
+               }\r
+\r
+               void Decode () \r
+               {\r
+                       if (byte_pos > 0)\r
+                               FlushBytes ();\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
+               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 (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
-                       internalStream.Flush ();\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
+                               count -= todo;\r
+                               index += todo;\r
+                               decode_pos += todo;\r
+                       }\r
                }\r
                \r
-               public override void Write (char[] buffer, int index, int count)\r
+               async Task LowLevelWriteAsync (string s)\r
                {\r
-                       byte[] res = new byte [internalEncoding.GetMaxByteCount (buffer.Length)];\r
-                       int len;\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
-                       len = internalEncoding.GetBytes (buffer, index, count, res, 0);\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
-                       internalStream.Write (res, 0, len);\r
+                       CheckState ();\r
 \r
+                       LowLevelWrite (buffer, index, count);\r
                        if (iflush)\r
-                               Flush ();\r
-                       \r
+                               FlushCore ();\r
+               }\r
+               \r
+               public override void Write (char value)\r
+               {\r
+                       CheckState ();\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
+                               Decode ();\r
+                       decode_buf [decode_pos++] = value;\r
+                       if (iflush)\r
+                               FlushCore ();\r
                }\r
 \r
-               public override void Write(string value)\r
+               public override void Write (char[] buffer)\r
                {\r
-                       Write (value.ToCharArray (), 0, value.Length);\r
+                       CheckState ();\r
+\r
+                       if (buffer != null)\r
+                               LowLevelWrite (buffer, 0, buffer.Length);\r
+                       if (iflush)\r
+                               FlushCore ();\r
+               }\r
+\r
+               public override void Write (string value) \r
+               {\r
+                       CheckState ();\r
+\r
+                       if (value == null)\r
+                               return;\r
+                       \r
+                       LowLevelWrite (value);\r
+                       \r
+                       if (iflush)\r
+                               FlushCore ();\r
                }\r
 \r
                public override void Close()\r
                {\r
-                       Dispose(true);\r
-                       closed = true;\r
+                       Dispose (true);\r
+               }\r
+\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
+                       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
-        }\r
+#endif\r
+       }\r
 }\r
-                        \r
-                        \r