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