Merge branch 'BigIntegerParse'
[mono.git] / mcs / class / corlib / System / Int64.cs
index 7aa3119cb24d295d9a150d13aa0ca20edd6c0733..84d542e9b24234637ccee9c62143ad7ec4aff65e 100644 (file)
@@ -1,12 +1,13 @@
 //
 // System.Int64.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
@@ -34,13 +35,8 @@ using System.Threading;
 namespace System {
        
        [Serializable]
-#if NET_2_0
        [System.Runtime.InteropServices.ComVisible (true)]
-#endif
-       public struct Int64 : IFormattable, IConvertible, IComparable
-#if NET_2_0
-               , IComparable<Int64>, IEquatable <Int64>
-#endif
+       public struct Int64 : IFormattable, IConvertible, IComparable, IComparable<Int64>, IEquatable <Int64>
        {
 
                public const long MaxValue = 0x7fffffffffffffff;
@@ -48,29 +44,28 @@ namespace System {
                
                internal long m_value;
 
-               public int CompareTo (object v)
+               public int CompareTo (object value)
                {
-                       if (v == null)
+                       if (value == null)
                                return 1;
                        
-                       if (!(v is System.Int64))
+                       if (!(value is System.Int64))
                                throw new ArgumentException (Locale.GetText ("Value is not a System.Int64"));
 
-                       if (m_value == (long) v)
-                               return 0;
+                       long lValue = (long) value;
 
-                       if (m_value < (long) v)
-                               return -1;
+                       if (m_value == lValue)
+                               return 0;
 
-                       return 1;
+                       return (m_value < lValue) ? -1 : 1;
                }
 
-               public override bool Equals (object o)
+               public override bool Equals (object obj)
                {
-                       if (!(o is System.Int64))
+                       if (!(obj is System.Int64))
                                return false;
 
-                       return ((long) o) == m_value;
+                       return ((long) obj) == m_value;
                }
 
                public override int GetHashCode ()
@@ -78,7 +73,6 @@ namespace System {
                        return (int)(m_value & 0xffffffff) ^ (int)(m_value >> 32);
                }
 
-#if NET_2_0
                public int CompareTo (long value)
                {
                        if (m_value == value)
@@ -89,22 +83,21 @@ namespace System {
                                return -1;
                }
 
-               public bool Equals (long value)
+               public bool Equals (long obj)
                {
-                       return value == m_value;
+                       return obj == m_value;
                }
-#endif
 
                internal static bool Parse (string s, bool tryParse, out long result, out Exception exc)
                {
                        long val = 0;
                        int len;
-                       int i;
-                       int sign = 1;
+                       int i, sign = 1;
                        bool digits_seen = false;
 
                        result = 0;
                        exc = null;
+                       NumberFormatInfo nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
 
                        if (s == null) {
                                if (!tryParse) 
@@ -127,12 +120,11 @@ namespace System {
                                return false;
                        }
 
-                       c = s [i];
-                       if (c == '+')
-                               i++;
-                       else if (c == '-'){
+                       if (String.Compare (s, i, nfi.PositiveSign, 0, nfi.PositiveSign.Length) == 0)
+                               i += nfi.PositiveSign.Length;
+                       else if (String.Compare (s, i, nfi.NegativeSign, 0, nfi.NegativeSign.Length) == 0) {
                                sign = -1;
-                               i++;
+                               i += nfi.NegativeSign.Length;
                        }
                        
                        for (; i < len; i++){
@@ -160,11 +152,9 @@ namespace System {
                                        } else 
                                                val = val * 10 + d;
                                        
-                                       
                                        digits_seen = true;
                                } else if (!Int32.ProcessTrailingWhitespace (tryParse, s, i, ref exc))
                                        return false;
-                                       
                        }
                        if (!digits_seen) {
                                if (!tryParse)
@@ -180,14 +170,14 @@ namespace System {
                        return true;
 
                overflow:
-                       if (tryParse)
-                               return false;
-                       throw new OverflowException ("Value is too large");
+                       if (!tryParse)
+                               exc = new OverflowException ("Value is too large");
+                       return false;
                }
 
-               public static long Parse (string s, IFormatProvider fp)
+               public static long Parse (string s, IFormatProvider provider)
                {
-                       return Parse (s, NumberStyles.Integer, fp);
+                       return Parse (s, NumberStyles.Integer, provider);
                }
 
                public static long Parse (string s, NumberStyles style)
@@ -208,17 +198,16 @@ namespace System {
 
                        if (s.Length == 0) {
                                if (!tryParse)
-                                       exc = new FormatException ("Input string was not " + 
-                                                       "in the correct format: s.Length==0.");
+                                       exc = Int32.GetFormatException ();
                                return false;
                        }
 
-                       NumberFormatInfo nfi;
+                       NumberFormatInfo nfi = null;
                        if (fp != null) {
                                Type typeNFI = typeof (System.Globalization.NumberFormatInfo);
-                               nfi = (NumberFormatInfo) fp.GetFormat (typeNFI);
-                       }
-                       else
+                               nfi = fp.GetFormat (typeNFI) as NumberFormatInfo;
+                       } 
+                       if (nfi == null)
                                nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
 
                        if (!Int32.CheckStyle (style, tryParse, ref exc))
@@ -233,6 +222,7 @@ namespace System {
                        bool AllowLeadingSign = (style & NumberStyles.AllowLeadingSign) != 0;
                        bool AllowTrailingWhite = (style & NumberStyles.AllowTrailingWhite) != 0;
                        bool AllowLeadingWhite = (style & NumberStyles.AllowLeadingWhite) != 0;
+                       bool AllowExponent = (style & NumberStyles.AllowExponent) != 0;
 
                        int pos = 0;
 
@@ -256,14 +246,13 @@ namespace System {
 
                                if (s.Substring (pos, nfi.NegativeSign.Length) == nfi.NegativeSign) {
                                        if (!tryParse)
-                                               exc = new FormatException ("Input string was not in the correct " +
-                                                               "format: Has Negative Sign.");
+                                               exc = Int32.GetFormatException ();
                                        return false;
                                }
+                               
                                if (s.Substring (pos, nfi.PositiveSign.Length) == nfi.PositiveSign) {
                                        if (!tryParse)
-                                               exc = new FormatException ("Input string was not in the correct " +
-                                                               "format: Has Positive Sign.");
+                                               exc = Int32.GetFormatException ();
                                        return false;
                                }
                        }
@@ -304,30 +293,32 @@ namespace System {
                        
                        long number = 0;
                        int nDigits = 0;
-                       bool decimalPointFound = false;
+                       int decimalPointPos = -1;
                        int digitValue;
                        char hexDigit;
                                
                        // Number stuff
-                       do {
+                       while (pos < s.Length) {
 
                                if (!Int32.ValidDigit (s [pos], AllowHexSpecifier)) {
                                        if (AllowThousands &&
                                            (Int32.FindOther (ref pos, s, nfi.NumberGroupSeparator)
                                                || Int32.FindOther (ref pos, s, nfi.CurrencyGroupSeparator)))
                                            continue;
-                                       else
-                                       if (!decimalPointFound && AllowDecimalPoint &&
+
+                                       if (AllowDecimalPoint && decimalPointPos < 0 &&
                                            (Int32.FindOther (ref pos, s, nfi.NumberDecimalSeparator)
                                                || Int32.FindOther (ref pos, s, nfi.CurrencyDecimalSeparator))) {
-                                           decimalPointFound = true;
+                                           decimalPointPos = nDigits;
                                            continue;
                                        }
 
                                        break;
                                }
-                               else if (AllowHexSpecifier) {
-                                       nDigits++;
+
+                               nDigits++;
+
+                               if (AllowHexSpecifier) {
                                        hexDigit = s [pos++];
                                        if (Char.IsDigit (hexDigit))
                                                digitValue = (int) (hexDigit - '0');
@@ -346,64 +337,47 @@ namespace System {
                                                        exc = e;
                                                return false;
                                        }
-                               }
-                               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 - 
-                                                       (long) (s [pos++] - '0')
-                                                       );
-                                       } catch (OverflowException) {
-                                               if (!tryParse)
-                                                       exc = new OverflowException ("Value too large or too " +
-                                                                       "small.");
-                                               return false;
-                                       }
+                                       continue;
                                }
-                       } while (pos < s.Length);
+
+                               try {
+                                       // Calculations done as negative
+                                       // (abs (MinValue) > abs (MaxValue))
+                                       number = checked (number * 10 - (long) (s [pos++] - '0'));
+                               } catch (OverflowException) {
+                                       if (!tryParse)
+                                               exc = new OverflowException ("Value too large or too small.");
+                                       return false;
+                               }                               
+                       }
 
                        // Post number stuff
                        if (nDigits == 0) {
                                if (!tryParse)
-                                       exc = new FormatException ("Input string was not in the correct format: nDigits == 0.");
+                                       exc = Int32.GetFormatException ();
                                return false;
                        }
 
+                       int exponent = 0;
+                       if (AllowExponent)
+                               if (Int32.FindExponent (ref pos, s, ref exponent, tryParse, ref exc) && exc != null)
+                                       return false;
+
                        if (AllowTrailingSign && !foundSign) {
                                // Sign + Currency
                                Int32.FindSign (ref pos, s, nfi, ref foundSign, ref negative);
-                               if (foundSign) {
+                               if (foundSign && pos < s.Length) {
                                        if (AllowTrailingWhite && !Int32.JumpOverWhite (ref pos, s, true, tryParse, ref exc))
                                                return false;
-                                       if (AllowCurrencySymbol)
-                                               Int32.FindCurrency (ref pos, s, nfi,
-                                                                   ref foundCurrency);
                                }
                        }
                        
                        if (AllowCurrencySymbol && !foundCurrency) {
+                               if (AllowTrailingWhite && pos < s.Length && !Int32.JumpOverWhite (ref pos, s, false, tryParse, ref exc))
+                                       return false;
+                               
                                // Currency + sign
-                               if (nfi.CurrencyPositivePattern == 3 && s[pos++] != ' ')
-                                       if (tryParse)
-                                               return false;
-                                       else
-                                               throw new FormatException ("Input string was not in the correct format: no space between number and currency symbol.");
-
                                Int32.FindCurrency (ref pos, s, nfi, ref foundCurrency);
                                if (foundCurrency && pos < s.Length) {
                                        if (AllowTrailingWhite && !Int32.JumpOverWhite (ref pos, s, true, tryParse, ref exc))
@@ -420,8 +394,7 @@ namespace System {
                        if (foundOpenParentheses) {
                                if (pos >= s.Length || s [pos++] != ')') {
                                        if (!tryParse)
-                                               exc = new FormatException ("Input string was not in the correct " +
-                                                               "format: No room for close parens.");
+                                               exc = Int32.GetFormatException ();
                                        return false;
                                }
                                if (AllowTrailingWhite && pos < s.Length && !Int32.JumpOverWhite (ref pos, s, false, tryParse, ref exc))
@@ -430,12 +403,10 @@ namespace System {
 
                        if (pos < s.Length && s [pos] != '\u0000') {
                                if (!tryParse)
-                                       exc = new FormatException ("Input string was not in the correct format: Did not parse entire string. pos = " 
-                                                       + pos + " s.Length = " + s.Length);
+                                       exc = Int32.GetFormatException ();
                                return false;
                        }
 
-                       
                        if (!negative && !AllowHexSpecifier){
                                try {
                                        number = checked (-number);
@@ -446,6 +417,36 @@ namespace System {
                                }
                        }
 
+                       if (decimalPointPos >= 0)
+                               exponent = exponent - nDigits + decimalPointPos;
+                       
+                       if (exponent < 0) {
+                               //
+                               // Any non-zero values after decimal point are not allowed
+                               //
+                               long remainder;
+                               number = Math.DivRem (number, (long) 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 = (long)res;
+                       }
+
                        result = number;
                        return true;
                }
@@ -461,18 +462,17 @@ namespace System {
                        return res;
                }
 
-               public static long Parse (string s, NumberStyles style, IFormatProvider fp
+               public static long Parse (string s, NumberStyles style, IFormatProvider provider
                {
                        Exception exc;
                        long 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 long result) 
                {
                        Exception exc;
@@ -494,16 +494,15 @@ namespace System {
 
                        return true;
                }
-#endif
 
                public override string ToString ()
                {
-                       return NumberFormatter.FormatGeneral (new NumberFormatter.NumberStore (m_value));
+                       return NumberFormatter.NumberToString (m_value, null);
                }
 
-               public string ToString (IFormatProvider fp)
+               public string ToString (IFormatProvider provider)
                {
-                       return NumberFormatter.FormatGeneral (new NumberFormatter.NumberStore (m_value), fp);
+                       return NumberFormatter.NumberToString (m_value, provider);
                }
 
                public string ToString (string format)
@@ -511,10 +510,9 @@ namespace System {
                        return ToString (format, null);
                }
 
-               public string ToString (string format, IFormatProvider fp)
+               public string ToString (string format, IFormatProvider provider)
                {
-                       NumberFormatInfo nfi = NumberFormatInfo.GetInstance( fp );
-                       return NumberFormatter.NumberToString (format, m_value, nfi);
+                       return NumberFormatter.NumberToString (format, m_value, provider);
                }
 
                // =========== IConvertible Methods =========== //
@@ -566,22 +564,24 @@ namespace System {
 
                long IConvertible.ToInt64 (IFormatProvider provider)
                {
-                       return System.Convert.ToInt64 (m_value);
+                       return m_value;
                }
 
                sbyte IConvertible.ToSByte (IFormatProvider provider)
                {
                        return System.Convert.ToSByte (m_value);
                }
-               
+
                float IConvertible.ToSingle (IFormatProvider provider)
                {
                        return System.Convert.ToSingle (m_value);
                }
 
-               object IConvertible.ToType (Type conversionType, IFormatProvider provider)
+               object IConvertible.ToType (Type targetType, IFormatProvider provider)
                {
-                       return System.Convert.ToType (m_value, conversionType, provider);
+                       if (targetType == null)
+                               throw new ArgumentNullException ("targetType");
+                       return System.Convert.ToType (m_value, targetType, provider, false);
                }
 
                ushort IConvertible.ToUInt16 (IFormatProvider provider)