Merge pull request #799 from kebby/master
[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                 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                 }\r
253                 \r
254                 void LowLevelWrite (string s)\r
255                 {\r
256                         int count = s.Length;\r
257                         int index = 0;\r
258                         while (count > 0) {\r
259                                 int todo = decode_buf.Length - decode_pos;\r
260                                 if (todo == 0) {\r
261                                         Decode ();\r
262                                         todo = decode_buf.Length;\r
263                                 }\r
264                                 if (todo > count)\r
265                                         todo = count;\r
266                                 \r
267                                 for (int i = 0; i < todo; i ++)\r
268                                         decode_buf [i + decode_pos] = s [i + index];\r
269                                 \r
270                                 count -= todo;\r
271                                 index += todo;\r
272                                 decode_pos += todo;\r
273                         }\r
274                 }               \r
275 \r
276 #if NET_4_5\r
277                 async Task FlushCoreAsync ()\r
278                 {\r
279                         await DecodeAsync ().ConfigureAwait (false);\r
280                         if (byte_pos > 0) {\r
281                                 await FlushBytesAsync ().ConfigureAwait (false);\r
282                                 await internalStream.FlushAsync ().ConfigureAwait (false);\r
283                         }\r
284                 }\r
285 \r
286                 async Task FlushBytesAsync ()\r
287                 {\r
288                         // write the encoding preamble only at the start of the stream\r
289                         if (!preamble_done && byte_pos > 0) {\r
290                                 byte[] preamble = internalEncoding.GetPreamble ();\r
291                                 if (preamble.Length > 0)\r
292                                         await internalStream.WriteAsync (preamble, 0, preamble.Length).ConfigureAwait (false);\r
293                                 preamble_done = true;\r
294                         }\r
295 \r
296                         await internalStream.WriteAsync (byte_buf, 0, byte_pos).ConfigureAwait (false);\r
297                         byte_pos = 0;\r
298                 }\r
299 \r
300                 async Task DecodeAsync () \r
301                 {\r
302                         if (byte_pos > 0)\r
303                                 await FlushBytesAsync ().ConfigureAwait (false);\r
304                         if (decode_pos > 0) {\r
305                                 int len = internalEncoding.GetBytes (decode_buf, 0, decode_pos, byte_buf, byte_pos);\r
306                                 byte_pos += len;\r
307                                 decode_pos = 0;\r
308                         }\r
309                 }               \r
310 \r
311                 async Task LowLevelWriteAsync (char[] buffer, int index, int count)\r
312                 {\r
313                         while (count > 0) {\r
314                                 int todo = decode_buf.Length - decode_pos;\r
315                                 if (todo == 0) {\r
316                                         await DecodeAsync ().ConfigureAwait (false);\r
317                                         todo = decode_buf.Length;\r
318                                 }\r
319                                 if (todo > count)\r
320                                         todo = count;\r
321                                 Buffer.BlockCopy (buffer, index * 2, decode_buf, decode_pos * 2, todo * 2);\r
322                                 count -= todo;\r
323                                 index += todo;\r
324                                 decode_pos += todo;\r
325                         }\r
326                 }\r
327                 \r
328                 async Task LowLevelWriteAsync (string s)\r
329                 {\r
330                         int count = s.Length;\r
331                         int index = 0;\r
332                         while (count > 0) {\r
333                                 int todo = decode_buf.Length - decode_pos;\r
334                                 if (todo == 0) {\r
335                                         await DecodeAsync ().ConfigureAwait (false);\r
336                                         todo = decode_buf.Length;\r
337                                 }\r
338                                 if (todo > count)\r
339                                         todo = count;\r
340                                 \r
341                                 for (int i = 0; i < todo; i ++)\r
342                                         decode_buf [i + decode_pos] = s [i + index];\r
343                                 \r
344                                 count -= todo;\r
345                                 index += todo;\r
346                                 decode_pos += todo;\r
347                         }\r
348                 }       \r
349 #endif\r
350 \r
351                 public override void Write (char[] buffer, int index, int count) \r
352                 {\r
353                         if (buffer == null)\r
354                                 throw new ArgumentNullException ("buffer");\r
355                         if (index < 0)\r
356                                 throw new ArgumentOutOfRangeException ("index", "< 0");\r
357                         if (count < 0)\r
358                                 throw new ArgumentOutOfRangeException ("count", "< 0");\r
359                         // re-ordered to avoid possible integer overflow\r
360                         if (index > buffer.Length - count)\r
361                                 throw new ArgumentException ("index + count > buffer.Length");\r
362 \r
363                         CheckState ();\r
364 \r
365                         LowLevelWrite (buffer, index, count);\r
366                         if (iflush)\r
367                                 FlushCore ();\r
368                 }\r
369                 \r
370                 public override void Write (char value)\r
371                 {\r
372                         CheckState ();\r
373 \r
374                         // the size of decode_buf is always > 0 and\r
375                         // we check for overflow right away\r
376                         if (decode_pos >= decode_buf.Length)\r
377                                 Decode ();\r
378                         decode_buf [decode_pos++] = value;\r
379                         if (iflush)\r
380                                 FlushCore ();\r
381                 }\r
382 \r
383                 public override void Write (char[] buffer)\r
384                 {\r
385                         CheckState ();\r
386 \r
387                         if (buffer != null)\r
388                                 LowLevelWrite (buffer, 0, buffer.Length);\r
389                         if (iflush)\r
390                                 FlushCore ();\r
391                 }\r
392 \r
393                 public override void Write (string value) \r
394                 {\r
395                         CheckState ();\r
396 \r
397                         if (value == null)\r
398                                 return;\r
399                         \r
400                         LowLevelWrite (value);\r
401                         \r
402                         if (iflush)\r
403                                 FlushCore ();\r
404                 }\r
405 \r
406                 public override void Close()\r
407                 {\r
408                         Dispose (true);\r
409                 }\r
410 \r
411                 void CheckState ()\r
412                 {\r
413                         if (byte_buf == null)\r
414                                 throw new ObjectDisposedException ("StreamWriter");\r
415 \r
416 #if NET_4_5\r
417                         if (async_task != null && !async_task.IsCompleted)\r
418                                 throw new InvalidOperationException ();\r
419 #endif\r
420                 }\r
421 \r
422 #if NET_4_5\r
423                 public override Task FlushAsync ()\r
424                 {\r
425                         CheckState ();\r
426                         DecoupledTask res;\r
427                         async_task = res = new DecoupledTask (FlushCoreAsync ());\r
428                         return res.Task;\r
429                 }\r
430 \r
431                 public override Task WriteAsync (char value)\r
432                 {\r
433                         CheckState ();\r
434 \r
435                         DecoupledTask res;\r
436                         async_task = res = new DecoupledTask (WriteAsyncCore (value));\r
437                         return res.Task;\r
438                 }\r
439 \r
440                 async Task WriteAsyncCore (char value)\r
441                 {\r
442                         // the size of decode_buf is always > 0 and\r
443                         // we check for overflow right away\r
444                         if (decode_pos >= decode_buf.Length)\r
445                                 await DecodeAsync ().ConfigureAwait (false);\r
446                         decode_buf [decode_pos++] = value;\r
447 \r
448                         if (iflush)\r
449                                 await FlushCoreAsync ().ConfigureAwait (false);\r
450                 }\r
451 \r
452                 public override Task WriteAsync (char[] buffer, int index, int count)\r
453                 {\r
454                         CheckState ();\r
455                         if (buffer == null)\r
456                                 return TaskConstants.Finished;\r
457 \r
458                         DecoupledTask res;\r
459                         async_task = res = new DecoupledTask (WriteAsyncCore (buffer, index, count));\r
460                         return res.Task;\r
461                 }\r
462 \r
463                 async Task WriteAsyncCore (char[] buffer, int index, int count)\r
464                 {\r
465                         // Debug.Assert (buffer == null);\r
466 \r
467                         await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false);\r
468 \r
469                         if (iflush)\r
470                                 await FlushCoreAsync ().ConfigureAwait (false);\r
471                 }\r
472 \r
473                 public override Task WriteAsync (string value)\r
474                 {\r
475                         CheckState ();\r
476 \r
477                         if (value == null)\r
478                                 return TaskConstants.Finished;\r
479 \r
480                         DecoupledTask res;                      \r
481                         async_task = res = new DecoupledTask (WriteAsyncCore (value, false));\r
482                         return res.Task;\r
483                 }\r
484 \r
485                 async Task WriteAsyncCore (string value, bool appendNewLine)\r
486                 {\r
487                         // Debug.Assert (value == null);\r
488 \r
489                         await LowLevelWriteAsync (value).ConfigureAwait (false);\r
490                         if (appendNewLine)\r
491                                 await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);\r
492                         \r
493                         if (iflush)\r
494                                 await FlushCoreAsync ().ConfigureAwait (false);\r
495                 }               \r
496 \r
497                 public override Task WriteLineAsync ()\r
498                 {\r
499                         CheckState ();\r
500 \r
501                         DecoupledTask res;\r
502                         async_task = res = new DecoupledTask (WriteAsyncCore (CoreNewLine, 0, CoreNewLine.Length));\r
503                         return res.Task;\r
504                 }\r
505 \r
506                 public override Task WriteLineAsync (char value)\r
507                 {\r
508                         CheckState ();\r
509                         DecoupledTask res;\r
510                         async_task = res = new DecoupledTask (WriteLineAsyncCore (value));\r
511                         return res.Task;\r
512                 }\r
513 \r
514                 async Task WriteLineAsyncCore (char value)\r
515                 {\r
516                         await WriteAsyncCore (value).ConfigureAwait (false);\r
517                         await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);\r
518                         \r
519                         if (iflush)\r
520                                 await FlushCoreAsync ().ConfigureAwait (false);\r
521                 }               \r
522 \r
523                 public override Task WriteLineAsync (char[] buffer, int index, int count)\r
524                 {\r
525                         if (buffer == null)\r
526                                 throw new ArgumentNullException ("buffer");\r
527                         if (index < 0)\r
528                                 throw new ArgumentOutOfRangeException ("index", "< 0");\r
529                         if (count < 0)\r
530                                 throw new ArgumentOutOfRangeException ("count", "< 0");\r
531                         // re-ordered to avoid possible integer overflow\r
532                         if (index > buffer.Length - count)\r
533                                 throw new ArgumentException ("index + count > buffer.Length");\r
534 \r
535                         CheckState ();\r
536                         DecoupledTask res;\r
537                         async_task = res = new DecoupledTask (WriteLineAsyncCore (buffer, index, count));\r
538                         return res.Task;\r
539                 }\r
540 \r
541                 async Task WriteLineAsyncCore (char[] buffer, int index, int count)\r
542                 {\r
543                         // Debug.Assert (buffer == null);\r
544 \r
545                         await LowLevelWriteAsync (buffer, index, count).ConfigureAwait (false);\r
546                         await LowLevelWriteAsync (CoreNewLine, 0, CoreNewLine.Length).ConfigureAwait (false);\r
547                         \r
548                         if (iflush)\r
549                                 await FlushCoreAsync ().ConfigureAwait (false);\r
550                 }               \r
551 \r
552                 public override Task WriteLineAsync (string value)\r
553                 {\r
554                         if (value == null)\r
555                                 return WriteLineAsync ();\r
556 \r
557                         CheckState ();\r
558                         DecoupledTask res;                      \r
559                         async_task = res = new DecoupledTask (WriteAsyncCore (value, true));\r
560                         return res.Task;\r
561                 }\r
562 #endif\r
563         }\r
564 }\r