minor fix for bug 9520:
[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 //   Marek Safar (marek.safar@gmail.com)\r
8 //\r
9 // (C) Ximian, Inc.  http://www.ximian.com\r
10 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)\r
11 // Copyright 2011, 2013 Xamarin Inc.\r
12 //\r
13 // Permission is hereby granted, free of charge, to any person obtaining\r
14 // a copy of this software and associated documentation files (the\r
15 // "Software"), to deal in the Software without restriction, including\r
16 // without limitation the rights to use, copy, modify, merge, publish,\r
17 // distribute, sublicense, and/or sell copies of the Software, and to\r
18 // permit persons to whom the Software is furnished to do so, subject to\r
19 // the following conditions:\r
20 // \r
21 // The above copyright notice and this permission notice shall be\r
22 // included in all copies or substantial portions of the Software.\r
23 // \r
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\r
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\r
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\r
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
31 //\r
32 \r
33 using System.Text;\r
34 using System.Runtime.InteropServices;\r
35 #if NET_4_5\r
36 using System.Threading.Tasks;\r
37 #endif\r
38 \r
39 namespace System.IO {\r
40         \r
41         [Serializable]\r
42         [ComVisible (true)]\r
43         public class StreamWriter : TextWriter {\r
44 \r
45                 private Encoding internalEncoding;\r
46 \r
47                 private Stream internalStream;\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 char[] decode_buf;\r
55                 private int byte_pos;\r
56                 private int decode_pos;\r
57 \r
58                 private bool iflush;\r
59                 private bool preamble_done;\r
60 \r
61 #if NET_4_5\r
62                 readonly bool leave_open;\r
63                 IDecoupledTask async_task;\r
64 #endif\r
65 \r
66                 public new static readonly StreamWriter Null = new StreamWriter (Stream.Null, Encoding.UTF8Unmarked, 1);\r
67 \r
68                 public StreamWriter (Stream stream)\r
69                         : this (stream, Encoding.UTF8Unmarked, DefaultBufferSize) {}\r
70 \r
71                 public StreamWriter (Stream stream, Encoding encoding)\r
72                         : this (stream, encoding, DefaultBufferSize) {}\r
73 \r
74                 internal void Initialize(Encoding encoding, int bufferSize) {\r
75                         internalEncoding = encoding;\r
76                         decode_pos = byte_pos = 0;\r
77                         int BufferSize = Math.Max(bufferSize, MinimumBufferSize);\r
78                         decode_buf = new char [BufferSize];\r
79                         byte_buf = new byte [encoding.GetMaxByteCount (BufferSize)];\r
80 \r
81                         // Fixes bug http://bugzilla.ximian.com/show_bug.cgi?id=74513\r
82                         if (internalStream.CanSeek && internalStream.Position > 0)\r
83                                 preamble_done = true;\r
84                 }\r
85 \r
86 #if NET_4_5\r
87                 public StreamWriter (Stream stream, Encoding encoding, int bufferSize)\r
88                         : this (stream, encoding, bufferSize, false)\r
89                 {\r
90                 }\r
91                 \r
92                 public StreamWriter (Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)\r
93 #else\r
94                 const bool leave_open = false;\r
95 \r
96                 public StreamWriter (Stream stream, Encoding encoding, int bufferSize)\r
97 #endif\r
98                 {\r
99                         if (null == stream)\r
100                                 throw new ArgumentNullException("stream");\r
101                         if (null == encoding)\r
102                                 throw new ArgumentNullException("encoding");\r
103                         if (bufferSize <= 0)\r
104                                 throw new ArgumentOutOfRangeException("bufferSize");\r
105                         if (!stream.CanWrite)\r
106                                 throw new ArgumentException ("Can not write to stream");\r
107 \r
108 #if NET_4_5\r
109                         leave_open = leaveOpen;\r
110 #endif\r
111                         internalStream = stream;\r
112 \r
113                         Initialize(encoding, bufferSize);\r
114                 }\r
115 \r
116                 public StreamWriter (string path)\r
117                         : this (path, false, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}\r
118 \r
119                 public StreamWriter (string path, bool append)\r
120                         : this (path, append, Encoding.UTF8Unmarked, DefaultFileBufferSize) {}\r
121 \r
122                 public StreamWriter (string path, bool append, Encoding encoding)\r
123                         : this (path, append, encoding, DefaultFileBufferSize) {}\r
124 \r
125                 public StreamWriter (string path, bool append, Encoding encoding, int bufferSize)\r
126                 {\r
127                         if (null == encoding)\r
128                                 throw new ArgumentNullException("encoding");\r
129                         if (bufferSize <= 0)\r
130                                 throw new ArgumentOutOfRangeException("bufferSize");\r
131 \r
132                         FileMode mode;\r
133 \r
134                         if (append)\r
135                                 mode = FileMode.Append;\r
136                         else\r
137                                 mode = FileMode.Create;\r
138                         \r
139                         internalStream = new FileStream (path, mode, FileAccess.Write, FileShare.Read);\r
140 \r
141                         if (append)\r
142                                 internalStream.Position = internalStream.Length;\r
143                         else\r
144                                 internalStream.SetLength (0);\r
145 \r
146                         Initialize(encoding, bufferSize);\r
147                 }\r
148 \r
149                 public virtual bool AutoFlush {\r
150                         get {\r
151                                 return iflush;\r
152                         }\r
153                         set {\r
154                                 iflush = value;\r
155                                 if (iflush)\r
156                                         Flush ();\r
157                         }\r
158                 }\r
159 \r
160                 public virtual Stream BaseStream {\r
161                         get {\r
162                                 return internalStream;\r
163                         }\r
164                 }\r
165 \r
166                 public override Encoding Encoding {\r
167                         get {\r
168                                 return internalEncoding;\r
169                         }\r
170                 }\r
171 \r
172                 protected override void Dispose (bool disposing) \r
173                 {\r
174                         if (byte_buf == null || !disposing)\r
175                                 return;\r
176 \r
177                         try {\r
178                                 Flush ();\r
179                         } finally {\r
180                                 byte_buf = null;\r
181                                 internalEncoding = null;\r
182                                 decode_buf = null;\r
183 \r
184                                 if (!leave_open) {\r
185                                         internalStream.Close ();\r
186                                 }\r
187 \r
188                                 internalStream = null;\r
189                         }\r
190                 }\r
191 \r
192                 public override void Flush ()\r
193                 {\r
194                         CheckState ();\r
195                         FlushCore ();\r
196                 }\r
197 \r
198                 // Keep in sync with FlushCoreAsync\r
199                 void FlushCore ()\r
200                 {\r
201                         Decode ();\r
202                         if (byte_pos > 0) {\r
203                                 FlushBytes ();\r
204                                 internalStream.Flush ();\r
205                         }\r
206                 }\r
207 \r
208                 // how the speedup works:\r
209                 // the Write () methods simply copy the characters in a buffer of chars (decode_buf)\r
210                 // Decode () is called when the buffer is full or we need to flash.\r
211                 // Decode () will use the encoding to get the bytes and but them inside\r
212                 // byte_buf. From byte_buf the data is finally outputted to the stream.\r
213                 void FlushBytes () \r
214                 {\r
215                         // write the encoding preamble only at the start of the stream\r
216                         if (!preamble_done && byte_pos > 0) {\r
217                                 byte[] preamble = internalEncoding.GetPreamble ();\r
218                                 if (preamble.Length > 0)\r
219                                         internalStream.Write (preamble, 0, preamble.Length);\r
220                                 preamble_done = true;\r
221                         }\r
222                         internalStream.Write (byte_buf, 0, byte_pos);\r
223                         byte_pos = 0;\r
224                 }\r
225 \r
226                 void Decode () \r
227                 {\r
228                         if (byte_pos > 0)\r
229                                 FlushBytes ();\r
230                         if (decode_pos > 0) {\r
231                                 int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);\r
232                                 byte_pos += len;\r
233                                 decode_pos = 0;\r
234                         }\r
235                 }\r
236 \r
237 #if NET_4_5\r
238                 async Task FlushCoreAsync ()\r
239                 {\r
240                         await DecodeAsync ().ConfigureAwait (false);\r
241                         if (byte_pos > 0) {\r
242                                 await FlushBytesAsync ().ConfigureAwait (false);\r
243                                 await internalStream.FlushAsync ().ConfigureAwait (false);\r
244                         }\r
245                 }\r
246 \r
247                 async Task FlushBytesAsync ()\r
248                 {\r
249                         // write the encoding preamble only at the start of the stream\r
250                         if (!preamble_done && byte_pos > 0) {\r
251                                 byte[] preamble = internalEncoding.GetPreamble ();\r
252                                 if (preamble.Length > 0)\r
253                                         await internalStream.WriteAsync (preamble, 0, preamble.Length).ConfigureAwait (false);\r
254                                 preamble_done = true;\r
255                         }\r
256 \r
257                         await internalStream.WriteAsync (byte_buf, 0, byte_pos).ConfigureAwait (false);\r
258                         byte_pos = 0;\r
259                 }\r
260 \r
261                 async Task DecodeAsync () \r
262                 {\r
263                         if (byte_pos > 0)\r
264                                 await FlushBytesAsync ().ConfigureAwait (false);\r
265                         if (decode_pos > 0) {\r
266                                 int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);\r
267                                 byte_pos += len;\r
268                                 decode_pos = 0;\r
269                         }\r
270                 }               \r
271 #endif\r
272 \r
273                 public override void Write (char[] buffer, int index, int count) \r
274                 {\r
275                         if (buffer == null)\r
276                                 throw new ArgumentNullException ("buffer");\r
277                         if (index < 0)\r
278                                 throw new ArgumentOutOfRangeException ("index", "< 0");\r
279                         if (count < 0)\r
280                                 throw new ArgumentOutOfRangeException ("count", "< 0");\r
281                         // re-ordered to avoid possible integer overflow\r
282                         if (index > buffer.Length - count)\r
283                                 throw new ArgumentException ("index + count > buffer.Length");\r
284 \r
285                         CheckState ();\r
286 \r
287                         LowLevelWrite (buffer, index, count);\r
288                         if (iflush)\r
289                                 FlushCore ();\r
290                 }\r
291                 \r
292                 void LowLevelWrite (char[] buffer, int index, int count)\r
293                 {\r
294                         while (count > 0) {\r
295                                 int todo = decode_buf.Length - decode_pos;\r
296                                 if (todo == 0) {\r
297                                         Decode ();\r
298                                         todo = decode_buf.Length;\r
299                                 }\r
300                                 if (todo > count)\r
301                                         todo = count;\r
302                                 Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);\r
303                                 count -= todo;\r
304                                 index += todo;\r
305                                 decode_pos += todo;\r
306                         }\r
307                 }\r
308                 \r
309                 void LowLevelWrite (string s)\r
310                 {\r
311                         int count = s.Length;\r
312                         int index = 0;\r
313                         while (count > 0) {\r
314                                 int todo = decode_buf.Length - decode_pos;\r
315                                 if (todo == 0) {\r
316                                         Decode ();\r
317                                         todo = decode_buf.Length;\r
318                                 }\r
319                                 if (todo > count)\r
320                                         todo = count;\r
321                                 \r
322                                 for (int i = 0; i < todo; i ++)\r
323                                         decode_buf [i + decode_pos] = s [i + index];\r
324                                 \r
325                                 count -= todo;\r
326                                 index += todo;\r
327                                 decode_pos += todo;\r
328                         }\r
329                 }\r
330 \r
331                 public override void Write (char value)\r
332                 {\r
333                         CheckState ();\r
334 \r
335                         // the size of decode_buf is always > 0 and\r
336                         // we check for overflow right away\r
337                         if (decode_pos >= decode_buf.Length)\r
338                                 Decode ();\r
339                         decode_buf [decode_pos++] = value;\r
340                         if (iflush)\r
341                                 FlushCore ();\r
342                 }\r
343 \r
344                 public override void Write (char[] buffer)\r
345                 {\r
346                         CheckState ();\r
347 \r
348                         if (buffer != null)\r
349                                 LowLevelWrite (buffer, 0, buffer.Length);\r
350                         if (iflush)\r
351                                 FlushCore ();\r
352                 }\r
353 \r
354                 public override void Write (string value) \r
355                 {\r
356                         CheckState ();\r
357 \r
358                         if (value != null)\r
359                                 LowLevelWrite (value);\r
360                         \r
361                         if (iflush)\r
362                                 FlushCore ();\r
363                 }\r
364 \r
365                 public override void Close()\r
366                 {\r
367                         Dispose (true);\r
368                 }\r
369 \r
370                 void CheckState ()\r
371                 {\r
372                         if (byte_buf == null)\r
373                                 throw new ObjectDisposedException ("StreamWriter");\r
374 \r
375 #if NET_4_5\r
376                         if (async_task != null && !async_task.IsCompleted)\r
377                                 throw new InvalidOperationException ();\r
378 #endif\r
379                 }\r
380 \r
381 #if NET_4_5\r
382                 public override Task FlushAsync ()\r
383                 {\r
384                         CheckState ();\r
385                         DecoupledTask res;\r
386                         async_task = res = new DecoupledTask (FlushCoreAsync ());\r
387                         return res.Task;\r
388                 }\r
389 \r
390                 public override Task WriteAsync (char value)\r
391                 {\r
392                         CheckState ();\r
393 \r
394                         DecoupledTask res;\r
395                         async_task = res = new DecoupledTask (WriteAsyncCore (value));\r
396                         return res.Task;\r
397                 }\r
398 \r
399                 async Task WriteAsyncCore (char value)\r
400                 {\r
401                         // the size of decode_buf is always > 0 and\r
402                         // we check for overflow right away\r
403                         if (decode_pos >= decode_buf.Length)\r
404                                 await DecodeAsync ().ConfigureAwait (false);\r
405                         decode_buf [decode_pos++] = value;\r
406 \r
407                         if (iflush)\r
408                                 await FlushCoreAsync ().ConfigureAwait (false);\r
409                 }\r
410 \r
411                 public override Task WriteAsync (char[] buffer, int index, int count)\r
412                 {\r
413                         CheckState ();\r
414                         if (buffer == null)\r
415                                 return TaskConstants.Finished;\r
416 \r
417                         DecoupledTask res;\r
418                         async_task = res = new DecoupledTask (WriteAsyncCore (buffer, index, count));\r
419                         return res.Task;\r
420                 }\r
421 \r
422                 async Task WriteAsyncCore (char[] buffer, int index, int count)\r
423                 {\r
424                         // Debug.Assert (buffer == null);\r
425 \r
426                         LowLevelWrite (buffer, 0, buffer.Length);\r
427 \r
428                         if (iflush)\r
429                                 await FlushCoreAsync ().ConfigureAwait (false);\r
430                 }\r
431 \r
432                 public override Task WriteAsync (string value)\r
433                 {\r
434                         CheckState ();\r
435                         DecoupledTask res;                      \r
436                         async_task = res = new DecoupledTask(base.WriteAsync (value));\r
437                         return res.Task;\r
438                 }\r
439 \r
440                 public override Task WriteLineAsync ()\r
441                 {\r
442                         CheckState ();\r
443                         DecoupledTask res;                      \r
444                         async_task = res = new DecoupledTask (base.WriteLineAsync ());\r
445                         return res.Task;\r
446                 }\r
447 \r
448                 public override Task WriteLineAsync (char value)\r
449                 {\r
450                         CheckState ();\r
451                         DecoupledTask res;\r
452                         async_task = res = new DecoupledTask (base.WriteLineAsync (value));\r
453                         return res.Task;\r
454                 }\r
455 \r
456                 public override Task WriteLineAsync (char[] buffer, int index, int count)\r
457                 {\r
458                         CheckState ();\r
459                         DecoupledTask res;\r
460                         async_task = res = new DecoupledTask (base.WriteLineAsync (buffer, index, count));\r
461                         return res.Task;\r
462                 }\r
463 \r
464                 public override Task WriteLineAsync (string value)\r
465                 {\r
466                         CheckState ();\r
467                         DecoupledTask res;                      \r
468                         async_task = res = new DecoupledTask (base.WriteLineAsync (value));\r
469                         return res.Task;\r
470                 }\r
471 #endif\r
472         }\r
473 }\r