Merge pull request #601 from knocte/sock_improvements
[mono.git] / mcs / class / corlib / System / Int32.cs
index 6af4ccd3e842b50be57a3bd98150c70a83409efb..b78c0a5b14ec32b54a26167defe075bf8f6734db 100644 (file)
@@ -1,11 +1,13 @@
 //
 // System.Int32.cs
 //
-// Author:
+// Authors:
 //   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
 //
 // (C) Ximian, Inc.  http://www.ximian.com
 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -33,13 +35,8 @@ using System.Threading;
 namespace System {
        
        [Serializable]
-#if NET_2_0
        [System.Runtime.InteropServices.ComVisible (true)]
-#endif
-       public struct Int32 : IFormattable, IConvertible, IComparable
-#if NET_2_0
-               , IComparable<Int32>, IEquatable <Int32>
-#endif
+       public struct Int32 : IFormattable, IConvertible, IComparable, IComparable<Int32>, IEquatable <Int32>
        {
 
                public const int MaxValue = 0x7fffffff;
@@ -48,15 +45,15 @@ namespace System {
                // This field is looked up by name in the runtime
                internal int m_value;
 
-               public int CompareTo (object v)
+               public int CompareTo (object value)
                {
-                       if (v == null)
+                       if (value == null)
                                return 1;
                        
-                       if (!(v is System.Int32))
+                       if (!(value is System.Int32))
                                throw new ArgumentException (Locale.GetText ("Value is not a System.Int32"));
 
-                       int xv = (int) v;
+                       int xv = (int) value;
                        if (m_value == xv)
                                return 0;
                        if (m_value > xv)
@@ -65,12 +62,12 @@ namespace System {
                                return -1;
                }
 
-               public override bool Equals (object o)
+               public override bool Equals (object obj)
                {
-                       if (!(o is System.Int32))
+                       if (!(obj is System.Int32))
                                return false;
 
-                       return ((int) o) == m_value;
+                       return ((int) obj) == m_value;
                }
 
                public override int GetHashCode ()
@@ -78,7 +75,6 @@ namespace System {
                        return m_value;
                }
 
-#if NET_2_0
                public int CompareTo (int value)
                {
                        if (m_value == value)
@@ -89,11 +85,10 @@ namespace System {
                                return -1;
                }
 
-               public bool Equals (int value)
+               public bool Equals (int obj)
                {
-                       return value == m_value;
+                       return obj == m_value;
                }
-#endif
 
                internal static bool ProcessTrailingWhitespace (bool tryParse, string s, int position, ref Exception exc)
                {
@@ -102,7 +97,7 @@ namespace System {
                        for (int i = position; i < len; i++){
                                char c = s [i];
                                
-                               if (!Char.IsWhiteSpace (c)){
+                               if (c != 0 && !Char.IsWhiteSpace (c)){
                                        if (!tryParse)
                                                exc = GetFormatException ();
                                        return false;
@@ -120,6 +115,7 @@ namespace System {
 
                        result = 0;
                        exc = null;
+                       NumberFormatInfo nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
 
                        if (s == null) {
                                if (!tryParse)
@@ -142,12 +138,13 @@ namespace System {
                                return false;
                        }
 
-                       c = s [i];
-                       if (c == '+')
-                               i++;
-                       else if (c == '-'){
+                       var ps_length = nfi.PositiveSign.Length;
+                       var ns_length = nfi.NegativeSign.Length;
+                       if (len > ps_length && string.CompareOrdinalUnchecked (s, i, ns_length, nfi.PositiveSign, 0, ps_length) == 0)
+                               i += ps_length;
+                       else if (len > ns_length && string.CompareOrdinalUnchecked (s, i, ns_length, nfi.NegativeSign, 0, ns_length) == 0) {
                                sign = -1;
-                               i++;
+                               i += ns_length;
                        }
                        
                        for (; i < len; i++){
@@ -203,9 +200,9 @@ namespace System {
                        return false;
                }
 
-               public static int Parse (string s, IFormatProvider fp)
+               public static int Parse (string s, IFormatProvider provider)
                {
-                       return Parse (s, NumberStyles.Integer, fp);
+                       return Parse (s, NumberStyles.Integer, provider);
                }
 
                public static int Parse (string s, NumberStyles style)
@@ -229,6 +226,10 @@ namespace System {
                                                        "are permitted.");
                                        return false;
                                }
+                       } else if ((uint) style > (uint) NumberStyles.Any){
+                               if (!tryParse)
+                                       exc = new ArgumentException ("Not a valid number style");
+                               return false;
                        }
 
                        return true;
@@ -252,13 +253,12 @@ namespace System {
                                      ref bool foundSign, ref bool negative)
                {
                        if ((pos + nfi.NegativeSign.Length) <= s.Length &&
-                               s.IndexOf (nfi.NegativeSign, pos, nfi.NegativeSign.Length) == pos) {
+                               s.IndexOfOrdinalUnchecked (nfi.NegativeSign, pos, nfi.NegativeSign.Length) == pos) {
                                negative = true;
                                foundSign = true;
                                pos += nfi.NegativeSign.Length;
-                       } 
-                       else if ((pos + nfi.PositiveSign.Length) < s.Length &&
-                               s.IndexOf (nfi.PositiveSign, pos, nfi.PositiveSign.Length) == pos) {
+                       } else if ((pos + nfi.PositiveSign.Length) <= s.Length &&
+                               s.IndexOfOrdinalUnchecked (nfi.PositiveSign, pos, nfi.PositiveSign.Length) == pos) {
                                negative = false;
                                pos += nfi.PositiveSign.Length;
                                foundSign = true;
@@ -277,21 +277,52 @@ namespace System {
                        } 
                }
 
-               internal static bool FindExponent (ref int pos, string s)
+               internal static bool FindExponent (ref int pos, string s, ref int exponent, bool tryParse, ref Exception exc)
                {
-                               int i = s.IndexOfAny(new char [] {'e', 'E'}, pos);
-                               if (i < 0)
-                                               return false;
-                               if (++i == s.Length)
-                                               return false;
-                               if (s [i] == '+' || s [i] == '-')
-                                               if (++i == s.Length)
-                                                               return false;
-                               if (!Char.IsDigit (s [i]))
-                                               return false;
-                               for (; i < s.Length; ++i)
-                                               if (!Char.IsDigit (s [i])) 
-                                                               break;
+                               exponent = 0;
+
+                               if (pos >= s.Length || (s [pos] != 'e' && s[pos] != 'E')) {
+                                       exc = null;
+                                       return false;
+                               }
+
+                               var i = pos + 1;
+                               if (i == s.Length) {
+                                       exc = tryParse ? null : GetFormatException ();
+                                       return true;
+                               }
+
+                               // negative exponent not valid for Int32
+                               if (s [i] == '-') {
+                                       exc = tryParse ? null : new OverflowException ("Value too large or too small.");
+                                       return true;
+                               }
+
+                               if (s [i] == '+' && ++i == s.Length) {
+                                       exc = tryParse ? null : GetFormatException ();
+                                       return true;
+                               }
+
+                               long exp = 0; // temp long value
+                               for (; i < s.Length; i++) {
+                                       if (!Char.IsDigit (s [i]))  {
+                                               exc = tryParse ? null : GetFormatException ();
+                                               return true;
+                                       }
+
+                                       // Reduce the risk of throwing an overflow exc
+                                       exp = checked (exp * 10 - (int) (s [i] - '0'));
+                                       if (exp < Int32.MinValue || exp > Int32.MaxValue) {
+                                               exc = tryParse ? null : new OverflowException ("Value too large or too small.");
+                                               return true;
+                                       }
+                               }
+
+                               // exp value saved as negative
+                               exp = -exp;
+
+                               exc = null;
+                               exponent = (int)exp;
                                pos = i;
                                return true;
                }
@@ -329,13 +360,7 @@ namespace System {
 
                        if (s == null) {
                                if (!tryParse)
-                                       exc = GetFormatException ();
-                               return false;
-                       }
-                       
-                       if (s == null) {
-                               if (!tryParse)
-                                       exc = new ArgumentNullException ();
+                                       exc = new ArgumentNullException ("s");
                                return false;
                        }
 
@@ -345,12 +370,12 @@ namespace System {
                                return false;
                        }
 
-                       NumberFormatInfo nfi;
+                       NumberFormatInfo nfi = null;
                        if (fp != null) {
                                Type typeNFI = typeof (System.Globalization.NumberFormatInfo);
                                nfi = (NumberFormatInfo) fp.GetFormat (typeNFI);
                        }
-                       else
+                       if (nfi == null)
                                nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
 
                        if (!CheckStyle (style, tryParse, ref exc))
@@ -384,7 +409,7 @@ namespace System {
                                negative = true; // MS always make the number negative when there parentheses
                                                 // even when NumberFormatInfo.NumberNegativePattern != 0!!!
                                pos++;
-                               if (AllowLeadingWhite && !!JumpOverWhite (ref pos, s, true, tryParse, ref exc))
+                               if (AllowLeadingWhite && !JumpOverWhite (ref pos, s, true, tryParse, ref exc))
                                        return false;
 
                                if (s.Substring (pos, nfi.NegativeSign.Length) == nfi.NegativeSign) {
@@ -436,7 +461,7 @@ namespace System {
 
                        int number = 0;
                        int nDigits = 0;
-                       bool decimalPointFound = false;
+                       int decimalPointPos = -1;
                        int digitValue;
                        char hexDigit;
                                
@@ -445,19 +470,23 @@ namespace System {
 
                                if (!ValidDigit (s [pos], AllowHexSpecifier)) {
                                        if (AllowThousands &&
-                                           FindOther (ref pos, s, nfi.NumberGroupSeparator))
+                                           (FindOther (ref pos, s, nfi.NumberGroupSeparator)
+                                               || FindOther (ref pos, s, nfi.CurrencyGroupSeparator)))
                                            continue;
-                                       else
-                                       if (!decimalPointFound && AllowDecimalPoint &&
-                                           FindOther (ref pos, s, nfi.NumberDecimalSeparator)) {
-                                           decimalPointFound = true;
+
+                                       if (AllowDecimalPoint && decimalPointPos < 0 &&
+                                           (FindOther (ref pos, s, nfi.NumberDecimalSeparator)
+                                               || FindOther (ref pos, s, nfi.CurrencyDecimalSeparator))) {
+                                               decimalPointPos = nDigits;
                                            continue;
                                        }
 
                                        break;
                                }
-                               else if (AllowHexSpecifier) {
-                                       nDigits++;
+
+                               nDigits++;
+
+                               if (AllowHexSpecifier) {
                                        hexDigit = s [pos++];
                                        if (Char.IsDigit (hexDigit))
                                                digitValue = (int) (hexDigit - '0');
@@ -475,34 +504,18 @@ namespace System {
                                        } else {
                                                number = (int)checked (unumber * 16u + (uint)digitValue);
                                        }
+
+                                       continue;
                                }
-                               else if (decimalPointFound) {
-                                       nDigits++;
-                                       // Allows decimal point as long as it's only 
-                                       // followed by zeroes.
-                                       if (s [pos++] != '0') {
-                                               if (!tryParse)
-                                                       exc = new OverflowException ("Value too large or too " +
-                                                                       "small.");
-                                               return false;
-                                       }
-                               }
-                               else {
-                                       nDigits++;
-
-                                       try {
-                                               // Calculations done as negative
-                                               // (abs (MinValue) > abs (MaxValue))
-                                               number = checked (
-                                                       number * 10 - 
-                                                       (int) (s [pos++] - '0')
-                                                       );
-                                       } catch (OverflowException) {
-                                               if (!tryParse)
-                                                       exc = new OverflowException ("Value too large or too " +
-                                                                       "small.");
-                                               return false;
-                                       }
+
+                               try {
+                                       // Calculations done as negative
+                                       // (abs (MinValue) > abs (MaxValue))
+                                       number = checked (number * 10 - (int) (s [pos++] - '0'));
+                               } catch (OverflowException) {
+                                       if (!tryParse)
+                                               exc = new OverflowException ("Value too large or too small.");
+                                       return false;
                                }
                        } while (pos < s.Length);
 
@@ -513,26 +526,28 @@ namespace System {
                                return false;
                        }
 
-                       if (AllowExponent) 
-                                       FindExponent(ref pos, s);
+                       int exponent = 0;
+                       if (AllowExponent)
+                               if (FindExponent (ref pos, s, ref exponent, tryParse, ref exc) && exc != null)
+                                       return false;
 
                        if (AllowTrailingSign && !foundSign) {
                                // Sign + Currency
                                FindSign (ref pos, s, nfi, ref foundSign, ref negative);
-                               if (foundSign) {
+                               if (foundSign && pos < s.Length) {
                                        if (AllowTrailingWhite && !JumpOverWhite (ref pos, s, true, tryParse, ref exc))
                                                return false;
-                                       if (AllowCurrencySymbol)
-                                               FindCurrency (ref pos, s, nfi,
-                                                             ref foundCurrency);
                                }
                        }
                        
                        if (AllowCurrencySymbol && !foundCurrency) {
+                               if (AllowTrailingWhite && pos < s.Length && !JumpOverWhite (ref pos, s, false, tryParse, ref exc))
+                                       return false;
+                               
                                // Currency + sign
                                FindCurrency (ref pos, s, nfi, ref foundCurrency);
-                               if (foundCurrency) {
-                                       if (AllowTrailingWhite && !JumpOverWhite (ref pos, s, true, tryParse, ref exc))
+                               if (foundCurrency  && pos < s.Length) {
+                                       if (AllowTrailingWhite  && !JumpOverWhite (ref pos, s, true, tryParse, ref exc))
                                                return false;
                                        if (!foundSign && AllowTrailingSign)
                                                FindSign (ref pos, s, nfi, ref foundSign,
@@ -549,8 +564,7 @@ namespace System {
                                                exc = GetFormatException ();
                                        return false;
                                }
-                               if (AllowTrailingWhite && pos < s.Length &&
-                                               !JumpOverWhite (ref pos, s, false, tryParse, ref exc))
+                               if (AllowTrailingWhite && pos < s.Length && !JumpOverWhite (ref pos, s, false, tryParse, ref exc))
                                        return false;
                        }
 
@@ -562,7 +576,7 @@ namespace System {
                        
                        if (!negative && !AllowHexSpecifier){
                                if (tryParse){
-                                       long lval = -number;
+                                       long lval = -((long)number);
 
                                        if (lval < MinValue || lval > MaxValue)
                                                return false;
@@ -570,9 +584,38 @@ namespace System {
                                } else
                                        number = checked (-number);
                        }
+
+                       if (decimalPointPos >= 0)
+                               exponent = exponent - nDigits + decimalPointPos;
                        
-                       result = number;
+                       if (exponent < 0) {
+                               //
+                               // Any non-zero values after decimal point are not allowed
+                               //
+                               int remainder;
+                               number = Math.DivRem (number, (int) Math.Pow (10, -exponent), out remainder);
+                               if (remainder != 0) {
+                                       if (!tryParse)
+                                               exc = new OverflowException ("Value too large or too small.");
+                                       return false;
+                               }
+                       } else if (exponent > 0) {
+                               //
+                               // result *= 10^exponent
+                               //
+                               // Reduce the risk of throwing an overflow exc
+                               //
+                               double res = checked (Math.Pow (10, exponent) * number);
+                               if (res < MinValue || res > MaxValue) {
+                                       if (!tryParse)
+                                               exc = new OverflowException ("Value too large or too small.");
+                                       return false;
+                               }
 
+                               number = (int)res;
+                       }
+                       
+                       result = number;
                        return true;
                }
 
@@ -587,22 +630,20 @@ namespace System {
                        return res;
                }
 
-               public static int Parse (string s, NumberStyles style, IFormatProvider fp
+               public static int Parse (string s, NumberStyles style, IFormatProvider provider
                {
                        Exception exc;
                        int res;
 
-                       if (!Parse (s, style, fp, false, out res, out exc))
+                       if (!Parse (s, style, provider, false, out res, out exc))
                                throw exc;
 
                        return res;
                }
 
-#if NET_2_0
                public static bool TryParse (string s, out int result) 
                {
                        Exception exc;
-                       
                        if (!Parse (s, true, out result, out exc)) {
                                result = 0;
                                return false;
@@ -621,7 +662,6 @@ namespace System {
 
                        return true;
                }
-#endif
 
                public override string ToString ()
                {
@@ -638,9 +678,9 @@ namespace System {
                        return ToString (format, null);
                }
 
-               public string ToString (string format, IFormatProvider fp )
+               public string ToString (string format, IFormatProvider provider)
                {
-                       return NumberFormatter.NumberToString (format, m_value, fp);
+                       return NumberFormatter.NumberToString (format, m_value, provider);
                }
 
                // =========== IConvertible Methods =========== //
@@ -705,9 +745,11 @@ namespace System {
                        return System.Convert.ToSingle (m_value);
                }
 
-               object IConvertible.ToType (Type type, IFormatProvider provider)
+               object IConvertible.ToType (Type targetType, IFormatProvider provider)
                {
-                       return System.Convert.ToType (m_value, type, provider);
+                       if (targetType == null)
+                               throw new ArgumentNullException ("targetType");
+                       return System.Convert.ToType (m_value, targetType, provider, false);
                }
 
                ushort IConvertible.ToUInt16 (IFormatProvider provider)