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