Reorder fields to improve object layout since the runtime can't do it for corlib...
[mono.git] / mcs / class / corlib / System.IO / StreamWriter.cs
index d4ad8751cde2371b6c5a947abdb54db2d33982d2..755a553f6a3fe7690a35a2c5372d38e3691781a5 100644 (file)
@@ -1,62 +1,93 @@
 //\r
 // System.IO.StreamWriter.cs\r
 //\r
-// Author:\r
+// Authors:\r
 //   Dietmar Maurer (dietmar@ximian.com)\r
+//   Paolo Molaro (lupus@ximian.com)\r
 //\r
 // (C) Ximian, Inc.  http://www.ximian.com\r
 //\r
 \r
+//\r
+// Copyright (C) 2004 Novell, Inc (http://www.novell.com)\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;\r
 \r
+using System.Runtime.InteropServices;\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 = 2;\r
+               private const int MinimumBufferSize = 256;\r
 \r
-               private int pos;\r
-               private int BufferSize;\r
-               private byte[] TheBuffer;\r
+               private byte[] byte_buf;\r
+               private char[] decode_buf;\r
+               private int byte_pos;\r
+               private int decode_pos;\r
 \r
-               private bool DisposedAlready = false;\r
+               private bool iflush;\r
+               private bool DisposedAlready;\r
+               private bool preamble_done;\r
 \r
-               public new static readonly StreamWriter Null = new StreamWriter (Stream.Null, Encoding.UTF8, 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.UTF8, DefaultBufferSize) {}\r
+                       : this (stream, Encoding.UTF8Unmarked, DefaultBufferSize) {}\r
 \r
                public StreamWriter (Stream stream, Encoding encoding)\r
                        : this (stream, encoding, DefaultBufferSize) {}\r
 \r
                internal void Initialize(Encoding encoding, int bufferSize) {\r
                        internalEncoding = encoding;\r
-                       pos = 0;\r
-                       BufferSize = Math.Max(bufferSize, MinimumBufferSize);\r
-                       TheBuffer = new byte[BufferSize];\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
                public StreamWriter (Stream stream, Encoding encoding, int bufferSize) {\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
                        internalStream = stream;\r
 \r
@@ -64,31 +95,20 @@ namespace System.IO {
                }\r
 \r
                public StreamWriter (string path)\r
-                       : this (path, false, Encoding.UTF8, DefaultFileBufferSize) {}\r
+                       : this (path, false, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}\r
 \r
                public StreamWriter (string path, bool append)\r
-                       : this (path, append, Encoding.UTF8, DefaultFileBufferSize) {}\r
+                       : this (path, append, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}\r
 \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
                        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
@@ -96,7 +116,7 @@ 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
@@ -112,6 +132,8 @@ namespace System.IO {
                        }\r
                        set {\r
                                iflush = value;\r
+                               if (iflush)\r
+                                       Flush ();\r
                        }\r
                }\r
 \r
@@ -127,76 +149,166 @@ namespace System.IO {
                        }\r
                }\r
 \r
-               protected override void Dispose (bool disposing) {\r
+               protected override void Dispose (bool disposing) \r
+               {\r
+                       Exception exc = null;\r
                        if (!DisposedAlready && disposing && internalStream != null) {\r
+                               try {\r
+                                       Flush();\r
+                               } catch (Exception e) {\r
+                                       exc = e;\r
+                               }\r
                                DisposedAlready = true;\r
-                               Flush();\r
-                               internalStream.Close ();\r
+                               try {\r
+                                       internalStream.Close ();\r
+                               } catch (Exception e) {\r
+                                       if (exc == null)\r
+                                               exc = e;\r
+                               }\r
                        }\r
 \r
                        internalStream = null;\r
-                       TheBuffer = null;\r
+                       byte_buf = null;\r
                        internalEncoding = null;\r
+                       decode_buf = null;\r
+                       if (exc != null)\r
+                               throw exc;\r
                }\r
 \r
-               public override void Flush () {\r
+               public override void Flush ()\r
+               {\r
                        if (DisposedAlready)\r
                                throw new ObjectDisposedException("StreamWriter");\r
 \r
-                       if (pos > 0) {\r
-                               internalStream.Write (TheBuffer, 0, pos);\r
+                       Decode ();\r
+                       if (byte_pos > 0) {\r
+                               FlushBytes ();\r
                                internalStream.Flush ();\r
-                               pos = 0;\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
-               public override void Write (char[] buffer, int index, int count) {\r
+               public override void Write (char[] buffer, int index, int count) \r
+               {\r
                        if (DisposedAlready)\r
                                throw new ObjectDisposedException("StreamWriter");\r
-\r
-                       byte[] res = new byte [internalEncoding.GetByteCount (buffer)];\r
-                       int len;\r
-                       int BytesToBuffer;\r
-                       int resPos = 0;\r
-\r
-                       len = internalEncoding.GetBytes (buffer, index, count, res, 0);\r
-\r
-                       // if they want AutoFlush, don't bother buffering\r
-                       if (iflush) {\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
-                               internalStream.Write (res, 0, len);\r
-                               internalStream.Flush ();\r
-                       } else {\r
-                               // otherwise use the buffer.\r
-                               // NOTE: this logic is not optimized for performance.\r
-                               while (resPos < len) {\r
-                                       // fill the buffer if we've got more bytes than will fit\r
-                                       BytesToBuffer = Math.Min(BufferSize - pos, len - resPos);\r
-                                       Array.Copy(res, resPos, TheBuffer, pos, BytesToBuffer);\r
-                                       resPos += BytesToBuffer;\r
-                                       pos += BytesToBuffer;\r
-                                       // if the buffer is full, flush it out.\r
-                                       if (pos == BufferSize) Flush();\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
                public override void Write (char value)\r
                {\r
-                       Write (new char [] {value}, 0, 1);\r
+                       if (DisposedAlready)\r
+                               throw new ObjectDisposedException("StreamWriter");\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
+                               Flush ();\r
                }\r
 \r
-               public override void Write (char [] value)\r
+               public override void Write (char[] buffer)\r
                {\r
-                       Write (value, 0, value.Length);\r
+                       if (DisposedAlready)\r
+                               throw new ObjectDisposedException ("StreamWriter");\r
+\r
+                       if (buffer != null)\r
+                               LowLevelWrite (buffer, 0, buffer.Length);\r
+                       if (iflush)\r
+                               Flush ();\r
                }\r
 \r
-               public override void Write(string value) {\r
+               public override void Write (string value) \r
+               {\r
                        if (DisposedAlready)\r
                                throw new ObjectDisposedException("StreamWriter");\r
 \r
                        if (value != null)\r
-                               Write (value.ToCharArray (), 0, value.Length);\r
+                               LowLevelWrite (value);\r
+                       \r
+                       if (iflush)\r
+                               Flush ();\r
                }\r
 \r
                public override void Close()\r
@@ -204,7 +316,8 @@ namespace System.IO {
                        Dispose (true);\r
                }\r
 \r
-               ~StreamWriter() {\r
+               ~StreamWriter ()\r
+               {\r
                        Dispose(false);\r
                }\r
        }\r