2005-02-06 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / class / corlib / System.IO / StreamWriter.cs
1 //\r
2 // System.IO.StreamWriter.cs\r
3 //\r
4 // Authors:\r
5 //   Dietmar Maurer (dietmar@ximian.com)\r
6 //   Paolo Molaro (lupus@ximian.com)\r
7 //\r
8 // (C) Ximian, Inc.  http://www.ximian.com\r
9 //\r
10
11 //
12 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33 \r
34 using System.Text;\r
35 using System;\r
36 \r
37 namespace System.IO {\r
38         \r
39         [Serializable]\r
40         public class StreamWriter : TextWriter {\r
41 \r
42                 private Encoding internalEncoding;\r
43 \r
44                 private Stream internalStream;\r
45                 private bool closed = false;\r
46 \r
47                 private bool iflush;\r
48                 \r
49                 private const int DefaultBufferSize = 1024;\r
50                 private const int DefaultFileBufferSize = 4096;\r
51                 private const int MinimumBufferSize = 256;\r
52 \r
53                 private byte[] byte_buf;\r
54                 private int byte_pos;\r
55                 private char[] decode_buf;\r
56                 private int decode_pos;\r
57 \r
58                 private bool DisposedAlready = false;\r
59                 private bool preamble_done = false;\r
60 \r
61                 public new static readonly StreamWriter Null = new StreamWriter (Stream.Null, Encoding.UTF8Unmarked, 0);\r
62 \r
63                 public StreamWriter (Stream stream)\r
64                         : this (stream, Encoding.UTF8Unmarked, DefaultBufferSize) {}\r
65 \r
66                 public StreamWriter (Stream stream, Encoding encoding)\r
67                         : this (stream, encoding, DefaultBufferSize) {}\r
68 \r
69                 internal void Initialize(Encoding encoding, int bufferSize) {\r
70                         internalEncoding = encoding;\r
71                         decode_pos = byte_pos = 0;\r
72                         int BufferSize = Math.Max(bufferSize, MinimumBufferSize);\r
73                         decode_buf = new char [BufferSize];\r
74                         byte_buf = new byte [encoding.GetMaxByteCount (BufferSize)];\r
75                 }\r
76 \r
77                 //[MonoTODO("Nothing is done with bufferSize")]\r
78                 public StreamWriter (Stream stream, Encoding encoding, int bufferSize) {\r
79                         if (null == stream)\r
80                                 throw new ArgumentNullException("stream");\r
81                         if (null == encoding)\r
82                                 throw new ArgumentNullException("encoding");\r
83                         if (bufferSize < 0)\r
84                                 throw new ArgumentOutOfRangeException("bufferSize");\r
85                         if (!stream.CanWrite)\r
86                                 throw new ArgumentException("Can not write to stream", "stream");\r
87 \r
88                         internalStream = stream;\r
89 \r
90                         Initialize(encoding, bufferSize);\r
91                 }\r
92 \r
93                 public StreamWriter (string path)\r
94                         : this (path, false, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}\r
95 \r
96                 public StreamWriter (string path, bool append)\r
97                         : this (path, append, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}\r
98 \r
99                 public StreamWriter (string path, bool append, Encoding encoding)\r
100                         : this (path, append, encoding, DefaultFileBufferSize) {}\r
101                 \r
102                 public StreamWriter (string path, bool append, Encoding encoding, int bufferSize) {\r
103                         if (null == path)\r
104                                 throw new ArgumentNullException("path");\r
105                         if (String.Empty == path)\r
106                                 throw new ArgumentException("path cannot be empty string");\r
107                         if (path.IndexOfAny (Path.InvalidPathChars) != -1)\r
108                                 throw new ArgumentException("path contains invalid characters");\r
109 \r
110                         if (null == encoding)\r
111                                 throw new ArgumentNullException("encoding");\r
112                         if (bufferSize < 0)\r
113                                 throw new ArgumentOutOfRangeException("bufferSize");\r
114 \r
115                         string DirName = Path.GetDirectoryName(path);\r
116                         if (DirName != String.Empty && !Directory.Exists(DirName))\r
117                                 throw new DirectoryNotFoundException();\r
118 \r
119                         FileMode mode;\r
120 \r
121                         if (append)\r
122                                 mode = FileMode.Append;\r
123                         else\r
124                                 mode = FileMode.Create;\r
125                         \r
126                         internalStream = new FileStream (path, mode, FileAccess.Write, FileShare.Read);\r
127 \r
128                         if (append)\r
129                                 internalStream.Position = internalStream.Length;\r
130                         else\r
131                                 internalStream.SetLength (0);\r
132 \r
133                         Initialize(encoding, bufferSize);\r
134                 }\r
135 \r
136                 public virtual bool AutoFlush {\r
137                         get {\r
138                                 return iflush;\r
139                         }\r
140                         set {
141                                 if (DisposedAlready)
142                                         throw new ObjectDisposedException("StreamWriter");
143                                 iflush = value;
144
145                                 if (iflush) {
146                                         Flush ();
147                                 }
148                         }
149                 }
150 \r
151                 public virtual Stream BaseStream {\r
152                         get {\r
153                                 return internalStream;\r
154                         }\r
155                 }\r
156 \r
157                 public override Encoding Encoding {\r
158                         get {\r
159                                 return internalEncoding;\r
160                         }\r
161                 }\r
162 \r
163                 protected override void Dispose (bool disposing) \r
164                 {\r
165                         if (!DisposedAlready && disposing && internalStream != null) {\r
166                                 Flush();\r
167                                 DisposedAlready = true;\r
168                                 internalStream.Close ();\r
169                         }\r
170 \r
171                         internalStream = null;\r
172                         byte_buf = null;\r
173                         internalEncoding = null;\r
174                         decode_buf = null;\r
175                 }\r
176 \r
177                 public override void Flush ()\r
178                 {\r
179                         if (DisposedAlready)\r
180                                 throw new ObjectDisposedException("StreamWriter");\r
181 \r
182                         Decode ();\r
183                         if (byte_pos > 0) {\r
184                                 FlushBytes ();\r
185                                 internalStream.Flush ();\r
186                         }\r
187                 }\r
188 \r
189                 // how the speedup works:\r
190                 // the Write () methods simply copy the characters in a buffer of chars (decode_buf)\r
191                 // Decode () is called when the buffer is full or we need to flash.\r
192                 // Decode () will use the encoding to get the bytes and but them inside\r
193                 // byte_buf. From byte_buf the data is finally outputted to the stream.\r
194                 void FlushBytes () \r
195                 {\r
196                         // write the encoding preamble only at the start of the stream\r
197                         if (!preamble_done && byte_pos > 0) {\r
198                                 byte[] preamble = internalEncoding.GetPreamble ();\r
199                                 if (preamble.Length > 0)\r
200                                         internalStream.Write (preamble, 0, preamble.Length);\r
201                                 preamble_done = true;\r
202                         }\r
203                         internalStream.Write (byte_buf, 0, byte_pos);\r
204                         byte_pos = 0;\r
205                 }\r
206                 \r
207                 void Decode () \r
208                 {\r
209                         if (byte_pos > 0)\r
210                                 FlushBytes ();\r
211                         if (decode_pos > 0) {\r
212                                 int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);\r
213                                 byte_pos += len;\r
214                                 decode_pos = 0;\r
215                         }\r
216                 }\r
217                 \r
218                 public override void Write (char[] buffer, int index, int count) \r
219                 {\r
220                         if (DisposedAlready)\r
221                                 throw new ObjectDisposedException("StreamWriter");\r
222                         if (buffer == null)\r
223                                 throw new ArgumentNullException ("buffer");\r
224                         if (index < 0)\r
225                                 throw new ArgumentOutOfRangeException ("index", "< 0");\r
226                         if (count < 0)\r
227                                 throw new ArgumentOutOfRangeException ("count", "< 0");\r
228                         // re-ordered to avoid possible integer overflow\r
229                         if (index > buffer.Length - count)\r
230                                 throw new ArgumentException ("index + count > buffer.Length");\r
231 \r
232                         LowLevelWrite (buffer, index, count);\r
233                         if (iflush)\r
234                                 Flush();\r
235                 }\r
236                 \r
237                 void LowLevelWrite (char[] buffer, int index, int count)\r
238                 {\r
239                         while (count > 0) {\r
240                                 int todo = decode_buf.Length - decode_pos;\r
241                                 if (todo == 0) {\r
242                                         Decode ();\r
243                                         todo = decode_buf.Length;\r
244                                 }\r
245                                 if (todo > count)\r
246                                         todo = count;\r
247                                 Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);\r
248                                 count -= todo;\r
249                                 index += todo;\r
250                                 decode_pos += todo;\r
251                         }\r
252                 }
253                 
254                 void LowLevelWrite (string s)
255                 {
256                         int count = s.Length;
257                         int index = 0;
258                         while (count > 0) {
259                                 int todo = decode_buf.Length - decode_pos;
260                                 if (todo == 0) {
261                                         Decode ();
262                                         todo = decode_buf.Length;
263                                 }
264                                 if (todo > count)
265                                         todo = count;
266                                 
267                                 for (int i = 0; i < todo; i ++)
268                                         decode_buf [i + decode_pos] = s [i + index];
269                                 
270                                 count -= todo;
271                                 index += todo;
272                                 decode_pos += todo;
273                         }
274                 }\r
275 \r
276                 public override void Write (char value)\r
277                 {\r
278                         if (DisposedAlready)\r
279                                 throw new ObjectDisposedException("StreamWriter");\r
280 \r
281                         // the size of decode_buf is always > 0 and\r
282                         // we check for overflow right away\r
283                         if (decode_pos >= decode_buf.Length)\r
284                                 Decode ();\r
285                         decode_buf [decode_pos++] = value;\r
286                         if (iflush)\r
287                                 Flush ();\r
288                 }\r
289 \r
290                 public override void Write (char[] value)\r
291                 {\r
292                         if (DisposedAlready)\r
293                                 throw new ObjectDisposedException("StreamWriter");\r
294 \r
295                         if (value != null)\r
296                                 LowLevelWrite (value, 0, value.Length);\r
297                         if (iflush)\r
298                                 Flush ();\r
299                 }\r
300 \r
301                 public override void Write (string value) \r
302                 {\r
303                         if (DisposedAlready)\r
304                                 throw new ObjectDisposedException("StreamWriter");\r
305 \r
306                         if (value != null)\r
307                                 LowLevelWrite (value);
308                         \r
309                         if (iflush)\r
310                                 Flush ();\r
311                 }\r
312 \r
313                 public override void Close()\r
314                 {\r
315                         closed = true;\r
316                         Dispose (true);\r
317                 }\r
318 \r
319                 ~StreamWriter ()\r
320                 {\r
321                         Dispose(false);\r
322                 }\r
323         }\r
324 }\r