2 // System.IO.BinaryReader
5 // Matt Kimball (matt@kimball.net)
6 // Dick Porter (dick@ximian.com)
10 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
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:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
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.
34 using System
.Globalization
;
36 using System
.Runtime
.InteropServices
;
40 public class BinaryReader
: IDisposable
{
50 // 128 chars should cover most strings in one grab.
52 const int MaxBufferSize
= 128;
55 private bool m_disposed
= false;
57 public BinaryReader(Stream input
) : this(input
, Encoding
.UTF8UnmarkedUnsafe
) {
60 public BinaryReader(Stream input
, Encoding encoding
) {
61 if (input
== null || encoding
== null)
62 throw new ArgumentNullException(Locale
.GetText ("Input or Encoding is a null reference."));
64 throw new ArgumentException(Locale
.GetText ("The stream doesn't support reading."));
67 m_encoding
= encoding
;
68 decoder
= encoding
.GetDecoder ();
69 m_buffer
= new byte [32];
72 public virtual Stream BaseStream
{
78 public virtual void Close() {
83 protected virtual void Dispose (bool disposing
)
85 if (disposing
&& m_stream
!= null)
96 public void Dispose ()
98 void IDisposable
.Dispose()
104 protected virtual void FillBuffer (int numBytes
)
107 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
109 throw new IOException("Stream is invalid");
111 CheckBuffer(numBytes
);
113 /* Cope with partial reads */
116 while(pos
<numBytes
) {
117 int n
=m_stream
.Read(m_buffer
, pos
, numBytes
-pos
);
119 throw new EndOfStreamException();
126 public virtual int PeekChar() {
130 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
132 throw new IOException("Stream is invalid");
135 if ( !m_stream
.CanSeek
)
140 char[] result
= new char[1];
143 int ccount
= ReadCharBytes (result
, 0, 1, out bcount
);
145 // Reposition the stream
146 m_stream
.Position
-= bcount
;
148 // If we read 0 characters then return -1
154 // Return the single character we read
158 public virtual int Read() {
159 if (charBuffer
== null)
160 charBuffer
= new char [MaxBufferSize
];
162 int count
= Read (charBuffer
, 0, 1);
164 /* No chars available */
168 return charBuffer
[0];
171 public virtual int Read(byte[] buffer
, int index
, int count
) {
175 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
177 throw new IOException("Stream is invalid");
180 if (buffer
== null) {
181 throw new ArgumentNullException("buffer is null");
184 throw new ArgumentOutOfRangeException("index is less than 0");
187 throw new ArgumentOutOfRangeException("count is less than 0");
189 if (buffer
.Length
- index
< count
) {
190 throw new ArgumentException("buffer is too small");
193 int bytes_read
=m_stream
.Read(buffer
, index
, count
);
198 public virtual int Read(char[] buffer
, int index
, int count
) {
203 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
205 throw new IOException("Stream is invalid");
208 if (buffer
== null) {
209 throw new ArgumentNullException("buffer is null");
212 throw new ArgumentOutOfRangeException("index is less than 0");
215 throw new ArgumentOutOfRangeException("count is less than 0");
217 if (buffer
.Length
- index
< count
) {
218 throw new ArgumentException("buffer is too small");
222 return ReadCharBytes (buffer
, index
, count
, out bytes_read
);
225 private int ReadCharBytes (char[] buffer
, int index
, int count
, out int bytes_read
)
230 while (chars_read
< count
) {
233 CheckBuffer (pos
+ 1);
235 int read_byte
= m_stream
.ReadByte ();
241 m_buffer
[pos
++] = (byte)read_byte
;
244 int n
= m_encoding
.GetChars (m_buffer
, 0, pos
, buffer
, index
+ chars_read
);
254 protected int Read7BitEncodedInt() {
260 for (len
= 0; len
< 5; ++len
) {
263 ret
= ret
| ((b
& 0x7f) << shift
);
272 throw new FormatException ("Too many bytes in what should have been a 7 bit encoded Int32.");
275 public virtual bool ReadBoolean() {
277 // true if the byte is non-zero; otherwise false.
278 return ReadByte() != 0;
281 public virtual byte ReadByte() {
282 if (m_stream
== null) {
284 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
286 throw new IOException ("Stream is invalid");
289 int val
= m_stream
.ReadByte ();
293 throw new EndOfStreamException ();
296 public virtual byte[] ReadBytes(int count
) {
300 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
302 throw new IOException("Stream is invalid");
306 throw new ArgumentOutOfRangeException("count is less than 0");
309 /* Can't use FillBuffer() here, because it's OK to
310 * return fewer bytes than were requested
313 byte[] buf
= new byte[count
];
318 int n
=m_stream
.Read(buf
, pos
, count
-pos
);
328 byte[] new_buffer
=new byte[pos
];
329 Buffer
.BlockCopyInternal (buf
, 0, new_buffer
, 0, pos
);
336 public virtual char ReadChar() {
340 throw new EndOfStreamException();
346 public virtual char[] ReadChars(int count
) {
348 throw new ArgumentOutOfRangeException("count is less than 0");
354 char[] full
= new char[count
];
355 int chars
= Read(full
, 0, count
);
358 throw new EndOfStreamException();
359 } else if (chars
!= full
.Length
) {
360 char[] ret
= new char[chars
];
361 Array
.Copy(full
, 0, ret
, 0, chars
);
368 unsafe public virtual decimal ReadDecimal() {
372 byte* ret_ptr
= (byte *)&ret
;
375 * internal representation of decimal is
376 * ss32, hi32, lo32, mi32,
377 * but in stream it is
378 * lo32, mi32, hi32, ss32
379 * So we have to rerange this int32 values
382 if (BitConverter
.IsLittleEndian
) {
383 for (int i
= 0; i
< 16; i
++) {
386 ret_ptr
[i
+ 8] = m_buffer
[i
];
389 ret_ptr
[i
+ 8] = m_buffer
[i
];
392 ret_ptr
[i
- 4] = m_buffer
[i
];
395 ret_ptr
[i
- 12] = m_buffer
[i
];
399 for (int i
= 0; i
< 16; i
++) {
402 ret_ptr
[11 - i
] = m_buffer
[i
];
405 ret_ptr
[19 - i
] = m_buffer
[i
];
408 ret_ptr
[15 - i
] = m_buffer
[i
];
411 ret_ptr
[15 - i
] = m_buffer
[i
];
419 public virtual double ReadDouble() {
422 return(BitConverterLE
.ToDouble(m_buffer
, 0));
425 public virtual short ReadInt16() {
428 return((short) (m_buffer
[0] | (m_buffer
[1] << 8)));
431 public virtual int ReadInt32() {
434 return(m_buffer
[0] | (m_buffer
[1] << 8) |
435 (m_buffer
[2] << 16) | (m_buffer
[3] << 24));
438 public virtual long ReadInt64() {
441 uint ret_low
= (uint) (m_buffer
[0] |
443 (m_buffer
[2] << 16) |
446 uint ret_high
= (uint) (m_buffer
[4] |
448 (m_buffer
[6] << 16) |
451 return (long) ((((ulong) ret_high
) << 32) | ret_low
);
454 [CLSCompliant(false)]
455 public virtual sbyte ReadSByte() {
456 return (sbyte) ReadByte ();
459 public virtual string ReadString() {
460 /* Inspection of BinaryWriter-written files
461 * shows that the length is given in bytes,
464 int len
= Read7BitEncodedInt();
467 throw new IOException ("Invalid binary file (string len < 0)");
473 if (charBuffer
== null)
474 charBuffer
= new char [MaxBufferSize
];
477 // We read the string here in small chunks. Also, we
478 // Attempt to optimize the common case of short strings.
480 StringBuilder sb
= null;
482 int readLen
= (len
> MaxBufferSize
)
486 FillBuffer (readLen
);
488 int cch
= decoder
.GetChars (m_buffer
, 0, readLen
, charBuffer
, 0);
490 if (sb
== null && readLen
== len
) // ok, we got out the easy way, dont bother with the sb
491 return new String (charBuffer
, 0, cch
);
494 // Len is a fairly good estimate of the number of chars in a string
495 // Most of the time 1 byte == 1 char
496 sb
= new StringBuilder (len
);
498 sb
.Append (charBuffer
, 0, cch
);
502 return sb
.ToString();
505 public virtual float ReadSingle() {
508 return(BitConverterLE
.ToSingle(m_buffer
, 0));
511 [CLSCompliant(false)]
512 public virtual ushort ReadUInt16() {
515 return((ushort) (m_buffer
[0] | (m_buffer
[1] << 8)));
518 [CLSCompliant(false)]
519 public virtual uint ReadUInt32() {
523 return((uint) (m_buffer
[0] |
525 (m_buffer
[2] << 16) |
526 (m_buffer
[3] << 24)));
529 [CLSCompliant(false)]
530 public virtual ulong ReadUInt64() {
533 uint ret_low
= (uint) (m_buffer
[0] |
535 (m_buffer
[2] << 16) |
538 uint ret_high
= (uint) (m_buffer
[4] |
540 (m_buffer
[6] << 16) |
543 return (((ulong) ret_high
) << 32) | ret_low
;
546 /* Ensures that m_buffer is at least length bytes
547 * long, growing it if necessary
549 private void CheckBuffer(int length
)
551 if(m_buffer
.Length
<= length
) {
552 byte[] new_buffer
=new byte[length
];
553 Buffer
.BlockCopyInternal (m_buffer
, 0, new_buffer
, 0, m_buffer
.Length
);