New test.
[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                         if (charBuffer == null)
156                                 charBuffer = new char [MaxBufferSize];
157
158                         int count = Read (charBuffer, 0, 1);
159                         if(count == 0) {
160                                 /* No chars available */
161                                 return -1;
162                         }
163                         
164                         return charBuffer [0];
165                 }
166
167                 public virtual int Read(byte[] buffer, int index, int count) {
168                         if(m_stream==null) {
169
170                                 if (m_disposed)
171                                         throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
172
173                                 throw new IOException("Stream is invalid");
174                         }
175                         
176                         if (buffer == null) {
177                                 throw new ArgumentNullException("buffer is null");
178                         }
179                         if (index < 0) {
180                                 throw new ArgumentOutOfRangeException("index is less than 0");
181                         }
182                         if (count < 0) {
183                                 throw new ArgumentOutOfRangeException("count is less than 0");
184                         }
185                         if (buffer.Length - index < count) {
186                                 throw new ArgumentException("buffer is too small");
187                         }
188
189                         int bytes_read=m_stream.Read(buffer, index, count);
190
191                         return(bytes_read);
192                 }
193
194                 public virtual int Read(char[] buffer, int index, int count) {
195
196                         if(m_stream==null) {
197
198                                 if (m_disposed)
199                                         throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
200
201                                 throw new IOException("Stream is invalid");
202                         }
203                         
204                         if (buffer == null) {
205                                 throw new ArgumentNullException("buffer is null");
206                         }
207                         if (index < 0) {
208                                 throw new ArgumentOutOfRangeException("index is less than 0");
209                         }
210                         if (count < 0) {
211                                 throw new ArgumentOutOfRangeException("count is less than 0");
212                         }
213                         if (buffer.Length - index < count) {
214                                 throw new ArgumentException("buffer is too small");
215                         }
216
217                         int bytes_read;
218                         byte[] bytes;
219                         return ReadCharBytes (buffer, index, count, out bytes, out bytes_read);
220                 }
221
222                 private int ReadCharBytes(char[] buffer, int index, int count, out byte[] bytes, out int bytes_read) \r
223                 {
224                         int chars_read=0;
225                         bytes_read=0;
226                         
227                         while(chars_read < count) 
228                         {
229                                 CheckBuffer(bytes_read + 1);
230
231                                 int read_byte = m_stream.ReadByte();
232
233                                 if(read_byte==-1) 
234                                 {
235                                         /* EOF */
236                                         bytes = m_buffer;
237                                         return(chars_read);
238                                 }
239
240                                 m_buffer[bytes_read]=(byte)read_byte;
241                                 bytes_read++;
242
243                                 chars_read=m_encoding.GetChars(m_buffer, 0,
244                                                                                  bytes_read,
245                                                                                  buffer, index);
246                                 
247                         }
248
249                         bytes = m_buffer;
250                         return(chars_read);
251                 }
252
253                 protected int Read7BitEncodedInt() {
254                         int ret = 0;
255                         int shift = 0;
256                         byte b;
257
258                         do {
259                                 b = ReadByte();
260                                 
261                                 ret = ret | ((b & 0x7f) << shift);
262                                 shift += 7;
263                         } while ((b & 0x80) == 0x80);
264
265                         return ret;
266                 }
267
268                 public virtual bool ReadBoolean() {
269                         // Return value:
270                         //  true if the byte is non-zero; otherwise false.
271                         return ReadByte() != 0;
272                 }
273
274                 public virtual byte ReadByte() {
275                         if (m_stream == null) {
276                                 if (m_disposed)
277                                         throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
278
279                                 throw new IOException ("Stream is invalid");
280                         }
281                         
282                         int val = m_stream.ReadByte ();
283                         if (val != -1)
284                                 return (byte) val;
285                         
286                         throw new EndOfStreamException ();
287                 }
288
289                 public virtual byte[] ReadBytes(int count) {
290                         if(m_stream==null) {
291
292                                 if (m_disposed)
293                                         throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
294
295                                 throw new IOException("Stream is invalid");
296                         }
297                         
298                         if (count < 0) {
299                                 throw new ArgumentOutOfRangeException("count is less than 0");
300                         }
301
302                         /* Can't use FillBuffer() here, because it's OK to
303                          * return fewer bytes than were requested
304                          */
305
306                         byte[] buf = new byte[count];
307                         int pos=0;
308                         
309                         while(pos < count) \r
310                         {
311                                 int n=m_stream.Read(buf, pos, count-pos);
312                                 if(n==0) {
313                                         /* EOF */
314                                         break;
315                                 }
316
317                                 pos+=n;
318                         }
319                                 
320                         if (pos!=count) {
321                                 byte[] new_buffer=new byte[pos];
322                                 Buffer.BlockCopyInternal (buf, 0, new_buffer, 0, pos);
323                                 return(new_buffer);
324                         }
325                         
326                         return(buf);
327                 }
328
329                 public virtual char ReadChar() {
330                         int ch=Read();
331
332                         if(ch==-1) {
333                                 throw new EndOfStreamException();
334                         }
335
336                         return((char)ch);
337                 }
338
339                 public virtual char[] ReadChars(int count) {
340                         if (count < 0) {
341                                 throw new ArgumentOutOfRangeException("count is less than 0");
342                         }
343
344                         if (count == 0)
345                                 return new char [0];
346                                         
347                         char[] full = new char[count];
348                         int chars = Read(full, 0, count);
349                         
350                         if (chars == 0) {
351                                 throw new EndOfStreamException();
352                         } else if (chars != full.Length) {
353                                 char[] ret = new char[chars];
354                                 Array.Copy(full, 0, ret, 0, chars);
355                                 return ret;
356                         } else {
357                                 return full;
358                         }
359                 }
360
361                 unsafe public virtual decimal ReadDecimal() {
362                         FillBuffer(16);
363
364                         decimal ret;
365                         byte* ret_ptr = (byte *)&ret;
366                         
367                         /*
368                          * internal representation of decimal is 
369                          * ss32, hi32, lo32, mi32, 
370                          * but in stream it is 
371                          * lo32, mi32, hi32, ss32
372                          * So we have to rerange this int32 values
373                          */                       
374                   
375                         if (BitConverter.IsLittleEndian) {
376                                 for (int i = 0; i < 16; i++) {
377                                         if (i < 4) {
378                                                 // lo 8 - 12                      
379                                                 ret_ptr [i + 8] = m_buffer [i];
380                                         } else if (i < 8) {
381                                                 // mid 12 - 16
382                                                 ret_ptr [i + 8] = m_buffer [i];
383                                         } else if (i < 12) {
384                                                 // hi 4 - 8
385                                                 ret_ptr [i - 4] = m_buffer [i];
386                                         } else if (i < 16) {
387                                                 // ss 0 - 4
388                                                 ret_ptr [i - 12] = m_buffer [i];
389                                         }                               
390                                 }
391                         } else {
392                                 for (int i = 0; i < 16; i++) {
393                                         if (i < 4) {
394                                                 // lo 8 - 12                      
395                                                 ret_ptr [11 - i] = m_buffer [i];
396                                         } else if (i < 8) {
397                                                 // mid 12 - 16
398                                                 ret_ptr [19 - i] = m_buffer [i];
399                                         } else if (i < 12) {
400                                                 // hi 4 - 8
401                                                 ret_ptr [15 - i] = m_buffer [i];
402                                         } else if (i < 16) {
403                                                 // ss 0 - 4
404                                                 ret_ptr [15 - i] = m_buffer [i];
405                                         }                               
406                                 }
407                         }
408
409                         return ret;
410                 }
411
412                 public virtual double ReadDouble() {
413                         FillBuffer(8);
414
415                         return(BitConverterLE.ToDouble(m_buffer, 0));
416                 }
417
418                 public virtual short ReadInt16() {
419                         FillBuffer(2);
420
421                         return((short) (m_buffer[0] | (m_buffer[1] << 8)));
422                 }
423
424                 public virtual int ReadInt32() {
425                         FillBuffer(4);
426
427                         return(m_buffer[0] | (m_buffer[1] << 8) |
428                                (m_buffer[2] << 16) | (m_buffer[3] << 24));
429                 }
430
431                 public virtual long ReadInt64() {
432                         FillBuffer(8);
433
434                         uint ret_low  = (uint) (m_buffer[0]            |
435                                                (m_buffer[1] << 8)  |
436                                                (m_buffer[2] << 16) |
437                                                (m_buffer[3] << 24)
438                                                );
439                         uint ret_high = (uint) (m_buffer[4]        |
440                                                (m_buffer[5] << 8)  |
441                                                (m_buffer[6] << 16) |
442                                                (m_buffer[7] << 24)
443                                                );
444                         return (long) ((((ulong) ret_high) << 32) | ret_low);
445                 }
446
447                 [CLSCompliant(false)]
448                 public virtual sbyte ReadSByte() {
449                         return (sbyte) ReadByte ();
450                 }
451
452                 public virtual string ReadString() {
453                         /* Inspection of BinaryWriter-written files
454                          * shows that the length is given in bytes,
455                          * not chars
456                          */
457                         int len = Read7BitEncodedInt();
458                         
459                         if (len < 0)
460                                 throw new IOException ("Invalid binary file (string len < 0)");
461
462                         if (len == 0)
463                                 return String.Empty;
464                         
465                         
466                         if (charBuffer == null)
467                                 charBuffer = new char [MaxBufferSize];
468
469                         //
470                         // We read the string here in small chunks. Also, we
471                         // Attempt to optimize the common case of short strings.
472                         //
473                         StringBuilder sb = null;
474                         do {
475                                 int readLen = (len > MaxBufferSize)
476                                                 ? MaxBufferSize
477                                                 : len;
478                                 
479                                 FillBuffer (readLen);
480                                 
481                                 int cch = decoder.GetChars (m_buffer, 0, readLen, charBuffer, 0);
482
483                                 if (sb == null && readLen == len) // ok, we got out the easy way, dont bother with the sb
484                                         return new String (charBuffer, 0, cch);
485
486                                 if (sb == null)
487                                         // Len is a fairly good estimate of the number of chars in a string
488                                         // Most of the time 1 byte == 1 char
489                                         sb = new StringBuilder (len);
490                                 
491                                 sb.Append (charBuffer, 0, cch);
492                                 len -= readLen;
493                         } while (len > 0);
494
495                         return sb.ToString();
496                 }
497
498                 public virtual float ReadSingle() {
499                         FillBuffer(4);
500
501                         return(BitConverterLE.ToSingle(m_buffer, 0));
502                 }
503
504                 [CLSCompliant(false)]
505                 public virtual ushort ReadUInt16() {
506                         FillBuffer(2);
507
508                         return((ushort) (m_buffer[0] | (m_buffer[1] << 8)));
509                 }
510
511                 [CLSCompliant(false)]
512                 public virtual uint ReadUInt32() {
513                         FillBuffer(4);
514                                 
515
516                         return((uint) (m_buffer[0] |
517                                        (m_buffer[1] << 8) |
518                                        (m_buffer[2] << 16) |
519                                        (m_buffer[3] << 24)));
520                 }
521
522                 [CLSCompliant(false)]
523                 public virtual ulong ReadUInt64() {
524                         FillBuffer(8);
525
526                         uint ret_low  = (uint) (m_buffer[0]            |
527                                                (m_buffer[1] << 8)  |
528                                                (m_buffer[2] << 16) |
529                                                (m_buffer[3] << 24)
530                                                );
531                         uint ret_high = (uint) (m_buffer[4]        |
532                                                (m_buffer[5] << 8)  |
533                                                (m_buffer[6] << 16) |
534                                                (m_buffer[7] << 24)
535                                                );
536                         return (((ulong) ret_high) << 32) | ret_low;
537                 }
538
539                 /* Ensures that m_buffer is at least length bytes
540                  * long, growing it if necessary
541                  */
542                 private void CheckBuffer(int length)
543                 {
544                         if(m_buffer.Length <= length) {
545                                 byte[] new_buffer=new byte[length];
546                                 Buffer.BlockCopyInternal (m_buffer, 0, new_buffer, 0, m_buffer.Length);
547                                 m_buffer=new_buffer;
548                         }
549                 }
550         }
551 }