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 char[] decode = new char[1];
157 int count=Read(decode, 0, 1);
159 /* No chars available */
166 public virtual int Read(byte[] buffer, int index, int count) {
170 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
172 throw new IOException("Stream is invalid");
175 if (buffer == null) {
176 throw new ArgumentNullException("buffer is null");
179 throw new ArgumentOutOfRangeException("index is less than 0");
182 throw new ArgumentOutOfRangeException("count is less than 0");
184 if (buffer.Length - index < count) {
185 throw new ArgumentException("buffer is too small");
188 int bytes_read=m_stream.Read(buffer, index, count);
193 public virtual int Read(char[] buffer, int index, int count) {
198 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
200 throw new IOException("Stream is invalid");
203 if (buffer == null) {
204 throw new ArgumentNullException("buffer is null");
207 throw new ArgumentOutOfRangeException("index is less than 0");
210 throw new ArgumentOutOfRangeException("count is less than 0");
212 if (buffer.Length - index < count) {
213 throw new ArgumentException("buffer is too small");
218 return ReadCharBytes (buffer, index, count, out bytes, out bytes_read);
221 private int ReadCharBytes(char[] buffer, int index, int count, out byte[] bytes, out int bytes_read)
\r
226 while(chars_read < count)
228 CheckBuffer(bytes_read + 1);
230 int read_byte = m_stream.ReadByte();
239 m_buffer[bytes_read]=(byte)read_byte;
242 chars_read=m_encoding.GetChars(m_buffer, 0,
252 protected int Read7BitEncodedInt() {
260 ret = ret | ((b & 0x7f) << shift);
262 } while ((b & 0x80) == 0x80);
267 public virtual bool ReadBoolean() {
269 // true if the byte is non-zero; otherwise false.
270 return ReadByte() != 0;
273 public virtual byte ReadByte() {
274 if (m_stream == null) {
276 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
278 throw new IOException ("Stream is invalid");
281 int val = m_stream.ReadByte ();
285 throw new EndOfStreamException ();
288 public virtual byte[] ReadBytes(int count) {
292 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
294 throw new IOException("Stream is invalid");
298 throw new ArgumentOutOfRangeException("count is less than 0");
301 /* Can't use FillBuffer() here, because it's OK to
302 * return fewer bytes than were requested
305 byte[] buf = new byte[count];
308 while(pos < count)
\r
310 int n=m_stream.Read(buf, pos, count-pos);
320 byte[] new_buffer=new byte[pos];
321 Buffer.BlockCopyInternal (buf, 0, new_buffer, 0, pos);
328 public virtual char ReadChar() {
332 throw new EndOfStreamException();
338 public virtual char[] ReadChars(int count) {
340 throw new ArgumentOutOfRangeException("count is less than 0");
346 char[] full = new char[count];
347 int chars = Read(full, 0, count);
350 throw new EndOfStreamException();
351 } else if (chars != full.Length) {
352 char[] ret = new char[chars];
353 Array.Copy(full, 0, ret, 0, chars);
360 unsafe public virtual decimal ReadDecimal() {
364 byte* ret_ptr = (byte *)&ret;
367 * internal representation of decimal is
368 * ss32, hi32, lo32, mi32,
369 * but in stream it is
370 * lo32, mi32, hi32, ss32
371 * So we have to rerange this int32 values
374 if (BitConverter.IsLittleEndian) {
375 for (int i = 0; i < 16; i++) {
378 ret_ptr [i + 8] = m_buffer [i];
381 ret_ptr [i + 8] = m_buffer [i];
384 ret_ptr [i - 4] = m_buffer [i];
387 ret_ptr [i - 12] = m_buffer [i];
391 for (int i = 0; i < 16; i++) {
394 ret_ptr [11 - i] = m_buffer [i];
397 ret_ptr [19 - i] = m_buffer [i];
400 ret_ptr [15 - i] = m_buffer [i];
403 ret_ptr [15 - i] = m_buffer [i];
411 public virtual double ReadDouble() {
414 return(BitConverterLE.ToDouble(m_buffer, 0));
417 public virtual short ReadInt16() {
420 return((short) (m_buffer[0] | (m_buffer[1] << 8)));
423 public virtual int ReadInt32() {
426 return(m_buffer[0] | (m_buffer[1] << 8) |
427 (m_buffer[2] << 16) | (m_buffer[3] << 24));
430 public virtual long ReadInt64() {
433 uint ret_low = (uint) (m_buffer[0] |
435 (m_buffer[2] << 16) |
438 uint ret_high = (uint) (m_buffer[4] |
440 (m_buffer[6] << 16) |
443 return (long) ((((ulong) ret_high) << 32) | ret_low);
446 [CLSCompliant(false)]
447 public virtual sbyte ReadSByte() {
448 return (sbyte) ReadByte ();
451 public virtual string ReadString() {
452 /* Inspection of BinaryWriter-written files
453 * shows that the length is given in bytes,
456 int len = Read7BitEncodedInt();
459 throw new IOException ("Invalid binary file (string len < 0)");
465 if (charBuffer == null)
466 charBuffer = new char [MaxBufferSize];
469 // We read the string here in small chunks. Also, we
470 // Attempt to optimize the common case of short strings.
472 StringBuilder sb = null;
474 int readLen = (len > MaxBufferSize)
478 FillBuffer (readLen);
480 int cch = decoder.GetChars (m_buffer, 0, readLen, charBuffer, 0);
482 if (sb == null && readLen == len) // ok, we got out the easy way, dont bother with the sb
483 return new String (charBuffer, 0, cch);
486 // Len is a fairly good estimate of the number of chars in a string
487 // Most of the time 1 byte == 1 char
488 sb = new StringBuilder (len);
490 sb.Append (charBuffer, 0, cch);
494 return sb.ToString();
497 public virtual float ReadSingle() {
500 return(BitConverterLE.ToSingle(m_buffer, 0));
503 [CLSCompliant(false)]
504 public virtual ushort ReadUInt16() {
507 return((ushort) (m_buffer[0] | (m_buffer[1] << 8)));
510 [CLSCompliant(false)]
511 public virtual uint ReadUInt32() {
515 return((uint) (m_buffer[0] |
517 (m_buffer[2] << 16) |
518 (m_buffer[3] << 24)));
521 [CLSCompliant(false)]
522 public virtual ulong ReadUInt64() {
525 uint ret_low = (uint) (m_buffer[0] |
527 (m_buffer[2] << 16) |
530 uint ret_high = (uint) (m_buffer[4] |
532 (m_buffer[6] << 16) |
535 return (((ulong) ret_high) << 32) | ret_low;
538 /* Ensures that m_buffer is at least length bytes
539 * long, growing it if necessary
541 private void CheckBuffer(int length)
543 if(m_buffer.Length <= length) {
544 byte[] new_buffer=new byte[length];
545 Buffer.BlockCopyInternal (m_buffer, 0, new_buffer, 0, m_buffer.Length);