11d02ec889923781b54b4587d48dc568719b869c
[mono.git] / mcs / class / corlib / System.IO / StreamReader.cs
1 //
2 // System.IO.StreamReader.cs
3 //
4 // Author:
5 //   Dietmar Maurer (dietmar@ximian.com)
6 //   Miguel de Icaza (miguel@ximian.com) 
7 //
8 // (C) Ximian, Inc.  http://www.ximian.com
9 //
10
11 using System;
12 using System.Text;
13
14
15 namespace System.IO {
16         [Serializable]
17         public class StreamReader : TextReader {
18
19                 private const int DefaultBufferSize = 1024;
20                 private const int DefaultFileBufferSize = 4096;
21                 private const int MinimumBufferSize = 128;
22
23                 //
24                 // The input buffer
25                 //
26                 private byte [] input_buffer;
27
28                 //
29                 // The decoded buffer from the above input buffer
30                 //
31                 private char [] decoded_buffer;
32
33                 //
34                 // Decoded bytes in decoded_buffer.
35                 //
36                 private int decoded_count;
37
38                 //
39                 // Current position in the decoded_buffer
40                 //
41                 private int pos;
42
43                 //
44                 // The buffer size that we are using
45                 //
46                 private int buffer_size;
47
48                 //
49                 // Index into `input_buffer' where we start decoding
50                 //
51                 private int parse_start;
52
53                 int do_checks;
54                 
55                 private Encoding encoding;
56                 private Decoder decoder;
57
58                 private Stream base_stream;
59                 private bool mayBlock;
60
61                 private class NullStreamReader : StreamReader {
62                         public override int Peek ()
63                         {
64                                 return -1;
65                         }
66
67                         public override int Read ()
68                         {
69                                 return -1;
70                         }
71
72                         public override int Read (char[] buffer, int index, int count)
73                         {
74                                 return 0;
75                         }
76
77                         public override string ReadLine ()
78                         {
79                                 return null;
80                         }
81
82                         public override string ReadToEnd ()
83                         {
84                                 return String.Empty;
85                         }
86
87                         public override Stream BaseStream
88                         {
89                                 get { return Stream.Null; }
90                         }
91
92                         public override Encoding CurrentEncoding
93                         {
94                                 get { return Encoding.Unicode; }
95                         }
96                 }
97
98                 public new static readonly StreamReader Null =  (StreamReader)(new NullStreamReader());
99                 
100                 internal StreamReader() {}
101
102                 public StreamReader(Stream stream)
103                         : this (stream, Encoding.UTF8Unmarked, true, DefaultBufferSize) { }
104
105                 public StreamReader(Stream stream, bool detect_encoding_from_bytemarks)
106                         : this (stream, Encoding.UTF8Unmarked, detect_encoding_from_bytemarks, DefaultBufferSize) { }
107
108                 public StreamReader(Stream stream, Encoding encoding)
109                         : this (stream, encoding, true, DefaultBufferSize) { }
110
111                 public StreamReader(Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks)
112                         : this (stream, encoding, detect_encoding_from_bytemarks, DefaultBufferSize) { }
113                 
114                 public StreamReader(Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)
115                 {
116                         Initialize (stream, encoding, detect_encoding_from_bytemarks, buffer_size);
117                 }
118
119                 public StreamReader(string path)
120                         : this (path, Encoding.UTF8Unmarked, true, DefaultFileBufferSize) { }
121
122                 public StreamReader(string path, bool detect_encoding_from_bytemarks)
123                         : this (path, Encoding.UTF8Unmarked, detect_encoding_from_bytemarks, DefaultFileBufferSize) { }
124
125                 public StreamReader(string path, Encoding encoding)
126                         : this (path, encoding, true, DefaultFileBufferSize) { }
127
128                 public StreamReader(string path, Encoding encoding, bool detect_encoding_from_bytemarks)
129                         : this (path, encoding, detect_encoding_from_bytemarks, DefaultFileBufferSize) { }
130                 
131                 public StreamReader(string path, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)
132                 {
133                         if (null == path)
134                                 throw new ArgumentNullException("path");
135                         if (String.Empty == path)
136                                 throw new ArgumentException("Empty path not allowed");
137                         if (path.IndexOfAny (Path.InvalidPathChars) != -1)
138                                 throw new ArgumentException("path contains invalid characters");
139
140                         string DirName = Path.GetDirectoryName(path);
141                         if (DirName != String.Empty && !Directory.Exists(DirName))
142                                 throw new DirectoryNotFoundException ("Directory '" + DirName + "' not found.");
143                         if (!File.Exists(path))
144                                 throw new FileNotFoundException("File not found.", path);
145
146                         Stream stream = (Stream) File.OpenRead (path);
147                         Initialize (stream, encoding, detect_encoding_from_bytemarks, buffer_size);
148                 }
149
150                 internal void Initialize (Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size)
151                 {
152                         if (null == stream)
153                                 throw new ArgumentNullException("stream");
154                         if (!stream.CanRead)
155                                 throw new ArgumentException("Cannot read stream");
156
157                         if (buffer_size < MinimumBufferSize)
158                                 buffer_size = MinimumBufferSize;
159
160                         base_stream = stream;
161                         input_buffer = new byte [buffer_size];
162                         this.buffer_size = buffer_size;
163                         this.encoding = encoding;
164                         decoder = encoding.GetDecoder ();
165
166                         byte [] preamble = encoding.GetPreamble ();
167                         do_checks = detect_encoding_from_bytemarks ? 1 : 0;
168                         do_checks += (preamble.Length == 0) ? 0 : 2;
169                         
170                         decoded_buffer = new char [encoding.GetMaxCharCount (buffer_size)];
171                         decoded_count = 0;
172                         pos = 0;
173                 }
174
175                 public virtual Stream BaseStream
176                 {
177                         get {
178                                 return base_stream;
179                         }
180                 }
181
182                 public virtual Encoding CurrentEncoding
183                 {
184                         get {
185                                 if (encoding == null)
186                                         throw new Exception ();
187                                 return encoding;
188                         }
189                 }
190
191                 public override void Close ()
192                 {
193                         Dispose (true);
194                 }
195
196                 protected override void Dispose (bool disposing)
197                 {
198                         if (disposing && base_stream != null)
199                                 base_stream.Close ();
200                         
201                         input_buffer = null;
202                         decoded_buffer = null;
203                         encoding = null;
204                         decoder = null;
205                         base_stream = null;
206                         base.Dispose (disposing);
207                 }
208
209                 //
210                 // Provides auto-detection of the encoding, as well as skipping over
211                 // byte marks at the beginning of a stream.
212                 //
213                 int DoChecks (int count)
214                 {
215                         if ((do_checks & 2) == 2){
216                                 byte [] preamble = encoding.GetPreamble ();
217                                 int c = preamble.Length;
218                                 if (count >= c){
219                                         int i;
220                                         
221                                         for (i = 0; i < c; i++)
222                                                 if (input_buffer [i] != preamble [i])
223                                                         break;
224
225                                         if (i == c)
226                                                 return i;
227                                 }
228                         }
229
230                         if ((do_checks & 1) == 1){
231                                 if (count < 2)
232                                         return 0;
233
234                                 if (input_buffer [0] == 0xfe && input_buffer [1] == 0xff){
235                                         this.encoding = Encoding.BigEndianUnicode;
236                                         return 2;
237                                 }
238
239                                 if (input_buffer [0] == 0xff && input_buffer [1] == 0xfe){
240                                         this.encoding = Encoding.Unicode;
241                                         return 2;
242                                 }
243
244                                 if (count < 3)
245                                         return 0;
246
247                                 if (input_buffer [0] == 0xef && input_buffer [1] == 0xbb && input_buffer [2] == 0xbf){
248                                         this.encoding = Encoding.UTF8Unmarked;
249                                         return 3;
250                                 }
251                         }
252
253                         return 0;
254                 }
255                 
256                 // the buffer is empty, fill it again
257                 private int ReadBuffer ()
258                 {
259                         pos = 0;
260                         int cbEncoded = 0;
261
262                         // keep looping until the decoder gives us some chars
263                         decoded_count = 0;
264                         int parse_start = 0;
265                         do      
266                         {
267                                 cbEncoded = base_stream.Read (input_buffer, 0, buffer_size);
268                                 
269                                 if (cbEncoded == 0)
270                                         return 0;
271
272                                 mayBlock = (cbEncoded < buffer_size);
273                                 if (do_checks > 0){
274                                         Encoding old = encoding;
275                                         parse_start = DoChecks (cbEncoded);
276                                         if (old != encoding){
277                                                 decoder = encoding.GetDecoder ();
278                                         }
279                                         do_checks = 0;
280                                         cbEncoded -= parse_start;
281                                 }
282                                 
283                                 decoded_count += decoder.GetChars (input_buffer, parse_start, cbEncoded, decoded_buffer, 0);
284                                 parse_start = 0;
285                         } while (decoded_count == 0);
286                         
287                         return decoded_count;
288                 }
289
290                 public override int Peek ()
291                 {
292                         if (pos >= decoded_count && (mayBlock || ReadBuffer () == 0))
293                                 return -1;
294
295                         return decoded_buffer [pos];
296                 }
297
298                 public override int Read ()
299                 {
300                         if (pos >= decoded_count && ReadBuffer () == 0)
301                                 return -1;
302
303                         return decoded_buffer [pos++];
304                 }
305
306                 public override int Read (char[] dest_buffer, int index, int count)
307                 {
308                         if (dest_buffer == null)
309                                 throw new ArgumentException ();
310
311                         if ((index < 0) || (count < 0))
312                                 throw new ArgumentOutOfRangeException ();
313
314                         if (index + count > dest_buffer.Length)
315                                 throw new ArgumentException ();
316
317                         int chars_read = 0;
318                         while (count > 0)
319                         {
320                                 if (pos >= decoded_count && ReadBuffer () == 0)
321                                         return chars_read > 0 ? chars_read : 0;
322
323                                 int cch = Math.Min (decoded_count - pos, count);
324                                 Array.Copy (decoded_buffer, pos, dest_buffer, index, cch);
325                                 pos += cch;
326                                 index += cch;
327                                 count -= cch;
328                                 chars_read += cch;
329                         }
330                         return chars_read;
331                 }
332
333                 public override string ReadLine()
334                 {
335                         bool foundCR = false;
336                         StringBuilder text = new StringBuilder ();
337
338                         while (true) {
339                                 int c = Read ();
340
341                                 if (c == -1) {                          // end of stream
342                                         if (text.Length == 0)
343                                                 return null;
344
345                                         if (foundCR)
346                                                 text.Length--;
347
348                                         break;
349                                 }
350
351                                 if (c == '\n') {                        // newline
352                                         if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
353                                                 text.Length--;
354
355                                         foundCR = false;
356                                         break;
357                                 } else if (foundCR) {
358                                         pos--;
359                                         text.Length--;
360                                         break;
361                                 }
362
363                                 if (c == '\r')
364                                         foundCR = true;
365                                         
366
367                                 text.Append ((char) c);
368                         }
369
370                         return text.ToString ();
371                 }
372
373                 public override string ReadToEnd()
374                 {
375                         StringBuilder text = new StringBuilder ();
376
377                         int size = decoded_buffer.Length;
378                         char [] buffer = new char [size];
379                         int len;
380                         
381                         while ((len = Read (buffer, 0, size)) != 0)
382                                 text.Append (buffer, 0, len);
383
384                         return text.ToString ();
385                 }
386         }
387 }