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;
38 public class BinaryReader : IDisposable {
41 int m_encoding_max_byte;
49 // 128 chars should cover most strings in one grab.
51 const int MaxBufferSize = 128;
54 private bool m_disposed = false;
56 public BinaryReader(Stream input) : this(input, Encoding.UTF8Unmarked) {
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."));
63 throw new ArgumentException(Locale.GetText ("The stream doesn't support reading."));
66 m_encoding = encoding;
67 decoder = encoding.GetDecoder ();
68 m_buffer = new byte [32];
71 public virtual Stream BaseStream {
77 public virtual void Close() {
82 protected virtual void Dispose (bool disposing)
84 if (disposing && m_stream != null)
94 void IDisposable.Dispose()
99 protected virtual void FillBuffer (int bytes)
102 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
104 throw new IOException("Stream is invalid");
108 /* Cope with partial reads */
112 int n=m_stream.Read(m_buffer, pos, bytes-pos);
114 throw new EndOfStreamException();
121 public virtual int PeekChar() {
125 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
127 throw new IOException("Stream is invalid");
130 if ( !m_stream.CanSeek )
135 char[] result = new char[1];
139 int ccount = ReadCharBytes (result, 0, 1, out bytes, out bcount);
141 // Reposition the stream
142 m_stream.Position -= bcount;
144 // If we read 0 characters then return -1
150 // Return the single character we read
154 public virtual int Read() {
155 if (charBuffer == null)
156 charBuffer = new char [MaxBufferSize];
158 int count = Read (charBuffer, 0, 1);
160 /* No chars available */
164 return charBuffer [0];
167 public virtual int Read(byte[] buffer, int index, int count) {
171 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
173 throw new IOException("Stream is invalid");
176 if (buffer == null) {
177 throw new ArgumentNullException("buffer is null");
180 throw new ArgumentOutOfRangeException("index is less than 0");
183 throw new ArgumentOutOfRangeException("count is less than 0");
185 if (buffer.Length - index < count) {
186 throw new ArgumentException("buffer is too small");
189 int bytes_read=m_stream.Read(buffer, index, count);
194 public virtual int Read(char[] buffer, int index, int count) {
199 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
201 throw new IOException("Stream is invalid");
204 if (buffer == null) {
205 throw new ArgumentNullException("buffer is null");
208 throw new ArgumentOutOfRangeException("index is less than 0");
211 throw new ArgumentOutOfRangeException("count is less than 0");
213 if (buffer.Length - index < count) {
214 throw new ArgumentException("buffer is too small");
219 return ReadCharBytes (buffer, index, count, out bytes, out bytes_read);
222 private int ReadCharBytes(char[] buffer, int index, int count, out byte[] bytes, out int bytes_read)
\r
227 while(chars_read < count)
229 CheckBuffer(bytes_read + 1);
231 int read_byte = m_stream.ReadByte();
240 m_buffer[bytes_read]=(byte)read_byte;
243 chars_read=m_encoding.GetChars(m_buffer, 0,
253 protected int Read7BitEncodedInt() {
261 ret = ret | ((b & 0x7f) << shift);
263 } while ((b & 0x80) == 0x80);
268 public virtual bool ReadBoolean() {
270 // true if the byte is non-zero; otherwise false.
271 return ReadByte() != 0;
274 public virtual byte ReadByte() {
275 if (m_stream == null) {
277 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
279 throw new IOException ("Stream is invalid");
282 int val = m_stream.ReadByte ();
286 throw new EndOfStreamException ();
289 public virtual byte[] ReadBytes(int count) {
293 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
295 throw new IOException("Stream is invalid");
299 throw new ArgumentOutOfRangeException("count is less than 0");
302 /* Can't use FillBuffer() here, because it's OK to
303 * return fewer bytes than were requested
306 byte[] buf = new byte[count];
309 while(pos < count)
\r
311 int n=m_stream.Read(buf, pos, count-pos);
321 byte[] new_buffer=new byte[pos];
322 Buffer.BlockCopyInternal (buf, 0, new_buffer, 0, pos);
329 public virtual char ReadChar() {
333 throw new EndOfStreamException();
339 public virtual char[] ReadChars(int count) {
341 throw new ArgumentOutOfRangeException("count is less than 0");
347 char[] full = new char[count];
348 int chars = Read(full, 0, count);
351 throw new EndOfStreamException();
352 } else if (chars != full.Length) {
353 char[] ret = new char[chars];
354 Array.Copy(full, 0, ret, 0, chars);
361 unsafe public virtual decimal ReadDecimal() {
365 byte* ret_ptr = (byte *)&ret;
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
375 if (BitConverter.IsLittleEndian) {
376 for (int i = 0; i < 16; i++) {
379 ret_ptr [i + 8] = m_buffer [i];
382 ret_ptr [i + 8] = m_buffer [i];
385 ret_ptr [i - 4] = m_buffer [i];
388 ret_ptr [i - 12] = m_buffer [i];
392 for (int i = 0; i < 16; i++) {
395 ret_ptr [11 - i] = m_buffer [i];
398 ret_ptr [19 - i] = m_buffer [i];
401 ret_ptr [15 - i] = m_buffer [i];
404 ret_ptr [15 - i] = m_buffer [i];
412 public virtual double ReadDouble() {
415 return(BitConverterLE.ToDouble(m_buffer, 0));
418 public virtual short ReadInt16() {
421 return((short) (m_buffer[0] | (m_buffer[1] << 8)));
424 public virtual int ReadInt32() {
427 return(m_buffer[0] | (m_buffer[1] << 8) |
428 (m_buffer[2] << 16) | (m_buffer[3] << 24));
431 public virtual long ReadInt64() {
434 uint ret_low = (uint) (m_buffer[0] |
436 (m_buffer[2] << 16) |
439 uint ret_high = (uint) (m_buffer[4] |
441 (m_buffer[6] << 16) |
444 return (long) ((((ulong) ret_high) << 32) | ret_low);
447 [CLSCompliant(false)]
448 public virtual sbyte ReadSByte() {
449 return (sbyte) ReadByte ();
452 public virtual string ReadString() {
453 /* Inspection of BinaryWriter-written files
454 * shows that the length is given in bytes,
457 int len = Read7BitEncodedInt();
460 throw new IOException ("Invalid binary file (string len < 0)");
466 if (charBuffer == null)
467 charBuffer = new char [MaxBufferSize];
470 // We read the string here in small chunks. Also, we
471 // Attempt to optimize the common case of short strings.
473 StringBuilder sb = null;
475 int readLen = (len > MaxBufferSize)
479 FillBuffer (readLen);
481 int cch = decoder.GetChars (m_buffer, 0, readLen, charBuffer, 0);
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);
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);
491 sb.Append (charBuffer, 0, cch);
495 return sb.ToString();
498 public virtual float ReadSingle() {
501 return(BitConverterLE.ToSingle(m_buffer, 0));
504 [CLSCompliant(false)]
505 public virtual ushort ReadUInt16() {
508 return((ushort) (m_buffer[0] | (m_buffer[1] << 8)));
511 [CLSCompliant(false)]
512 public virtual uint ReadUInt32() {
516 return((uint) (m_buffer[0] |
518 (m_buffer[2] << 16) |
519 (m_buffer[3] << 24)));
522 [CLSCompliant(false)]
523 public virtual ulong ReadUInt64() {
526 uint ret_low = (uint) (m_buffer[0] |
528 (m_buffer[2] << 16) |
531 uint ret_high = (uint) (m_buffer[4] |
533 (m_buffer[6] << 16) |
536 return (((ulong) ret_high) << 32) | ret_low;
539 /* Ensures that m_buffer is at least length bytes
540 * long, growing it if necessary
542 private void CheckBuffer(int length)
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);