* roottypes.cs: Rename from tree.cs.
[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
76                         // Fixes bug http://bugzilla.ximian.com/show_bug.cgi?id=74513
77                         if (internalStream.CanSeek && internalStream.Position > 0)
78                                 preamble_done = true;
79                 }\r
80 \r
81                 //[MonoTODO("Nothing is done with bufferSize")]\r
82                 public StreamWriter (Stream stream, Encoding encoding, int bufferSize) {\r
83                         if (null == stream)\r
84                                 throw new ArgumentNullException("stream");\r
85                         if (null == encoding)\r
86                                 throw new ArgumentNullException("encoding");\r
87                         if (bufferSize < 0)\r
88                                 throw new ArgumentOutOfRangeException("bufferSize");\r
89                         if (!stream.CanWrite)\r
90                                 throw new ArgumentException("Can not write to stream", "stream");\r
91 \r
92                         internalStream = stream;\r
93 \r
94                         Initialize(encoding, bufferSize);\r
95                 }\r
96 \r
97                 public StreamWriter (string path)\r
98                         : this (path, false, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}\r
99 \r
100                 public StreamWriter (string path, bool append)\r
101                         : this (path, append, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}\r
102 \r
103                 public StreamWriter (string path, bool append, Encoding encoding)\r
104                         : this (path, append, encoding, DefaultFileBufferSize) {}\r
105                 \r
106                 public StreamWriter (string path, bool append, Encoding encoding, int bufferSize) {\r
107                         if (null == path)\r
108                                 throw new ArgumentNullException("path");\r
109                         if (String.Empty == path)\r
110                                 throw new ArgumentException("path cannot be empty string");\r
111                         if (path.IndexOfAny (Path.InvalidPathChars) != -1)\r
112                                 throw new ArgumentException("path contains invalid characters");\r
113 \r
114                         if (null == encoding)\r
115                                 throw new ArgumentNullException("encoding");\r
116                         if (bufferSize < 0)\r
117                                 throw new ArgumentOutOfRangeException("bufferSize");\r
118 \r
119                         string DirName = Path.GetDirectoryName(path);\r
120                         if (DirName != String.Empty && !Directory.Exists(DirName))\r
121                                 throw new DirectoryNotFoundException();\r
122 \r
123                         FileMode mode;\r
124 \r
125                         if (append)\r
126                                 mode = FileMode.Append;\r
127                         else\r
128                                 mode = FileMode.Create;\r
129                         \r
130                         internalStream = new FileStream (path, mode, FileAccess.Write, FileShare.Read);\r
131 \r
132                         if (append)\r
133                                 internalStream.Position = internalStream.Length;\r
134                         else\r
135                                 internalStream.SetLength (0);\r
136 \r
137                         Initialize(encoding, bufferSize);\r
138                 }\r
139 \r
140                 public virtual bool AutoFlush {\r
141                         get {\r
142                                 return iflush;\r
143                         }\r
144                         set {
145                                 if (DisposedAlready)
146                                         throw new ObjectDisposedException("StreamWriter");
147                                 iflush = value;
148
149                                 if (iflush) {
150                                         Flush ();
151                                 }
152                         }
153                 }
154 \r
155                 public virtual Stream BaseStream {\r
156                         get {\r
157                                 return internalStream;\r
158                         }\r
159                 }\r
160 \r
161                 public override Encoding Encoding {\r
162                         get {\r
163                                 return internalEncoding;\r
164                         }\r
165                 }\r
166 \r
167                 protected override void Dispose (bool disposing) \r
168                 {\r
169                         if (!DisposedAlready && disposing && internalStream != null) {\r
170                                 Flush();\r
171                                 DisposedAlready = true;\r
172                                 internalStream.Close ();\r
173                         }\r
174 \r
175                         internalStream = null;\r
176                         byte_buf = null;\r
177                         internalEncoding = null;\r
178                         decode_buf = null;\r
179                 }\r
180 \r
181                 public override void Flush ()\r
182                 {\r
183                         if (DisposedAlready)\r
184                                 throw new ObjectDisposedException("StreamWriter");\r
185 \r
186                         Decode ();\r
187                         if (byte_pos > 0) {\r
188                                 FlushBytes ();\r
189                                 internalStream.Flush ();\r
190                         }\r
191                 }\r
192 \r
193                 // how the speedup works:\r
194                 // the Write () methods simply copy the characters in a buffer of chars (decode_buf)\r
195                 // Decode () is called when the buffer is full or we need to flash.\r
196                 // Decode () will use the encoding to get the bytes and but them inside\r
197                 // byte_buf. From byte_buf the data is finally outputted to the stream.\r
198                 void FlushBytes () \r
199                 {\r
200                         // write the encoding preamble only at the start of the stream\r
201                         if (!preamble_done && byte_pos > 0) {\r
202                                 byte[] preamble = internalEncoding.GetPreamble ();\r
203                                 if (preamble.Length > 0)\r
204                                         internalStream.Write (preamble, 0, preamble.Length);\r
205                                 preamble_done = true;\r
206                         }\r
207                         internalStream.Write (byte_buf, 0, byte_pos);\r
208                         byte_pos = 0;\r
209                 }\r
210                 \r
211                 void Decode () \r
212                 {\r
213                         if (byte_pos > 0)\r
214                                 FlushBytes ();\r
215                         if (decode_pos > 0) {\r
216                                 int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);\r
217                                 byte_pos += len;\r
218                                 decode_pos = 0;\r
219                         }\r
220                 }\r
221                 \r
222                 public override void Write (char[] buffer, int index, int count) \r
223                 {\r
224                         if (DisposedAlready)\r
225                                 throw new ObjectDisposedException("StreamWriter");\r
226                         if (buffer == null)\r
227                                 throw new ArgumentNullException ("buffer");\r
228                         if (index < 0)\r
229                                 throw new ArgumentOutOfRangeException ("index", "< 0");\r
230                         if (count < 0)\r
231                                 throw new ArgumentOutOfRangeException ("count", "< 0");\r
232                         // re-ordered to avoid possible integer overflow\r
233                         if (index > buffer.Length - count)\r
234                                 throw new ArgumentException ("index + count > buffer.Length");\r
235 \r
236                         LowLevelWrite (buffer, index, count);\r
237                         if (iflush)\r
238                                 Flush();\r
239                 }\r
240                 \r
241                 void LowLevelWrite (char[] buffer, int index, int count)\r
242                 {\r
243                         while (count > 0) {\r
244                                 int todo = decode_buf.Length - decode_pos;\r
245                                 if (todo == 0) {\r
246                                         Decode ();\r
247                                         todo = decode_buf.Length;\r
248                                 }\r
249                                 if (todo > count)\r
250                                         todo = count;\r
251                                 Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);\r
252                                 count -= todo;\r
253                                 index += todo;\r
254                                 decode_pos += todo;\r
255                         }\r
256                 }
257                 
258                 void LowLevelWrite (string s)
259                 {
260                         int count = s.Length;
261                         int index = 0;
262                         while (count > 0) {
263                                 int todo = decode_buf.Length - decode_pos;
264                                 if (todo == 0) {
265                                         Decode ();
266                                         todo = decode_buf.Length;
267                                 }
268                                 if (todo > count)
269                                         todo = count;
270                                 
271                                 for (int i = 0; i < todo; i ++)
272                                         decode_buf [i + decode_pos] = s [i + index];
273                                 
274                                 count -= todo;
275                                 index += todo;
276                                 decode_pos += todo;
277                         }
278                 }\r
279 \r
280                 public override void Write (char value)\r
281                 {\r
282                         if (DisposedAlready)\r
283                                 throw new ObjectDisposedException("StreamWriter");\r
284 \r
285                         // the size of decode_buf is always > 0 and\r
286                         // we check for overflow right away\r
287                         if (decode_pos >= decode_buf.Length)\r
288                                 Decode ();\r
289                         decode_buf [decode_pos++] = value;\r
290                         if (iflush)\r
291                                 Flush ();\r
292                 }\r
293 \r
294                 public override void Write (char[] value)\r
295                 {\r
296                         if (DisposedAlready)\r
297                                 throw new ObjectDisposedException("StreamWriter");\r
298 \r
299                         if (value != null)\r
300                                 LowLevelWrite (value, 0, value.Length);\r
301                         if (iflush)\r
302                                 Flush ();\r
303                 }\r
304 \r
305                 public override void Write (string value) \r
306                 {\r
307                         if (DisposedAlready)\r
308                                 throw new ObjectDisposedException("StreamWriter");\r
309 \r
310                         if (value != null)\r
311                                 LowLevelWrite (value);
312                         \r
313                         if (iflush)\r
314                                 Flush ();\r
315                 }\r
316 \r
317                 public override void Close()\r
318                 {\r
319                         closed = true;\r
320                         Dispose (true);\r
321                 }\r
322 \r
323                 ~StreamWriter ()\r
324                 {\r
325                         Dispose(false);\r
326                 }\r
327         }\r
328 }\r