2009-10-21 Miguel de Icaza <miguel@novell.com>
[mono.git] / mcs / class / corlib / System.IO / BinaryReader.cs
1 //
2 // System.IO.BinaryReader
3 //
4 // Author:
5 //   Matt Kimball (matt@kimball.net)
6 //   Dick Porter (dick@ximian.com)
7 //
8
9 //
10 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System;
33 using System.Text;
34 using System.Globalization;
35 using Mono.Security;
36 using System.Runtime.InteropServices;
37
38 namespace System.IO {
39         [ComVisible (true)]
40         public class BinaryReader : IDisposable {
41                 Stream m_stream;
42                 Encoding m_encoding;
43
44                 byte[] m_buffer;
45
46                 Decoder decoder;
47                 char [] charBuffer;
48                 
49                 //
50                 // 128 chars should cover most strings in one grab.
51                 //
52                 const int MaxBufferSize = 128;
53
54                 
55                 private bool m_disposed = false;
56
57                 public BinaryReader(Stream input) : this(input, Encoding.UTF8UnmarkedUnsafe) {
58                 }
59
60                 public BinaryReader(Stream input, Encoding encoding) {
61                         if (input == null || encoding == null) 
62                                 throw new ArgumentNullException(Locale.GetText ("Input or Encoding is a null reference."));
63                         if (!input.CanRead)
64                                 throw new ArgumentException(Locale.GetText ("The stream doesn't support reading."));
65
66                         m_stream = input;
67                         m_encoding = encoding;
68                         decoder = encoding.GetDecoder ();
69                         m_buffer = new byte [32];
70                 }
71
72                 public virtual Stream BaseStream {
73                         get {
74                                 return m_stream;
75                         }
76                 }
77
78                 public virtual void Close() {
79                         Dispose (true);
80                         m_disposed = true;
81                 }
82                 
83                 protected virtual void Dispose (bool disposing)
84                 {
85                         if (disposing && m_stream != null)
86                                 m_stream.Close ();
87
88                         m_disposed = true;
89                         m_buffer = null;
90                         m_encoding = null;
91                         m_stream = null;
92                         charBuffer = null;
93                 }
94
95 #if NET_4_0
96                 public void Dispose ()
97 #else
98                 void IDisposable.Dispose() 
99 #endif
100                 {
101                         Dispose (true);
102                 }
103
104                 protected virtual void FillBuffer (int numBytes)
105                 {
106                         if (m_disposed)
107                                 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
108                         if (m_stream==null)
109                                 throw new IOException("Stream is invalid");
110                         
111                         CheckBuffer(numBytes);
112
113                         /* Cope with partial reads */
114                         int pos=0;
115
116                         while(pos<numBytes) {
117                                 int n=m_stream.Read(m_buffer, pos, numBytes-pos);
118                                 if(n==0) {
119                                         throw new EndOfStreamException();
120                                 }
121
122                                 pos+=n;
123                         }
124                 }
125
126                 public virtual int PeekChar() {
127                         if(m_stream==null) {
128                                 
129                                 if (m_disposed)
130                                         throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
131
132                                 throw new IOException("Stream is invalid");
133                         }
134
135                         if ( !m_stream.CanSeek )
136                         {
137                                 return -1;
138                         }
139
140                         char[] result = new char[1];
141                         int bcount;
142
143                         int ccount = ReadCharBytes (result, 0, 1, out bcount);
144
145                         // Reposition the stream
146                         m_stream.Position -= bcount;
147
148                         // If we read 0 characters then return -1
149                         if (ccount == 0) 
150                         {
151                                 return -1;
152                         }
153                         
154                         // Return the single character we read
155                         return result[0];
156                 }
157
158                 public virtual int Read() {
159                         if (charBuffer == null)
160                                 charBuffer = new char [MaxBufferSize];
161
162                         int count = Read (charBuffer, 0, 1);
163                         if(count == 0) {
164                                 /* No chars available */
165                                 return -1;
166                         }
167                         
168                         return charBuffer [0];
169                 }
170
171                 public virtual int Read(byte[] buffer, int index, int count) {
172                         if(m_stream==null) {
173
174                                 if (m_disposed)
175                                         throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
176
177                                 throw new IOException("Stream is invalid");
178                         }
179                         
180                         if (buffer == null) {
181                                 throw new ArgumentNullException("buffer is null");
182                         }
183                         if (index < 0) {
184                                 throw new ArgumentOutOfRangeException("index is less than 0");
185                         }
186                         if (count < 0) {
187                                 throw new ArgumentOutOfRangeException("count is less than 0");
188                         }
189                         if (buffer.Length - index < count) {
190                                 throw new ArgumentException("buffer is too small");
191                         }
192
193                         int bytes_read=m_stream.Read(buffer, index, count);
194
195                         return(bytes_read);
196                 }
197
198                 public virtual int Read(char[] buffer, int index, int count) {
199
200                         if(m_stream==null) {
201
202                                 if (m_disposed)
203                                         throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
204
205                                 throw new IOException("Stream is invalid");
206                         }
207                         
208                         if (buffer == null) {
209                                 throw new ArgumentNullException("buffer is null");
210                         }
211                         if (index < 0) {
212                                 throw new ArgumentOutOfRangeException("index is less than 0");
213                         }
214                         if (count < 0) {
215                                 throw new ArgumentOutOfRangeException("count is less than 0");
216                         }
217                         if (buffer.Length - index < count) {
218                                 throw new ArgumentException("buffer is too small");
219                         }
220
221                         int bytes_read;
222                         return ReadCharBytes (buffer, index, count, out bytes_read);
223                 }
224
225                 private int ReadCharBytes (char[] buffer, int index, int count, out int bytes_read) 
226                 {
227                         int chars_read = 0;
228                         bytes_read = 0;
229                         
230                         while (chars_read < count) {
231                                 int pos = 0;
232                                 while (true) {
233                                         CheckBuffer (pos + 1);
234
235                                         int read_byte = m_stream.ReadByte ();
236
237                                         if (read_byte == -1)
238                                                 /* EOF */
239                                                 return chars_read;
240
241                                         m_buffer [pos ++] = (byte)read_byte;
242                                         bytes_read ++;
243
244                                         int n = m_encoding.GetChars (m_buffer, 0, pos, buffer, index + chars_read);
245                                         if (n > 0)
246                                                 break;
247                                 }
248                                 chars_read ++;
249                         }
250
251                         return chars_read;
252                 }
253
254                 protected int Read7BitEncodedInt() {
255                         int ret = 0;
256                         int shift = 0;
257                         int len;
258                         byte b;
259
260                         for (len = 0; len < 5; ++len) {
261                                 b = ReadByte();
262                                 
263                                 ret = ret | ((b & 0x7f) << shift);
264                                 shift += 7;
265                                 if ((b & 0x80) == 0)
266                                         break;
267                         }
268
269                         if (len < 5)
270                                 return ret;
271                         else
272                                 throw new FormatException ("Too many bytes in what should have been a 7 bit encoded Int32.");
273                 }
274
275                 public virtual bool ReadBoolean() {
276                         // Return value:
277                         //  true if the byte is non-zero; otherwise false.
278                         return ReadByte() != 0;
279                 }
280
281                 public virtual byte ReadByte() {
282                         if (m_stream == null) {
283                                 if (m_disposed)
284                                         throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
285
286                                 throw new IOException ("Stream is invalid");
287                         }
288                         
289                         int val = m_stream.ReadByte ();
290                         if (val != -1)
291                                 return (byte) val;
292                         
293                         throw new EndOfStreamException ();
294                 }
295
296                 public virtual byte[] ReadBytes(int count) {
297                         if(m_stream==null) {
298
299                                 if (m_disposed)
300                                         throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
301
302                                 throw new IOException("Stream is invalid");
303                         }
304                         
305                         if (count < 0) {
306                                 throw new ArgumentOutOfRangeException("count is less than 0");
307                         }
308
309                         /* Can't use FillBuffer() here, because it's OK to
310                          * return fewer bytes than were requested
311                          */
312
313                         byte[] buf = new byte[count];
314                         int pos=0;
315                         
316                         while(pos < count) 
317                         {
318                                 int n=m_stream.Read(buf, pos, count-pos);
319                                 if(n==0) {
320                                         /* EOF */
321                                         break;
322                                 }
323
324                                 pos+=n;
325                         }
326                                 
327                         if (pos!=count) {
328                                 byte[] new_buffer=new byte[pos];
329                                 Buffer.BlockCopyInternal (buf, 0, new_buffer, 0, pos);
330                                 return(new_buffer);
331                         }
332                         
333                         return(buf);
334                 }
335
336                 public virtual char ReadChar() {
337                         int ch=Read();
338
339                         if(ch==-1) {
340                                 throw new EndOfStreamException();
341                         }
342
343                         return((char)ch);
344                 }
345
346                 public virtual char[] ReadChars(int count) {
347                         if (count < 0) {
348                                 throw new ArgumentOutOfRangeException("count is less than 0");
349                         }
350
351                         if (count == 0)
352                                 return new char [0];
353                                         
354                         char[] full = new char[count];
355                         int chars = Read(full, 0, count);
356                         
357                         if (chars == 0) {
358                                 throw new EndOfStreamException();
359                         } else if (chars != full.Length) {
360                                 char[] ret = new char[chars];
361                                 Array.Copy(full, 0, ret, 0, chars);
362                                 return ret;
363                         } else {
364                                 return full;
365                         }
366                 }
367
368                 unsafe public virtual decimal ReadDecimal() {
369                         FillBuffer(16);
370
371                         decimal ret;
372                         byte* ret_ptr = (byte *)&ret;
373                         
374                         /*
375                          * internal representation of decimal is 
376                          * ss32, hi32, lo32, mi32, 
377                          * but in stream it is 
378                          * lo32, mi32, hi32, ss32
379                          * So we have to rerange this int32 values
380                          */                       
381                   
382                         if (BitConverter.IsLittleEndian) {
383                                 for (int i = 0; i < 16; i++) {
384                                         if (i < 4) {
385                                                 // lo 8 - 12                      
386                                                 ret_ptr [i + 8] = m_buffer [i];
387                                         } else if (i < 8) {
388                                                 // mid 12 - 16
389                                                 ret_ptr [i + 8] = m_buffer [i];
390                                         } else if (i < 12) {
391                                                 // hi 4 - 8
392                                                 ret_ptr [i - 4] = m_buffer [i];
393                                         } else if (i < 16) {
394                                                 // ss 0 - 4
395                                                 ret_ptr [i - 12] = m_buffer [i];
396                                         }                               
397                                 }
398                         } else {
399                                 for (int i = 0; i < 16; i++) {
400                                         if (i < 4) {
401                                                 // lo 8 - 12                      
402                                                 ret_ptr [11 - i] = m_buffer [i];
403                                         } else if (i < 8) {
404                                                 // mid 12 - 16
405                                                 ret_ptr [19 - i] = m_buffer [i];
406                                         } else if (i < 12) {
407                                                 // hi 4 - 8
408                                                 ret_ptr [15 - i] = m_buffer [i];
409                                         } else if (i < 16) {
410                                                 // ss 0 - 4
411                                                 ret_ptr [15 - i] = m_buffer [i];
412                                         }                               
413                                 }
414                         }
415
416                         return ret;
417                 }
418
419                 public virtual double ReadDouble() {
420                         FillBuffer(8);
421
422                         return(BitConverterLE.ToDouble(m_buffer, 0));
423                 }
424
425                 public virtual short ReadInt16() {
426                         FillBuffer(2);
427
428                         return((short) (m_buffer[0] | (m_buffer[1] << 8)));
429                 }
430
431                 public virtual int ReadInt32() {
432                         FillBuffer(4);
433
434                         return(m_buffer[0] | (m_buffer[1] << 8) |
435                                (m_buffer[2] << 16) | (m_buffer[3] << 24));
436                 }
437
438                 public virtual long ReadInt64() {
439                         FillBuffer(8);
440
441                         uint ret_low  = (uint) (m_buffer[0]            |
442                                                (m_buffer[1] << 8)  |
443                                                (m_buffer[2] << 16) |
444                                                (m_buffer[3] << 24)
445                                                );
446                         uint ret_high = (uint) (m_buffer[4]        |
447                                                (m_buffer[5] << 8)  |
448                                                (m_buffer[6] << 16) |
449                                                (m_buffer[7] << 24)
450                                                );
451                         return (long) ((((ulong) ret_high) << 32) | ret_low);
452                 }
453
454                 [CLSCompliant(false)]
455                 public virtual sbyte ReadSByte() {
456                         return (sbyte) ReadByte ();
457                 }
458
459                 public virtual string ReadString() {
460                         /* Inspection of BinaryWriter-written files
461                          * shows that the length is given in bytes,
462                          * not chars
463                          */
464                         int len = Read7BitEncodedInt();
465                         
466                         if (len < 0)
467                                 throw new IOException ("Invalid binary file (string len < 0)");
468
469                         if (len == 0)
470                                 return String.Empty;
471                         
472                         
473                         if (charBuffer == null)
474                                 charBuffer = new char [MaxBufferSize];
475
476                         //
477                         // We read the string here in small chunks. Also, we
478                         // Attempt to optimize the common case of short strings.
479                         //
480                         StringBuilder sb = null;
481                         do {
482                                 int readLen = (len > MaxBufferSize)
483                                                 ? MaxBufferSize
484                                                 : len;
485                                 
486                                 FillBuffer (readLen);
487                                 
488                                 int cch = decoder.GetChars (m_buffer, 0, readLen, charBuffer, 0);
489
490                                 if (sb == null && readLen == len) // ok, we got out the easy way, dont bother with the sb
491                                         return new String (charBuffer, 0, cch);
492
493                                 if (sb == null)
494                                         // Len is a fairly good estimate of the number of chars in a string
495                                         // Most of the time 1 byte == 1 char
496                                         sb = new StringBuilder (len);
497                                 
498                                 sb.Append (charBuffer, 0, cch);
499                                 len -= readLen;
500                         } while (len > 0);
501
502                         return sb.ToString();
503                 }
504
505                 public virtual float ReadSingle() {
506                         FillBuffer(4);
507
508                         return(BitConverterLE.ToSingle(m_buffer, 0));
509                 }
510
511                 [CLSCompliant(false)]
512                 public virtual ushort ReadUInt16() {
513                         FillBuffer(2);
514
515                         return((ushort) (m_buffer[0] | (m_buffer[1] << 8)));
516                 }
517
518                 [CLSCompliant(false)]
519                 public virtual uint ReadUInt32() {
520                         FillBuffer(4);
521                                 
522
523                         return((uint) (m_buffer[0] |
524                                        (m_buffer[1] << 8) |
525                                        (m_buffer[2] << 16) |
526                                        (m_buffer[3] << 24)));
527                 }
528
529                 [CLSCompliant(false)]
530                 public virtual ulong ReadUInt64() {
531                         FillBuffer(8);
532
533                         uint ret_low  = (uint) (m_buffer[0]            |
534                                                (m_buffer[1] << 8)  |
535                                                (m_buffer[2] << 16) |
536                                                (m_buffer[3] << 24)
537                                                );
538                         uint ret_high = (uint) (m_buffer[4]        |
539                                                (m_buffer[5] << 8)  |
540                                                (m_buffer[6] << 16) |
541                                                (m_buffer[7] << 24)
542                                                );
543                         return (((ulong) ret_high) << 32) | ret_low;
544                 }
545
546                 /* Ensures that m_buffer is at least length bytes
547                  * long, growing it if necessary
548                  */
549                 private void CheckBuffer(int length)
550                 {
551                         if(m_buffer.Length <= length) {
552                                 byte[] new_buffer=new byte[length];
553                                 Buffer.BlockCopyInternal (m_buffer, 0, new_buffer, 0, m_buffer.Length);
554                                 m_buffer=new_buffer;
555                         }
556                 }
557         }
558 }