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