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