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