2010-04-06 Jb Evain <jbevain@novell.com>
[mcs.git] / class / corlib / System.IO / BinaryReader.cs
blobd6dd9c96afdfd21725721e24589e7f6cec459b45
1 //
2 // System.IO.BinaryReader
3 //
4 // Author:
5 // Matt Kimball (matt@kimball.net)
6 // Dick Porter (dick@ximian.com)
7 //
9 //
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:
19 //
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 //
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.
32 using System;
33 using System.Text;
34 using System.Globalization;
35 using Mono.Security;
36 using System.Runtime.InteropServices;
38 namespace System.IO {
39 [ComVisible (true)]
40 public class BinaryReader : IDisposable {
41 Stream m_stream;
42 Encoding m_encoding;
44 byte[] m_buffer;
46 Decoder decoder;
47 char [] charBuffer;
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."));
63 if (!input.CanRead)
64 throw new ArgumentException(Locale.GetText ("The stream doesn't support reading."));
66 m_stream = input;
67 m_encoding = encoding;
68 decoder = encoding.GetDecoder ();
69 m_buffer = new byte [32];
72 public virtual Stream BaseStream {
73 get {
74 return m_stream;
78 public virtual void Close() {
79 Dispose (true);
80 m_disposed = true;
83 protected virtual void Dispose (bool disposing)
85 if (disposing && m_stream != null)
86 m_stream.Close ();
88 m_disposed = true;
89 m_buffer = null;
90 m_encoding = null;
91 m_stream = null;
92 charBuffer = null;
95 #if NET_4_0
96 public void Dispose ()
97 #else
98 void IDisposable.Dispose()
99 #endif
101 Dispose (true);
104 protected virtual void FillBuffer (int numBytes)
106 if (m_disposed)
107 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
108 if (m_stream==null)
109 throw new IOException("Stream is invalid");
111 CheckBuffer(numBytes);
113 /* Cope with partial reads */
114 int pos=0;
116 while(pos<numBytes) {
117 int n=m_stream.Read(m_buffer, pos, numBytes-pos);
118 if(n==0) {
119 throw new EndOfStreamException();
122 pos+=n;
126 public virtual int PeekChar() {
127 if(m_stream==null) {
129 if (m_disposed)
130 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
132 throw new IOException("Stream is invalid");
135 if ( !m_stream.CanSeek )
137 return -1;
140 char[] result = new char[1];
141 int bcount;
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
149 if (ccount == 0)
151 return -1;
154 // Return the single character we read
155 return result[0];
158 public virtual int Read() {
159 if (charBuffer == null)
160 charBuffer = new char [MaxBufferSize];
162 int count = Read (charBuffer, 0, 1);
163 if(count == 0) {
164 /* No chars available */
165 return -1;
168 return charBuffer [0];
171 public virtual int Read(byte[] buffer, int index, int count) {
172 if(m_stream==null) {
174 if (m_disposed)
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");
183 if (index < 0) {
184 throw new ArgumentOutOfRangeException("index is less than 0");
186 if (count < 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);
195 return(bytes_read);
198 public virtual int Read(char[] buffer, int index, int count) {
200 if(m_stream==null) {
202 if (m_disposed)
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");
211 if (index < 0) {
212 throw new ArgumentOutOfRangeException("index is less than 0");
214 if (count < 0) {
215 throw new ArgumentOutOfRangeException("count is less than 0");
217 if (buffer.Length - index < count) {
218 throw new ArgumentException("buffer is too small");
221 int bytes_read;
222 return ReadCharBytes (buffer, index, count, out bytes_read);
225 private int ReadCharBytes (char[] buffer, int index, int count, out int bytes_read)
227 int chars_read = 0;
228 bytes_read = 0;
230 while (chars_read < count) {
231 int pos = 0;
232 while (true) {
233 CheckBuffer (pos + 1);
235 int read_byte = m_stream.ReadByte ();
237 if (read_byte == -1)
238 /* EOF */
239 return chars_read;
241 m_buffer [pos ++] = (byte)read_byte;
242 bytes_read ++;
244 int n = m_encoding.GetChars (m_buffer, 0, pos, buffer, index + chars_read);
245 if (n > 0)
246 break;
248 chars_read ++;
251 return chars_read;
254 protected int Read7BitEncodedInt() {
255 int ret = 0;
256 int shift = 0;
257 int len;
258 byte b;
260 for (len = 0; len < 5; ++len) {
261 b = ReadByte();
263 ret = ret | ((b & 0x7f) << shift);
264 shift += 7;
265 if ((b & 0x80) == 0)
266 break;
269 if (len < 5)
270 return ret;
271 else
272 throw new FormatException ("Too many bytes in what should have been a 7 bit encoded Int32.");
275 public virtual bool ReadBoolean() {
276 // Return value:
277 // true if the byte is non-zero; otherwise false.
278 return ReadByte() != 0;
281 public virtual byte ReadByte() {
282 if (m_stream == null) {
283 if (m_disposed)
284 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
286 throw new IOException ("Stream is invalid");
289 int val = m_stream.ReadByte ();
290 if (val != -1)
291 return (byte) val;
293 throw new EndOfStreamException ();
296 public virtual byte[] ReadBytes(int count) {
297 if(m_stream==null) {
299 if (m_disposed)
300 throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
302 throw new IOException("Stream is invalid");
305 if (count < 0) {
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];
314 int pos=0;
316 while(pos < count)
318 int n=m_stream.Read(buf, pos, count-pos);
319 if(n==0) {
320 /* EOF */
321 break;
324 pos+=n;
327 if (pos!=count) {
328 byte[] new_buffer=new byte[pos];
329 Buffer.BlockCopyInternal (buf, 0, new_buffer, 0, pos);
330 return(new_buffer);
333 return(buf);
336 public virtual char ReadChar() {
337 int ch=Read();
339 if(ch==-1) {
340 throw new EndOfStreamException();
343 return((char)ch);
346 public virtual char[] ReadChars(int count) {
347 if (count < 0) {
348 throw new ArgumentOutOfRangeException("count is less than 0");
351 if (count == 0)
352 return new char [0];
354 char[] full = new char[count];
355 int chars = Read(full, 0, count);
357 if (chars == 0) {
358 throw new EndOfStreamException();
359 } else if (chars != full.Length) {
360 char[] ret = new char[chars];
361 Array.Copy(full, 0, ret, 0, chars);
362 return ret;
363 } else {
364 return full;
368 unsafe public virtual decimal ReadDecimal() {
369 FillBuffer(16);
371 decimal ret;
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++) {
384 if (i < 4) {
385 // lo 8 - 12
386 ret_ptr [i + 8] = m_buffer [i];
387 } else if (i < 8) {
388 // mid 12 - 16
389 ret_ptr [i + 8] = m_buffer [i];
390 } else if (i < 12) {
391 // hi 4 - 8
392 ret_ptr [i - 4] = m_buffer [i];
393 } else if (i < 16) {
394 // ss 0 - 4
395 ret_ptr [i - 12] = m_buffer [i];
398 } else {
399 for (int i = 0; i < 16; i++) {
400 if (i < 4) {
401 // lo 8 - 12
402 ret_ptr [11 - i] = m_buffer [i];
403 } else if (i < 8) {
404 // mid 12 - 16
405 ret_ptr [19 - i] = m_buffer [i];
406 } else if (i < 12) {
407 // hi 4 - 8
408 ret_ptr [15 - i] = m_buffer [i];
409 } else if (i < 16) {
410 // ss 0 - 4
411 ret_ptr [15 - i] = m_buffer [i];
416 return ret;
419 public virtual double ReadDouble() {
420 FillBuffer(8);
422 return(BitConverterLE.ToDouble(m_buffer, 0));
425 public virtual short ReadInt16() {
426 FillBuffer(2);
428 return((short) (m_buffer[0] | (m_buffer[1] << 8)));
431 public virtual int ReadInt32() {
432 FillBuffer(4);
434 return(m_buffer[0] | (m_buffer[1] << 8) |
435 (m_buffer[2] << 16) | (m_buffer[3] << 24));
438 public virtual long ReadInt64() {
439 FillBuffer(8);
441 uint ret_low = (uint) (m_buffer[0] |
442 (m_buffer[1] << 8) |
443 (m_buffer[2] << 16) |
444 (m_buffer[3] << 24)
446 uint ret_high = (uint) (m_buffer[4] |
447 (m_buffer[5] << 8) |
448 (m_buffer[6] << 16) |
449 (m_buffer[7] << 24)
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,
462 * not chars
464 int len = Read7BitEncodedInt();
466 if (len < 0)
467 throw new IOException ("Invalid binary file (string len < 0)");
469 if (len == 0)
470 return String.Empty;
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;
481 do {
482 int readLen = (len > MaxBufferSize)
483 ? MaxBufferSize
484 : len;
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);
493 if (sb == null)
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);
499 len -= readLen;
500 } while (len > 0);
502 return sb.ToString();
505 public virtual float ReadSingle() {
506 FillBuffer(4);
508 return(BitConverterLE.ToSingle(m_buffer, 0));
511 [CLSCompliant(false)]
512 public virtual ushort ReadUInt16() {
513 FillBuffer(2);
515 return((ushort) (m_buffer[0] | (m_buffer[1] << 8)));
518 [CLSCompliant(false)]
519 public virtual uint ReadUInt32() {
520 FillBuffer(4);
523 return((uint) (m_buffer[0] |
524 (m_buffer[1] << 8) |
525 (m_buffer[2] << 16) |
526 (m_buffer[3] << 24)));
529 [CLSCompliant(false)]
530 public virtual ulong ReadUInt64() {
531 FillBuffer(8);
533 uint ret_low = (uint) (m_buffer[0] |
534 (m_buffer[1] << 8) |
535 (m_buffer[2] << 16) |
536 (m_buffer[3] << 24)
538 uint ret_high = (uint) (m_buffer[4] |
539 (m_buffer[5] << 8) |
540 (m_buffer[6] << 16) |
541 (m_buffer[7] << 24)
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);
554 m_buffer=new_buffer;