2004-07-05 Dick Porter <dick@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
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                         FillBuffer(1);
258
259                         // Return value:
260                         //  true if the byte is non-zero; otherwise false.
261                         return(m_buffer[0] != 0);
262                 }
263
264                 public virtual byte ReadByte() {
265                         FillBuffer(1);
266
267                         return(m_buffer[0]);
268                 }
269
270                 public virtual byte[] ReadBytes(int count) {
271                         if(m_stream==null) {
272
273                                 if (m_disposed)
274                                         throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
275
276                                 throw new IOException("Stream is invalid");
277                         }
278                         
279                         if (count < 0) {
280                                 throw new ArgumentOutOfRangeException("count is less than 0");
281                         }
282
283                         /* Can't use FillBuffer() here, because it's OK to
284                          * return fewer bytes than were requested
285                          */
286
287                         byte[] buf = new byte[count];
288                         int pos=0;
289                         
290                         while(pos < count) \r
291                         {
292                                 int n=m_stream.Read(buf, pos, count-pos);
293                                 if(n==0) {
294                                         /* EOF */
295                                         break;
296                                 }
297
298                                 pos+=n;
299                         }
300                                 
301                         if (pos!=count) {
302                                 byte[] new_buffer=new byte[pos];
303                                 Array.Copy(buf, new_buffer, pos);
304                                 return(new_buffer);
305                         }
306                         
307                         return(buf);
308                 }
309
310                 public virtual char ReadChar() {
311                         int ch=Read();
312
313                         if(ch==-1) {
314                                 throw new EndOfStreamException();
315                         }
316
317                         return((char)ch);
318                 }
319
320                 public virtual char[] ReadChars(int count) {
321                         if (count < 0) {
322                                 throw new ArgumentOutOfRangeException("count is less than 0");
323                         }
324
325                         char[] full = new char[count];
326                         int chars = Read(full, 0, count);
327                         
328                         if (chars == 0) {
329                                 throw new EndOfStreamException();
330                         } else if (chars != full.Length) {
331                                 char[] ret = new char[chars];
332                                 Array.Copy(full, 0, ret, 0, chars);
333                                 return ret;
334                         } else {
335                                 return full;
336                         }
337                 }
338
339                 unsafe public virtual decimal ReadDecimal() {
340                         FillBuffer(16);
341
342                         decimal ret;
343                         byte* ret_ptr = (byte *)&ret;
344                         for (int i = 0; i < 16; i++) {
345                           
346                                 /*
347                                  * internal representation of decimal is 
348                                  * ss32, hi32, lo32, mi32, 
349                                  * but in stream it is 
350                                  * lo32, mi32, hi32, ss32
351                                  * So we have to rerange this int32 values
352                                  */                       
353                           
354                                 if (i < 4) {
355                                         // lo 8 - 12                      
356                                         ret_ptr [i + 8] = m_buffer [i];
357                                 } else if (i < 8) {
358                                         // mid 12 - 16
359                                         ret_ptr [i + 8] = m_buffer [i];
360                                 } else if (i < 12) {
361                                         // hi 4 - 8
362                                         ret_ptr [i - 4] = m_buffer [i];
363                                 } else if (i < 16) {
364                                         // ss 0 - 4
365                                         ret_ptr [i - 12] = m_buffer [i];
366                                 }                               
367                         }
368
369                         return ret;
370                 }
371
372                 public virtual double ReadDouble() {
373                         FillBuffer(8);
374
375                         return(BitConverter.ToDouble(m_buffer, 0));
376                 }
377
378                 public virtual short ReadInt16() {
379                         FillBuffer(2);
380
381                         return((short) (m_buffer[0] | (m_buffer[1] << 8)));
382                 }
383
384                 public virtual int ReadInt32() {
385                         FillBuffer(4);
386
387                         return(m_buffer[0] | (m_buffer[1] << 8) |
388                                (m_buffer[2] << 16) | (m_buffer[3] << 24));
389                 }
390
391                 public virtual long ReadInt64() {
392                         FillBuffer(8);
393
394                         uint ret_low  = (uint) (m_buffer[0]            |
395                                                (m_buffer[1] << 8)  |
396                                                (m_buffer[2] << 16) |
397                                                (m_buffer[3] << 24)
398                                                );
399                         uint ret_high = (uint) (m_buffer[4]        |
400                                                (m_buffer[5] << 8)  |
401                                                (m_buffer[6] << 16) |
402                                                (m_buffer[7] << 24)
403                                                );
404                         return (long) ((((ulong) ret_high) << 32) | ret_low);
405                 }
406
407                 [CLSCompliant(false)]
408                 public virtual sbyte ReadSByte() {
409                         FillBuffer(1);
410
411                         return((sbyte)m_buffer[0]);
412                 }
413
414                 public virtual string ReadString() {
415                         /* Inspection of BinaryWriter-written files
416                          * shows that the length is given in bytes,
417                          * not chars
418                          */
419                         int len = Read7BitEncodedInt();
420
421                         FillBuffer(len);
422                         
423                         char[] str = m_encoding.GetChars(m_buffer, 0, len);
424
425                         return(new String(str));
426                 }
427
428                 public virtual float ReadSingle() {
429                         FillBuffer(4);
430
431                         return(BitConverter.ToSingle(m_buffer, 0));
432                 }
433
434                 [CLSCompliant(false)]
435                 public virtual ushort ReadUInt16() {
436                         FillBuffer(2);
437
438                         return((ushort) (m_buffer[0] | (m_buffer[1] << 8)));
439                 }
440
441                 [CLSCompliant(false)]
442                 public virtual uint ReadUInt32() {
443                         FillBuffer(4);
444                                 
445
446                         return((uint) (m_buffer[0] |
447                                        (m_buffer[1] << 8) |
448                                        (m_buffer[2] << 16) |
449                                        (m_buffer[3] << 24)));
450                 }
451
452                 [CLSCompliant(false)]
453                 public virtual ulong ReadUInt64() {
454                         FillBuffer(8);
455
456                         uint ret_low  = (uint) (m_buffer[0]            |
457                                                (m_buffer[1] << 8)  |
458                                                (m_buffer[2] << 16) |
459                                                (m_buffer[3] << 24)
460                                                );
461                         uint ret_high = (uint) (m_buffer[4]        |
462                                                (m_buffer[5] << 8)  |
463                                                (m_buffer[6] << 16) |
464                                                (m_buffer[7] << 24)
465                                                );
466                         return (((ulong) ret_high) << 32) | ret_low;
467                 }
468
469                 /* Ensures that m_buffer is at least length bytes
470                  * long, growing it if necessary
471                  */
472                 private void CheckBuffer(int length)
473                 {
474                         if(m_buffer.Length <= length) {
475                                 byte[] new_buffer=new byte[length];
476                                 Array.Copy(m_buffer, new_buffer,
477                                            m_buffer.Length);
478                                 m_buffer=new_buffer;
479                         }
480                 }
481         }
482 }