2 // System.IO.BinaryReader
5 // Matt Kimball (matt@kimball.net)
6 // Dick Porter (dick@ximian.com)
7 // Marek Safar (marek.safar@gmail.com)
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
12 // Copyright 2011 Xamarin Inc.
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Globalization;
38 using System.Runtime.InteropServices;
42 public class BinaryReader : IDisposable {
50 byte[] charByteBuffer;
53 // 128 chars should cover most strings in one grab.
55 const int MaxBufferSize = 128;
58 private bool m_disposed;
60 public BinaryReader(Stream input)
61 : this(input, Encoding.UTF8UnmarkedUnsafe)
66 readonly bool leave_open;
68 public BinaryReader(Stream input, Encoding encoding)
69 : this (input, encoding, false)
73 public BinaryReader(Stream input, Encoding encoding, bool leaveOpen)
75 const bool leave_open = false;
77 public BinaryReader(Stream input, Encoding encoding)
80 if (input == null || encoding == null)
81 throw new ArgumentNullException(Locale.GetText ("Input or Encoding is a null reference."));
83 throw new ArgumentException(Locale.GetText ("The stream doesn't support reading."));
86 m_encoding = encoding;
88 leave_open = leaveOpen;
90 decoder = encoding.GetDecoder ();
92 // internal buffer size is documented to be between 16 and the value
93 // returned by GetMaxByteCount for the specified encoding
94 m_buffer = new byte [Math.Max (16, encoding.GetMaxByteCount (1))];
97 public virtual Stream BaseStream {
103 public virtual void Close() {
108 protected virtual void Dispose (bool disposing)
110 if (disposing && m_stream != null && !leave_open)
120 #if NET_4_0 || NET_2_1
121 public void Dispose ()
123 void IDisposable.Dispose()
129 protected virtual void FillBuffer (int numBytes)
131 if (numBytes > m_buffer.Length)
132 throw new ArgumentOutOfRangeException ("numBytes");
134 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
136 throw new IOException("Stream is invalid");
138 /* Cope with partial reads */
141 while(pos<numBytes) {
142 int n=m_stream.Read(m_buffer, pos, numBytes-pos);
144 throw new EndOfStreamException();
151 public virtual int PeekChar() {
155 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
157 throw new IOException("Stream is invalid");
160 if ( !m_stream.CanSeek )
165 char[] result = new char[1];
168 int ccount = ReadCharBytes (result, 0, 1, out bcount);
170 // Reposition the stream
171 m_stream.Position -= bcount;
173 // If we read 0 characters then return -1
179 // Return the single character we read
183 public virtual int Read() {
184 if (charBuffer == null)
185 charBuffer = new char [MaxBufferSize];
187 int count = Read (charBuffer, 0, 1);
189 /* No chars available */
193 return charBuffer [0];
196 public virtual int Read(byte[] buffer, int index, int count) {
200 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
202 throw new IOException("Stream is invalid");
205 if (buffer == null) {
206 throw new ArgumentNullException("buffer is null");
209 throw new ArgumentOutOfRangeException("index is less than 0");
212 throw new ArgumentOutOfRangeException("count is less than 0");
214 if (buffer.Length - index < count) {
215 throw new ArgumentException("buffer is too small");
218 int bytes_read=m_stream.Read(buffer, index, count);
223 public virtual int Read(char[] buffer, int index, int count) {
228 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
230 throw new IOException("Stream is invalid");
233 if (buffer == null) {
234 throw new ArgumentNullException("buffer is null");
237 throw new ArgumentOutOfRangeException("index is less than 0");
240 throw new ArgumentOutOfRangeException("count is less than 0");
242 if (buffer.Length - index < count) {
243 throw new ArgumentException("buffer is too small");
247 return ReadCharBytes (buffer, index, count, out bytes_read);
250 private int ReadCharBytes (char[] buffer, int index, int count, out int bytes_read)
255 while (chars_read < count) {
258 CheckBuffer (pos + 1);
260 int read_byte = m_stream.ReadByte ();
266 m_buffer [pos ++] = (byte)read_byte;
269 int n = m_encoding.GetChars (m_buffer, 0, pos, buffer, index + chars_read);
279 protected int Read7BitEncodedInt() {
285 for (len = 0; len < 5; ++len) {
288 ret = ret | ((b & 0x7f) << shift);
297 throw new FormatException ("Too many bytes in what should have been a 7 bit encoded Int32.");
300 public virtual bool ReadBoolean() {
302 // true if the byte is non-zero; otherwise false.
303 return ReadByte() != 0;
306 public virtual byte ReadByte() {
307 if (m_stream == null) {
309 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
311 throw new IOException ("Stream is invalid");
314 int val = m_stream.ReadByte ();
318 throw new EndOfStreamException ();
321 public virtual byte[] ReadBytes(int count) {
325 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
327 throw new IOException("Stream is invalid");
331 throw new ArgumentOutOfRangeException("count is less than 0");
334 /* Can't use FillBuffer() here, because it's OK to
335 * return fewer bytes than were requested
338 byte[] buf = new byte[count];
343 int n=m_stream.Read(buf, pos, count-pos);
353 byte[] new_buffer=new byte[pos];
354 Buffer.BlockCopyInternal (buf, 0, new_buffer, 0, pos);
361 public virtual char ReadChar() {
365 throw new EndOfStreamException();
371 public virtual char[] ReadChars(int count) {
373 throw new ArgumentOutOfRangeException("count is less than 0");
379 char[] full = new char[count];
380 int chars = Read(full, 0, count);
383 throw new EndOfStreamException();
384 } else if (chars != full.Length) {
385 char[] ret = new char[chars];
386 Array.Copy(full, 0, ret, 0, chars);
393 unsafe public virtual decimal ReadDecimal() {
397 byte* ret_ptr = (byte *)&ret;
400 * internal representation of decimal is
401 * ss32, hi32, lo32, mi32,
402 * but in stream it is
403 * lo32, mi32, hi32, ss32
404 * So we have to rerange this int32 values
407 if (BitConverter.IsLittleEndian) {
408 for (int i = 0; i < 16; i++) {
411 ret_ptr [i + 8] = m_buffer [i];
414 ret_ptr [i + 8] = m_buffer [i];
417 ret_ptr [i - 4] = m_buffer [i];
420 ret_ptr [i - 12] = m_buffer [i];
424 for (int i = 0; i < 16; i++) {
427 ret_ptr [11 - i] = m_buffer [i];
430 ret_ptr [19 - i] = m_buffer [i];
433 ret_ptr [15 - i] = m_buffer [i];
436 ret_ptr [15 - i] = m_buffer [i];
444 public virtual double ReadDouble() {
447 return(BitConverterLE.ToDouble(m_buffer, 0));
450 public virtual short ReadInt16() {
453 return((short) (m_buffer[0] | (m_buffer[1] << 8)));
456 public virtual int ReadInt32() {
459 return(m_buffer[0] | (m_buffer[1] << 8) |
460 (m_buffer[2] << 16) | (m_buffer[3] << 24));
463 public virtual long ReadInt64() {
466 uint ret_low = (uint) (m_buffer[0] |
468 (m_buffer[2] << 16) |
471 uint ret_high = (uint) (m_buffer[4] |
473 (m_buffer[6] << 16) |
476 return (long) ((((ulong) ret_high) << 32) | ret_low);
479 [CLSCompliant(false)]
480 public virtual sbyte ReadSByte() {
481 return (sbyte) ReadByte ();
484 public virtual string ReadString() {
485 /* Inspection of BinaryWriter-written files
486 * shows that the length is given in bytes,
489 int len = Read7BitEncodedInt();
492 throw new IOException ("Invalid binary file (string len < 0)");
497 if (charByteBuffer == null) {
498 charBuffer = new char [m_encoding.GetMaxByteCount (MaxBufferSize)];
499 charByteBuffer = new byte [MaxBufferSize];
503 // We read the string here in small chunks. Also, we
504 // Attempt to optimize the common case of short strings.
506 StringBuilder sb = null;
508 int readLen = Math.Min (MaxBufferSize, len);
510 int n = m_stream.Read (charByteBuffer, 0, readLen);
512 throw new EndOfStreamException();
514 int cch = decoder.GetChars (charByteBuffer, 0, n, charBuffer, 0);
516 if (sb == null && readLen == len) // ok, we got out the easy way, dont bother with the sb
517 return new String (charBuffer, 0, cch);
520 // Len is a fairly good estimate of the number of chars in a string
521 // Most of the time 1 byte == 1 char
522 sb = new StringBuilder (len);
524 sb.Append (charBuffer, 0, cch);
528 return sb.ToString();
531 public virtual float ReadSingle() {
534 return(BitConverterLE.ToSingle(m_buffer, 0));
537 [CLSCompliant(false)]
538 public virtual ushort ReadUInt16() {
541 return((ushort) (m_buffer[0] | (m_buffer[1] << 8)));
544 [CLSCompliant(false)]
545 public virtual uint ReadUInt32() {
549 return((uint) (m_buffer[0] |
551 (m_buffer[2] << 16) |
552 (m_buffer[3] << 24)));
555 [CLSCompliant(false)]
556 public virtual ulong ReadUInt64() {
559 uint ret_low = (uint) (m_buffer[0] |
561 (m_buffer[2] << 16) |
564 uint ret_high = (uint) (m_buffer[4] |
566 (m_buffer[6] << 16) |
569 return (((ulong) ret_high) << 32) | ret_low;
572 /* Ensures that m_buffer is at least length bytes
573 * long, growing it if necessary
575 private void CheckBuffer(int length)
577 if(m_buffer.Length <= length) {
578 byte[] new_buffer=new byte[length];
579 Buffer.BlockCopyInternal (m_buffer, 0, new_buffer, 0, m_buffer.Length);