2006-06-02 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / class / corlib / System.IO / BinaryReader.cs
index 51408c5baa8870f0538b3b7ee4d632204e7d28a4..510d9dd58ba74d12d212dc7c0221be839a7e4936 100644 (file)
@@ -6,9 +6,33 @@
 //   Dick Porter (dick@ximian.com)
 //
 
+//
+// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
 using System;
 using System.Text;
 using System.Globalization;
+using Mono.Security;
 
 namespace System.IO {
        public class BinaryReader : IDisposable {
@@ -17,6 +41,15 @@ namespace System.IO {
                int m_encoding_max_byte;
 
                byte[] m_buffer;
+
+               Decoder decoder;
+               char [] charBuffer;
+               
+               //
+               // 128 chars should cover most strings in one grab.
+               //
+               const int MaxBufferSize = 128;
+
                
                private bool m_disposed = false;
 
@@ -31,7 +64,7 @@ namespace System.IO {
 
                        m_stream = input;
                        m_encoding = encoding;
-                       m_encoding_max_byte = m_encoding.GetMaxByteCount(1);
+                       decoder = encoding.GetDecoder ();
                        m_buffer = new byte [32];
                }
 
@@ -55,6 +88,7 @@ namespace System.IO {
                        m_buffer = null;
                        m_encoding = null;
                        m_stream = null;
+                       charBuffer = null;
                }
 
                void IDisposable.Dispose() 
@@ -62,15 +96,18 @@ namespace System.IO {
                        Dispose (true);
                }
 
-               protected virtual void FillBuffer(int bytes) {
-                       if(m_stream==null) {
+               protected virtual void FillBuffer (int bytes)
+               {
+                       if (m_disposed)
+                               throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
+                       if (m_stream==null)
                                throw new IOException("Stream is invalid");
-                       }
                        
                        CheckBuffer(bytes);
 
                        /* Cope with partial reads */
                        int pos=0;
+
                        while(pos<bytes) {
                                int n=m_stream.Read(m_buffer, pos, bytes-pos);
                                if(n==0) {
@@ -90,15 +127,28 @@ namespace System.IO {
                                throw new IOException("Stream is invalid");
                        }
 
-                       if(!m_stream.CanSeek) {
-                               return(-1);
+                       if ( !m_stream.CanSeek )
+                       {
+                               return -1;
                        }
 
-                       long pos=m_stream.Position;
-                       int ch=Read();
-                       m_stream.Position=pos;
+                       char[] result = new char[1];
+                       byte[] bytes;
+                       int bcount;
 
-                       return(ch);
+                       int ccount = ReadCharBytes (result, 0, 1, out bytes, out bcount);
+
+                       // Reposition the stream
+                       m_stream.Position -= bcount;
+
+                       // If we read 0 characters then return -1
+                       if (ccount == 0) 
+                       {
+                               return -1;
+                       }
+                       
+                       // Return the single character we read
+                       return result[0];
                }
 
                public virtual int Read() {
@@ -125,15 +175,15 @@ namespace System.IO {
                        if (buffer == null) {
                                throw new ArgumentNullException("buffer is null");
                        }
-                       if (buffer.Length - index < count) {
-                               throw new ArgumentException("buffer is too small");
-                       }
                        if (index < 0) {
                                throw new ArgumentOutOfRangeException("index is less than 0");
                        }
                        if (count < 0) {
                                throw new ArgumentOutOfRangeException("count is less than 0");
                        }
+                       if (buffer.Length - index < count) {
+                               throw new ArgumentException("buffer is too small");
+                       }
 
                        int bytes_read=m_stream.Read(buffer, index, count);
 
@@ -153,25 +203,36 @@ namespace System.IO {
                        if (buffer == null) {
                                throw new ArgumentNullException("buffer is null");
                        }
-                       if (buffer.Length - index < count) {
-                               throw new ArgumentException("buffer is too small");
-                       }
                        if (index < 0) {
                                throw new ArgumentOutOfRangeException("index is less than 0");
                        }
                        if (count < 0) {
                                throw new ArgumentOutOfRangeException("count is less than 0");
                        }
+                       if (buffer.Length - index < count) {
+                               throw new ArgumentException("buffer is too small");
+                       }
 
+                       int bytes_read;
+                       byte[] bytes;
+                       return ReadCharBytes (buffer, index, count, out bytes, out bytes_read);
+               }
+
+               private int ReadCharBytes(char[] buffer, int index, int count, out byte[] bytes, out int bytes_read) \r
+               {
                        int chars_read=0;
-                       int bytes_read=0;
+                       bytes_read=0;
                        
-                       while(chars_read < count) {
+                       while(chars_read < count) 
+                       {
                                CheckBuffer(bytes_read + 1);
 
-                               int read_byte=m_stream.ReadByte();
-                               if(read_byte==-1) {
+                               int read_byte = m_stream.ReadByte();
+
+                               if(read_byte==-1) 
+                               {
                                        /* EOF */
+                                       bytes = m_buffer;
                                        return(chars_read);
                                }
 
@@ -179,11 +240,12 @@ namespace System.IO {
                                bytes_read++;
 
                                chars_read=m_encoding.GetChars(m_buffer, 0,
-                                                              bytes_read,
-                                                              buffer, index);
+                                                                                bytes_read,
+                                                                                buffer, index);
                                
                        }
 
+                       bytes = m_buffer;
                        return(chars_read);
                }
 
@@ -203,17 +265,24 @@ namespace System.IO {
                }
 
                public virtual bool ReadBoolean() {
-                       FillBuffer(1);
-
                        // Return value:
                        //  true if the byte is non-zero; otherwise false.
-                       return(m_buffer[0] != 0);
+                       return ReadByte() != 0;
                }
 
                public virtual byte ReadByte() {
-                       FillBuffer(1);
+                       if (m_stream == null) {
+                               if (m_disposed)
+                                       throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
 
-                       return(m_buffer[0]);
+                               throw new IOException ("Stream is invalid");
+                       }
+                       
+                       int val = m_stream.ReadByte ();
+                       if (val != -1)
+                               return (byte) val;
+                       
+                       throw new EndOfStreamException ();
                }
 
                public virtual byte[] ReadBytes(int count) {
@@ -236,7 +305,8 @@ namespace System.IO {
                        byte[] buf = new byte[count];
                        int pos=0;
                        
-                       while(pos < count) {
+                       while(pos < count) \r
+                       {
                                int n=m_stream.Read(buf, pos, count-pos);
                                if(n==0) {
                                        /* EOF */
@@ -248,7 +318,7 @@ namespace System.IO {
                                
                        if (pos!=count) {
                                byte[] new_buffer=new byte[pos];
-                               Array.Copy(buf, new_buffer, pos);
+                               Buffer.BlockCopyInternal (buf, 0, new_buffer, 0, pos);
                                return(new_buffer);
                        }
                        
@@ -270,6 +340,9 @@ namespace System.IO {
                                throw new ArgumentOutOfRangeException("count is less than 0");
                        }
 
+                       if (count == 0)
+                               return new char [0];
+                                       
                        char[] full = new char[count];
                        int chars = Read(full, 0, count);
                        
@@ -289,29 +362,47 @@ namespace System.IO {
 
                        decimal ret;
                        byte* ret_ptr = (byte *)&ret;
-                       for (int i = 0; i < 16; i++) {
-                         
-                               /*
-                                * internal representation of decimal is 
-                                * ss32, hi32, lo32, mi32, 
-                                * but in stream it is 
-                                * lo32, mi32, hi32, ss32
-                                * So we have to rerange this int32 values
-                                */                       
-                         
-                               if (i < 4) {
-                                       // lo 8 - 12                      
-                                       ret_ptr [i + 8] = m_buffer [i];
-                               } else if (i < 8) {
-                                       // mid 12 - 16
-                                       ret_ptr [i + 8] = m_buffer [i];
-                               } else if (i < 12) {
-                                       // hi 4 - 8
-                                       ret_ptr [i - 4] = m_buffer [i];
-                               } else if (i < 16) {
-                                       // ss 0 - 4
-                                       ret_ptr [i - 12] = m_buffer [i];
-                               }                               
+                       
+                       /*
+                        * internal representation of decimal is 
+                        * ss32, hi32, lo32, mi32, 
+                        * but in stream it is 
+                        * lo32, mi32, hi32, ss32
+                        * So we have to rerange this int32 values
+                        */                       
+                 
+                       if (BitConverter.IsLittleEndian) {
+                               for (int i = 0; i < 16; i++) {
+                                       if (i < 4) {
+                                               // lo 8 - 12                      
+                                               ret_ptr [i + 8] = m_buffer [i];
+                                       } else if (i < 8) {
+                                               // mid 12 - 16
+                                               ret_ptr [i + 8] = m_buffer [i];
+                                       } else if (i < 12) {
+                                               // hi 4 - 8
+                                               ret_ptr [i - 4] = m_buffer [i];
+                                       } else if (i < 16) {
+                                               // ss 0 - 4
+                                               ret_ptr [i - 12] = m_buffer [i];
+                                       }                               
+                               }
+                       } else {
+                               for (int i = 0; i < 16; i++) {
+                                       if (i < 4) {
+                                               // lo 8 - 12                      
+                                               ret_ptr [11 - i] = m_buffer [i];
+                                       } else if (i < 8) {
+                                               // mid 12 - 16
+                                               ret_ptr [19 - i] = m_buffer [i];
+                                       } else if (i < 12) {
+                                               // hi 4 - 8
+                                               ret_ptr [15 - i] = m_buffer [i];
+                                       } else if (i < 16) {
+                                               // ss 0 - 4
+                                               ret_ptr [15 - i] = m_buffer [i];
+                                       }                               
+                               }
                        }
 
                        return ret;
@@ -320,7 +411,7 @@ namespace System.IO {
                public virtual double ReadDouble() {
                        FillBuffer(8);
 
-                       return(BitConverter.ToDouble(m_buffer, 0));
+                       return(BitConverterLE.ToDouble(m_buffer, 0));
                }
 
                public virtual short ReadInt16() {
@@ -354,9 +445,7 @@ namespace System.IO {
 
                [CLSCompliant(false)]
                public virtual sbyte ReadSByte() {
-                       FillBuffer(1);
-
-                       return((sbyte)m_buffer[0]);
+                       return (sbyte) ReadByte ();
                }
 
                public virtual string ReadString() {
@@ -365,18 +454,50 @@ namespace System.IO {
                         * not chars
                         */
                        int len = Read7BitEncodedInt();
+                       
+                       if (len < 0)
+                               throw new IOException ("Invalid binary file (string len < 0)");
 
-                       FillBuffer(len);
+                       if (len == 0)
+                               return String.Empty;
+                       
                        
-                       char[] str = m_encoding.GetChars(m_buffer, 0, len);
+                       if (charBuffer == null)
+                               charBuffer = new char [MaxBufferSize];
+
+                       //
+                       // We read the string here in small chunks. Also, we
+                       // Attempt to optimize the common case of short strings.
+                       //
+                       StringBuilder sb = null;
+                       do {
+                               int readLen = (len > MaxBufferSize)
+                                               ? MaxBufferSize
+                                               : len;
+                               
+                               FillBuffer (readLen);
+                               
+                               int cch = decoder.GetChars (m_buffer, 0, readLen, charBuffer, 0);
+
+                               if (sb == null && readLen == len) // ok, we got out the easy way, dont bother with the sb
+                                       return new String (charBuffer, 0, cch);
+
+                               if (sb == null)
+                                       // Len is a fairly good estimate of the number of chars in a string
+                                       // Most of the time 1 byte == 1 char
+                                       sb = new StringBuilder (len);
+                               
+                               sb.Append (charBuffer, 0, cch);
+                               len -= readLen;
+                       } while (len > 0);
 
-                       return(new String(str));
+                       return sb.ToString();
                }
 
                public virtual float ReadSingle() {
                        FillBuffer(4);
 
-                       return(BitConverter.ToSingle(m_buffer, 0));
+                       return(BitConverterLE.ToSingle(m_buffer, 0));
                }
 
                [CLSCompliant(false)]
@@ -421,8 +542,7 @@ namespace System.IO {
                {
                        if(m_buffer.Length <= length) {
                                byte[] new_buffer=new byte[length];
-                               Array.Copy(m_buffer, new_buffer,
-                                          m_buffer.Length);
+                               Buffer.BlockCopyInternal (m_buffer, 0, new_buffer, 0, m_buffer.Length);
                                m_buffer=new_buffer;
                        }
                }