2004-08-13 Dick Porter <dick@ximian.com>
[mono.git] / mcs / class / corlib / System.IO / StreamWriter.cs
index d4ad8751cde2371b6c5a947abdb54db2d33982d2..117ab7f5d60d3956726125d94fccec22526b9832 100644 (file)
@@ -1,11 +1,35 @@
 //\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
+
+//
+// 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
@@ -24,27 +48,30 @@ namespace System.IO {
                \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 int byte_pos;\r
+               private char[] decode_buf;\r
+               private int decode_pos;\r
 \r
                private bool DisposedAlready = false;\r
+               private bool preamble_done = false;\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, 0);\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
 \r
                //[MonoTODO("Nothing is done with bufferSize")]\r
@@ -56,7 +83,7 @@ namespace System.IO {
                        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", "stream");\r
 \r
                        internalStream = stream;\r
 \r
@@ -64,10 +91,10 @@ 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
@@ -96,7 +123,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
@@ -111,6 +138,8 @@ namespace System.IO {
                                return iflush;\r
                        }\r
                        set {\r
+                               if (DisposedAlready)\r
+                                       throw new ObjectDisposedException("StreamWriter");\r
                                iflush = value;\r
                        }\r
                }\r
@@ -127,84 +156,141 @@ namespace System.IO {
                        }\r
                }\r
 \r
-               protected override void Dispose (bool disposing) {\r
+               protected override void Dispose (bool disposing) \r
+               {\r
                        if (!DisposedAlready && disposing && internalStream != null) {\r
-                               DisposedAlready = true;\r
                                Flush();\r
+                               DisposedAlready = true;\r
                                internalStream.Close ();\r
                        }\r
 \r
                        internalStream = null;\r
-                       TheBuffer = null;\r
+                       byte_buf = null;\r
                        internalEncoding = null;\r
+                       decode_buf = null;\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
-               public override void Write (char[] buffer, int index, int count) {\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
+               {\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
                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[] value)\r
                {\r
-                       Write (value, 0, value.Length);\r
+                       if (DisposedAlready)\r
+                               throw new ObjectDisposedException("StreamWriter");\r
+\r
+                       if (value != null)\r
+                               LowLevelWrite (value, 0, value.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.ToCharArray (), 0, value.Length);\r
+                       if (iflush)\r
+                               Flush ();\r
                }\r
 \r
                public override void Close()\r
                {\r
+                        closed = true;\r
                        Dispose (true);\r
                }\r
 \r
-               ~StreamWriter() {\r
+               ~StreamWriter ()\r
+               {\r
                        Dispose(false);\r
                }\r
        }\r