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;
37 using System.Runtime.InteropServices;
44 public class BinaryReader : IDisposable {
47 int m_encoding_max_byte;
55 // 128 chars should cover most strings in one grab.
57 const int MaxBufferSize = 128;
60 private bool m_disposed = false;
62 public BinaryReader(Stream input) : this(input, Encoding.UTF8UnmarkedUnsafe) {
65 public BinaryReader(Stream input, Encoding encoding) {
66 if (input == null || encoding == null)
67 throw new ArgumentNullException(Locale.GetText ("Input or Encoding is a null reference."));
69 throw new ArgumentException(Locale.GetText ("The stream doesn't support reading."));
72 m_encoding = encoding;
73 decoder = encoding.GetDecoder ();
74 m_buffer = new byte [32];
77 public virtual Stream BaseStream {
83 public virtual void Close() {
88 protected virtual void Dispose (bool disposing)
90 if (disposing && m_stream != null)
100 void IDisposable.Dispose()
105 protected virtual void FillBuffer (int bytes)
108 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
110 throw new IOException("Stream is invalid");
114 /* Cope with partial reads */
118 int n=m_stream.Read(m_buffer, pos, bytes-pos);
120 throw new EndOfStreamException();
127 public virtual int PeekChar() {
131 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
133 throw new IOException("Stream is invalid");
136 if ( !m_stream.CanSeek )
141 char[] result = new char[1];
145 int ccount = ReadCharBytes (result, 0, 1, out bytes, out bcount);
147 // Reposition the stream
148 m_stream.Position -= bcount;
150 // If we read 0 characters then return -1
156 // Return the single character we read
160 public virtual int Read() {
161 if (charBuffer == null)
162 charBuffer = new char [MaxBufferSize];
164 int count = Read (charBuffer, 0, 1);
166 /* No chars available */
170 return charBuffer [0];
173 public virtual int Read(byte[] buffer, int index, int count) {
177 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
179 throw new IOException("Stream is invalid");
182 if (buffer == null) {
183 throw new ArgumentNullException("buffer is null");
186 throw new ArgumentOutOfRangeException("index is less than 0");
189 throw new ArgumentOutOfRangeException("count is less than 0");
191 if (buffer.Length - index < count) {
192 throw new ArgumentException("buffer is too small");
195 int bytes_read=m_stream.Read(buffer, index, count);
200 public virtual int Read(char[] buffer, int index, int count) {
205 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
207 throw new IOException("Stream is invalid");
210 if (buffer == null) {
211 throw new ArgumentNullException("buffer is null");
214 throw new ArgumentOutOfRangeException("index is less than 0");
217 throw new ArgumentOutOfRangeException("count is less than 0");
219 if (buffer.Length - index < count) {
220 throw new ArgumentException("buffer is too small");
225 return ReadCharBytes (buffer, index, count, out bytes, out bytes_read);
228 private int ReadCharBytes(char[] buffer, int index, int count, out byte[] bytes, out int bytes_read)
233 while(chars_read < count)
235 CheckBuffer(bytes_read + 1);
237 int read_byte = m_stream.ReadByte();
246 m_buffer[bytes_read]=(byte)read_byte;
249 chars_read=m_encoding.GetChars(m_buffer, 0,
259 protected int Read7BitEncodedInt() {
267 ret = ret | ((b & 0x7f) << shift);
269 } while ((b & 0x80) == 0x80);
274 public virtual bool ReadBoolean() {
276 // true if the byte is non-zero; otherwise false.
277 return ReadByte() != 0;
280 public virtual byte ReadByte() {
281 if (m_stream == null) {
283 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
285 throw new IOException ("Stream is invalid");
288 int val = m_stream.ReadByte ();
292 throw new EndOfStreamException ();
295 public virtual byte[] ReadBytes(int count) {
299 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
301 throw new IOException("Stream is invalid");
305 throw new ArgumentOutOfRangeException("count is less than 0");
308 /* Can't use FillBuffer() here, because it's OK to
309 * return fewer bytes than were requested
312 byte[] buf = new byte[count];
317 int n=m_stream.Read(buf, pos, count-pos);
327 byte[] new_buffer=new byte[pos];
328 Buffer.BlockCopyInternal (buf, 0, new_buffer, 0, pos);
335 public virtual char ReadChar() {
339 throw new EndOfStreamException();
345 public virtual char[] ReadChars(int count) {
347 throw new ArgumentOutOfRangeException("count is less than 0");
353 char[] full = new char[count];
354 int chars = Read(full, 0, count);
357 throw new EndOfStreamException();
358 } else if (chars != full.Length) {
359 char[] ret = new char[chars];
360 Array.Copy(full, 0, ret, 0, chars);
367 unsafe public virtual decimal ReadDecimal() {
371 byte* ret_ptr = (byte *)&ret;
374 * internal representation of decimal is
375 * ss32, hi32, lo32, mi32,
376 * but in stream it is
377 * lo32, mi32, hi32, ss32
378 * So we have to rerange this int32 values
381 if (BitConverter.IsLittleEndian) {
382 for (int i = 0; i < 16; i++) {
385 ret_ptr [i + 8] = m_buffer [i];
388 ret_ptr [i + 8] = m_buffer [i];
391 ret_ptr [i - 4] = m_buffer [i];
394 ret_ptr [i - 12] = m_buffer [i];
398 for (int i = 0; i < 16; i++) {
401 ret_ptr [11 - i] = m_buffer [i];
404 ret_ptr [19 - i] = m_buffer [i];
407 ret_ptr [15 - i] = m_buffer [i];
410 ret_ptr [15 - i] = m_buffer [i];
418 public virtual double ReadDouble() {
421 return(BitConverterLE.ToDouble(m_buffer, 0));
424 public virtual short ReadInt16() {
427 return((short) (m_buffer[0] | (m_buffer[1] << 8)));
430 public virtual int ReadInt32() {
433 return(m_buffer[0] | (m_buffer[1] << 8) |
434 (m_buffer[2] << 16) | (m_buffer[3] << 24));
437 public virtual long ReadInt64() {
440 uint ret_low = (uint) (m_buffer[0] |
442 (m_buffer[2] << 16) |
445 uint ret_high = (uint) (m_buffer[4] |
447 (m_buffer[6] << 16) |
450 return (long) ((((ulong) ret_high) << 32) | ret_low);
453 [CLSCompliant(false)]
454 public virtual sbyte ReadSByte() {
455 return (sbyte) ReadByte ();
458 public virtual string ReadString() {
459 /* Inspection of BinaryWriter-written files
460 * shows that the length is given in bytes,
463 int len = Read7BitEncodedInt();
466 throw new IOException ("Invalid binary file (string len < 0)");
472 if (charBuffer == null)
473 charBuffer = new char [MaxBufferSize];
476 // We read the string here in small chunks. Also, we
477 // Attempt to optimize the common case of short strings.
479 StringBuilder sb = null;
481 int readLen = (len > MaxBufferSize)
485 FillBuffer (readLen);
487 int cch = decoder.GetChars (m_buffer, 0, readLen, charBuffer, 0);
489 if (sb == null && readLen == len) // ok, we got out the easy way, dont bother with the sb
490 return new String (charBuffer, 0, cch);
493 // Len is a fairly good estimate of the number of chars in a string
494 // Most of the time 1 byte == 1 char
495 sb = new StringBuilder (len);
497 sb.Append (charBuffer, 0, cch);
501 return sb.ToString();
504 public virtual float ReadSingle() {
507 return(BitConverterLE.ToSingle(m_buffer, 0));
510 [CLSCompliant(false)]
511 public virtual ushort ReadUInt16() {
514 return((ushort) (m_buffer[0] | (m_buffer[1] << 8)));
517 [CLSCompliant(false)]
518 public virtual uint ReadUInt32() {
522 return((uint) (m_buffer[0] |
524 (m_buffer[2] << 16) |
525 (m_buffer[3] << 24)));
528 [CLSCompliant(false)]
529 public virtual ulong ReadUInt64() {
532 uint ret_low = (uint) (m_buffer[0] |
534 (m_buffer[2] << 16) |
537 uint ret_high = (uint) (m_buffer[4] |
539 (m_buffer[6] << 16) |
542 return (((ulong) ret_high) << 32) | ret_low;
545 /* Ensures that m_buffer is at least length bytes
546 * long, growing it if necessary
548 private void CheckBuffer(int length)
550 if(m_buffer.Length <= length) {
551 byte[] new_buffer=new byte[length];
552 Buffer.BlockCopyInternal (m_buffer, 0, new_buffer, 0, m_buffer.Length);