2004-08-13 Dick Porter <dick@ximian.com>
[mono.git] / mcs / class / corlib / System.IO / StreamWriter.cs
index f7243a8fc0c209603a6cadc4cb0efaf7e15c1933..117ab7f5d60d3956726125d94fccec22526b9832 100644 (file)
@@ -1,36 +1,81 @@
 //\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
 \r
 namespace System.IO {\r
        \r
-               [Serializable]\r
-        public class StreamWriter : TextWriter {\r
+       [Serializable]\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
-                // new public static readonly StreamWriter Null;\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 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.UTF8Unmarked, 0);\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
-               [MonoTODO("Nothing is done with bufferSize")]\r
-               public StreamWriter (Stream stream, Encoding encoding, int bufferSize)\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
+\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
@@ -38,32 +83,39 @@ 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
-                       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
+                       : this (path, append, encoding, DefaultFileBufferSize) {}\r
                \r
-               public StreamWriter (string path, bool append, Encoding encoding, int bufferSize)\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
                                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
@@ -71,77 +123,175 @@ 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
+                               if (DisposedAlready)\r
+                                       throw new ObjectDisposedException("StreamWriter");\r
                                iflush = value;\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
+                       if (!DisposedAlready && disposing && internalStream != null) {\r
+                               Flush();\r
+                               DisposedAlready = true;\r
                                internalStream.Close ();\r
-                               internalStream = null;\r
                        }\r
+\r
+                       internalStream = null;\r
+                       byte_buf = null;\r
+                       internalEncoding = null;\r
+                       decode_buf = null;\r
                }\r
 \r
                public override void Flush ()\r
                {\r
-                       internalStream.Flush ();\r
+                       if (DisposedAlready)\r
+                               throw new ObjectDisposedException("StreamWriter");\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
-               public override void Write (char[] buffer, int index, int count)\r
+               public override void Write (char[] buffer, int index, int count) \r
                {\r
-                       byte[] res = new byte [internalEncoding.GetMaxByteCount (buffer.Length)];\r
-                       int len;\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
-                       len = internalEncoding.GetBytes (buffer, index, count, res, 0);\r
+                       LowLevelWrite (buffer, index, count);\r
+                       if (iflush)\r
+                               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
-                       internalStream.Write (res, 0, len);\r
+               public override void Write (char value)\r
+               {\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
+               {\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
 \r
-               public override void Write(string value)\r
+               public override void Write (string value) \r
                {\r
-                       Write (value.ToCharArray (), 0, value.Length);\r
+                       if (DisposedAlready)\r
+                               throw new ObjectDisposedException("StreamWriter");\r
+\r
+                       if (value != null)\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
-                         \r
-        }\r
+               ~StreamWriter ()\r
+               {\r
+                       Dispose(false);\r
+               }\r
+       }\r
 }\r
-                        \r
-                        \r