Inheritance: ArithmeticException
 public void DefaultConstructorWorks()
 {
     var ex = new OverflowException();
     Assert.True((object)ex is OverflowException, "is OverflowException");
     Assert.AreEqual(ex.InnerException, null, "InnerException");
     Assert.AreEqual(ex.Message, "Arithmetic operation resulted in an overflow.");
 }
 public void ConstructorWithMessageWorks()
 {
     var ex = new OverflowException("The message");
     Assert.True((object)ex is OverflowException, "is OverflowException");
     Assert.AreEqual(ex.InnerException, null, "InnerException");
     Assert.AreEqual(ex.Message, "The message");
 }
 public void TypePropertiesAreCorrect()
 {
     Assert.AreEqual(typeof(OverflowException).GetClassName(), "Bridge.OverflowException", "Name");
     object d = new OverflowException();
     Assert.True(d is OverflowException, "is OverflowException");
     Assert.True(d is Exception, "is Exception");
 }
Example #4
0
        internal Exception TryToTimeSpan(DurationType durationType, out TimeSpan result)
        {
            Exception exception = null;
            ulong     ticks     = 0;

            try
            {
                checked
                {
                    if (durationType != DurationType.DayTimeDuration)
                    {
                        ticks += ((ulong)this.years + ((ulong)this.months / 12)) * 365;
                        ticks += ((ulong)this.months % 12) * 30;
                    }

                    if (durationType != DurationType.YearMonthDuration)
                    {
                        ticks += (ulong)this.days;
                        ticks *= 24;
                        ticks += (ulong)this.hours;
                        ticks *= 60;
                        ticks += (ulong)this.minutes;
                        ticks *= 60;
                        ticks += (ulong)this.seconds;
                        ticks *= (ulong)TimeSpan.TicksPerSecond;
                        ticks += (ulong)Nanoseconds / 100;
                    }
                    else
                    {
                        ticks *= (ulong)TimeSpan.TicksPerDay;
                    }

                    if (IsNegative)
                    {
                        if (ticks == (ulong)Int64.MaxValue + 1)
                        {
                            result = new TimeSpan(Int64.MinValue);
                        }
                        else
                        {
                            result = new TimeSpan(-((long)ticks));
                        }
                    }
                    else
                    {
                        result = new TimeSpan((long)ticks);
                    }

                    return(null);
                }
            }
            catch (OverflowException)
            {
                result    = TimeSpan.MinValue;
                exception = new OverflowException();
            }

            return(exception);
        }
 public void ConstructorWithMessageAndInnerExceptionWorks()
 {
     var inner = new Exception("a");
     var ex = new OverflowException("The message", inner);
     Assert.True((object)ex is OverflowException, "is OverflowException");
     Assert.True(ReferenceEquals(ex.InnerException, inner), "InnerException");
     Assert.AreEqual(ex.Message, "The message");
 }
        /// <summary>
        /// Gets the sitemap XML for the current site. If there are more than 50,000 sitemap nodes 
        /// (The maximum allowed before you have to use a sitemap index file), the list is truncated and an error is logged.
        /// See http://www.sitemaps.org/protocol.html for more information.
        /// </summary>
        /// <returns>The sitemap XML for the current site.</returns>
        public string GetSitemapXml()
        {
            IReadOnlyCollection<SitemapNode> sitemapNotes = this.GetSitemapNodes();

            if (sitemapNotes.Count > MaximumSitemapNodeCount)
            {
                OverflowException overflowException = new OverflowException(string.Format("There are too many sitemap nodes, the collection has been truncated. If you want to use more than 50,000, you must use a sitemap index file (See http://www.sitemaps.org/protocol.html). Count:<{0}>.", sitemapNotes.Count));
                this.loggingService.Log(overflowException);
            }

            XNamespace xmlns = SitemapsNamespace;
            XElement root = new XElement(xmlns + "urlset");
            foreach (SitemapNode sitemapNode in sitemapNotes.Take(MaximumSitemapNodeCount))
            {
                root.Add(
                    new XElement(xmlns + "url",
                        new XElement(xmlns + "loc", Uri.EscapeUriString(sitemapNode.Url)),
                        sitemapNode.LastModified == null ? null : new XElement(xmlns + "lastmod", sitemapNode.LastModified.Value.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:sszzz")),
                        sitemapNode.Frequency == null ? null : new XElement(xmlns + "changefreq", sitemapNode.Frequency.Value.ToString().ToLowerInvariant()),
                        sitemapNode.Priority == null ? null : new XElement(xmlns + "priority", sitemapNode.Priority.Value.ToString("F1", CultureInfo.InvariantCulture))));
            }

            return root.ToString();
        }
 internal Exception TryToTimeSpan(DurationType durationType, out TimeSpan result)
 {
     Exception exception = null;
     ulong num = 0L;
     try
     {
         if (durationType != DurationType.DayTimeDuration)
         {
             num += (((ulong) this.years) + (((ulong) this.months) / 12L)) * ((ulong) 0x16dL);
             num += (((ulong) this.months) % 12L) * ((ulong) 30L);
         }
         if (durationType != DurationType.YearMonthDuration)
         {
             num += (ulong) this.days;
             num *= (ulong) 0x18L;
             num += (ulong) this.hours;
             num *= (ulong) 60L;
             num += (ulong) this.minutes;
             num *= (ulong) 60L;
             num += (ulong) this.seconds;
             num *= (ulong) 0x989680L;
             num += ((ulong) this.Nanoseconds) / 100L;
         }
         else
         {
             num *= (ulong) 0xc92a69c000L;
         }
         if (this.IsNegative)
         {
             if (num == 9223372036854775808L)
             {
                 result = new TimeSpan(-9223372036854775808L);
             }
             else
             {
                 result = new TimeSpan(0L - ((long) num));
             }
         }
         else
         {
             result = new TimeSpan((long) num);
         }
         return null;
     }
     catch (OverflowException)
     {
         result = TimeSpan.MinValue;
         exception = new OverflowException(Res.GetString("XmlConvert_Overflow", new object[] { durationType, "TimeSpan" }));
     }
     return exception;
 }
Example #8
0
        internal static bool Parse(string s, bool tryParse, out ulong result, out Exception exc)
        {
            ulong val = 0;
            int   len;
            int   i;
            bool  digits_seen       = false;
            bool  has_negative_sign = false;

            exc    = null;
            result = 0;

            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }

            len = s.Length;

            char c;

            for (i = 0; i < len; i++)
            {
                c = s [i];
                if (!Char.IsWhiteSpace(c))
                {
                    break;
                }
            }

            if (i == len)
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            if (s [i] == '+')
            {
                i++;
            }
            else if (s [i] == '-')
            {
                i++;
                has_negative_sign = true;
            }

            // Actual number stuff
            for (; i < len; i++)
            {
                c = s [i];

                if (c >= '0' && c <= '9')
                {
                    uint d = (uint)(c - '0');

                    if (val > MaxValue / 10 || (val == MaxValue / 10 && d > MaxValue % 10))
                    {
                        if (!tryParse)
                        {
                            exc = new OverflowException("Value is too large.");
                        }
                        return(false);
                    }

                    val         = (val * 10) + d;
                    digits_seen = true;
                }
                else if (!Int32.ProcessTrailingWhitespace(tryParse, s, i, ref exc))
                {
                    return(false);
                }
            }

            if (!digits_seen)
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            if (has_negative_sign && val > 0)
            {
                if (!tryParse)
                {
                    exc = new OverflowException("Negative number.");
                }
                return(false);
            }

            result = val;
            return(true);
        }
Example #9
0
        internal static bool Parse(string s, bool tryParse, out uint result, out Exception exc)
        {
            uint val = 0;
            int  len;
            int  i;
            bool digits_seen       = false;
            bool has_negative_sign = false;

            result = 0;
            exc    = null;

            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }

            len = s.Length;

            char c;

            for (i = 0; i < len; i++)
            {
                c = s [i];
                if (!Char.IsWhiteSpace(c))
                {
                    break;
                }
            }

            if (i == len)
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            if (s [i] == '+')
            {
                i++;
            }
            else
            if (s[i] == '-')
            {
                i++;
                has_negative_sign = true;
            }

            for (; i < len; i++)
            {
                c = s [i];

                if (c >= '0' && c <= '9')
                {
                    uint d = (uint)(c - '0');

                    if ((val > MaxValue / 10) || (val == (MaxValue / 10) && d > (MaxValue % 10)))
                    {
                        if (!tryParse)
                        {
                            exc = new OverflowException(Locale.GetText("Value is too large"));
                        }
                        return(false);
                    }
                    val         = (val * 10) + d;
                    digits_seen = true;
                }
                else if (!Int32.ProcessTrailingWhitespace(tryParse, s, i, ref exc))
                {
                    return(false);
                }
            }
            if (!digits_seen)
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            // -0 is legal but other negative values are not
            if (has_negative_sign && (val > 0))
            {
                if (!tryParse)
                {
                    exc = new OverflowException(
                        Locale.GetText("Negative number"));
                }
                return(false);
            }

            result = val;
            return(true);
        }
Example #10
0
        // FIXME: check if digits are group in correct numbers between the group separators
        internal static bool Parse(string s, NumberStyles style, IFormatProvider provider, bool tryParse, out double result, out Exception exc)
        {
            result = 0;
            exc    = null;

            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }
            if (s.Length == 0)
            {
                if (!tryParse)
                {
                    exc = new FormatException();
                }
                return(false);
            }
#if NET_2_0
            // yes it's counter intuitive (buggy?) but even TryParse actually throws in this case
            if ((style & NumberStyles.AllowHexSpecifier) != 0)
            {
                string msg = Locale.GetText("Double doesn't support parsing with '{0}'.", "AllowHexSpecifier");
                throw new ArgumentException(msg);
            }
#endif
            if (style > NumberStyles.Any)
            {
                if (!tryParse)
                {
                    exc = new ArgumentException();
                }
                return(false);
            }

            NumberFormatInfo format = NumberFormatInfo.GetInstance(provider);
            if (format == null)
            {
                throw new Exception("How did this happen?");
            }

            if (s == format.NaNSymbol)
            {
                result = Double.NaN;
                return(true);
            }
            if (s == format.PositiveInfinitySymbol)
            {
                result = Double.PositiveInfinity;
                return(true);
            }
            if (s == format.NegativeInfinitySymbol)
            {
                result = Double.NegativeInfinity;
                return(true);
            }

            //
            // validate and prepare string for C
            //
            int    len    = s.Length;
            string numstr = "";
            int    didx   = 0;
            int    sidx   = 0;
            char   c;

            if ((style & NumberStyles.AllowLeadingWhite) != 0)
            {
                while (sidx < len && Char.IsWhiteSpace(c = s[sidx]))
                {
                    sidx++;
                }

                if (sidx == len)
                {
                    if (!tryParse)
                    {
                        exc = IntParser.GetFormatException();
                    }
                    return(false);
                }
            }

            bool allow_trailing_white = ((style & NumberStyles.AllowTrailingWhite) != 0);

            //
            // Machine state
            //
            int state = State_AllowSign;

            //
            // Setup
            //
            string decimal_separator     = null;
            string group_separator       = null;
            string currency_symbol       = null;
            int    decimal_separator_len = 0;
            int    group_separator_len   = 0;
            int    currency_symbol_len   = 0;
            if ((style & NumberStyles.AllowDecimalPoint) != 0)
            {
                decimal_separator     = format.NumberDecimalSeparator;
                decimal_separator_len = decimal_separator.Length;
            }
            if ((style & NumberStyles.AllowThousands) != 0)
            {
                group_separator     = format.NumberGroupSeparator;
                group_separator_len = group_separator.Length;
            }
            if ((style & NumberStyles.AllowCurrencySymbol) != 0)
            {
                currency_symbol     = format.CurrencySymbol;
                currency_symbol_len = currency_symbol.Length;
            }
            string positive = format.PositiveSign;
            string negative = format.NegativeSign;

            for (; sidx < len; sidx++)
            {
                c = s[sidx];

                if (c == '\0')
                {
                    sidx = len;
                    continue;
                }

                switch (state)
                {
                case State_AllowSign:
                    if ((style & NumberStyles.AllowLeadingSign) != 0)
                    {
                        if (c == positive[0] &&
                            s.Substring(sidx, positive.Length) == positive)
                        {
                            state = State_Digits;
                            sidx += positive.Length - 1;
                            continue;
                        }

                        if (c == negative[0] &&
                            s.Substring(sidx, negative.Length) == negative)
                        {
                            state   = State_Digits;
                            numstr += '-';
                            sidx   += negative.Length - 1;
                            continue;
                        }
                    }
                    state = State_Digits;
                    goto case State_Digits;

                case State_Digits:
                    if (Char.IsDigit(c))
                    {
                        numstr += c;
                        break;
                    }
                    if (c == 'e' || c == 'E')
                    {
                        goto case State_Decimal;
                    }

                    if (decimal_separator != null &&
                        decimal_separator[0] == c)
                    {
                        if (String.CompareOrdinal(s, sidx, decimal_separator, 0, decimal_separator_len) == 0)
                        {
                            numstr += '.';
                            sidx   += decimal_separator_len - 1;
                            state   = State_Decimal;
                            break;
                        }
                    }
                    if (group_separator != null &&
                        group_separator[0] == c)
                    {
                        if (s.Substring(sidx, group_separator_len) ==
                            group_separator)
                        {
                            sidx += group_separator_len - 1;
                            state = State_Digits;
                            break;
                        }
                    }
                    if (currency_symbol != null &&
                        currency_symbol[0] == c)
                    {
                        if (s.Substring(sidx, currency_symbol_len) ==
                            currency_symbol)
                        {
                            sidx += currency_symbol_len - 1;
                            state = State_Digits;
                            break;
                        }
                    }

                    if (Char.IsWhiteSpace(c))
                    {
                        goto case State_ConsumeWhiteSpace;
                    }

                    if (!tryParse)
                    {
                        exc = new FormatException("Unknown char: " + c);
                    }
                    return(false);

                case State_Decimal:
                    if (Char.IsDigit(c))
                    {
                        numstr += c;
                        break;
                    }

                    if (c == 'e' || c == 'E')
                    {
                        if ((style & NumberStyles.AllowExponent) == 0)
                        {
                            if (!tryParse)
                            {
                                exc = new FormatException("Unknown char: " + c);
                            }
                            return(false);
                        }
                        numstr += c;
                        state   = State_ExponentSign;
                        break;
                    }

                    if (Char.IsWhiteSpace(c))
                    {
                        goto case State_ConsumeWhiteSpace;
                    }

                    if (!tryParse)
                    {
                        exc = new FormatException("Unknown char: " + c);
                    }
                    return(false);

                case State_ExponentSign:
                    if (Char.IsDigit(c))
                    {
                        state = State_Exponent;
                        goto case State_Exponent;
                    }

                    if (c == positive[0] &&
                        s.Substring(sidx, positive.Length) == positive)
                    {
                        state = State_Digits;
                        sidx += positive.Length - 1;
                        continue;
                    }

                    if (c == negative[0] &&
                        s.Substring(sidx, negative.Length) == negative)
                    {
                        state   = State_Digits;
                        numstr += '-';
                        sidx   += negative.Length - 1;
                        continue;
                    }

                    if (Char.IsWhiteSpace(c))
                    {
                        goto case State_ConsumeWhiteSpace;
                    }

                    if (!tryParse)
                    {
                        exc = new FormatException("Unknown char: " + c);
                    }
                    return(false);

                case State_Exponent:
                    if (Char.IsDigit(c))
                    {
                        numstr += c;
                        break;
                    }

                    if (Char.IsWhiteSpace(c))
                    {
                        goto case State_ConsumeWhiteSpace;
                    }

                    if (!tryParse)
                    {
                        exc = new FormatException("Unknown char: " + c);
                    }
                    return(false);

                case State_ConsumeWhiteSpace:
                    if (allow_trailing_white && Char.IsWhiteSpace(c))
                    {
                        state = State_ConsumeWhiteSpace;
                        break;
                    }

                    if (!tryParse)
                    {
                        exc = new FormatException("Unknown char");
                    }
                    return(false);
                }

                if (state == State_Exit)
                {
                    break;
                }
            }

            double retVal;
            try
            {
                retVal = Native.Global.parseFloat(numstr);
            }
            catch
            {
                if (!tryParse)
                {
                    exc = IntParser.GetFormatException();
                }
                return(false);
            }

            //if (!ParseImpl(p, out retVal))
            //{
            //    if (!tryParse)
            //        exc = IntParser.GetFormatException();
            //    return false;
            //}

            if (IsPositiveInfinity(retVal) || IsNegativeInfinity(retVal))
            {
                if (!tryParse)
                {
                    exc = new OverflowException();
                }
                return(false);
            }

            result = retVal;
            return(true);
        }
        internal Exception TryToTimeSpan(DurationType durationType, out TimeSpan result) {
            Exception exception = null; 
            ulong ticks = 0;

            // Throw error if result cannot fit into a long
            try {
                checked {
                    // Discard year and month parts if constructing TimeSpan for DayTimeDuration
                    if (durationType != DurationType.DayTimeDuration) {
                        ticks += ((ulong) this.years + (ulong) this.months / 12) * 365;
                        ticks += ((ulong) this.months % 12) * 30;
                    }

                    // Discard day and time parts if constructing TimeSpan for YearMonthDuration
                    if (durationType != DurationType.YearMonthDuration) {
                        ticks += (ulong) this.days;

                        ticks *= 24;
                        ticks += (ulong) this.hours;

                        ticks *= 60;
                        ticks += (ulong) this.minutes;

                        ticks *= 60;
                        ticks += (ulong) this.seconds;

                        // Tick count interval is in 100 nanosecond intervals (7 digits)
                        ticks *= (ulong) TimeSpan.TicksPerSecond;
                        ticks += (ulong) Nanoseconds / 100;
                    }
                    else {
                        // Multiply YearMonth duration by number of ticks per day
                        ticks *= (ulong) TimeSpan.TicksPerDay;
                    }

                    if (IsNegative) {
                        // Handle special case of Int64.MaxValue + 1 before negation, since it would otherwise overflow
                        if (ticks == (ulong) Int64.MaxValue + 1) {
                            result = new TimeSpan(Int64.MinValue);
                        }
                        else {
                            result = new TimeSpan(-((long) ticks));
                        }
                    }
                    else {
                        result = new TimeSpan((long) ticks);
                    }
                    return null;
                }
            }
            catch (OverflowException) {
                result = TimeSpan.MinValue;
                exception = new OverflowException(Res.GetString(Res.XmlConvert_Overflow, durationType, "TimeSpan"));
            }
            return exception;
        }
Example #12
0
File: SByte.cs Project: yonder/mono
        internal static bool Parse(string s, bool tryParse, out sbyte result, out Exception exc)
        {
            int  ival = 0;
            int  len;
            int  i;
            bool neg         = false;
            bool digits_seen = false;

            result = 0;
            exc    = null;

            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }

            len = s.Length;

            char c;

            for (i = 0; i < len; i++)
            {
                c = s [i];
                if (!Char.IsWhiteSpace(c))
                {
                    break;
                }
            }

            if (i == len)
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            c = s [i];
            if (c == '+')
            {
                i++;
            }
            else if (c == '-')
            {
                neg = true;
                i++;
            }

            for (; i < len; i++)
            {
                c = s [i];

                if (c >= '0' && c <= '9')
                {
                    if (tryParse)
                    {
                        int intval = ival * 10 - (int)(c - '0');

                        if (intval < MinValue)
                        {
                            return(false);
                        }
                        ival = (sbyte)intval;
                    }
                    else
                    {
                        ival = checked (ival * 10 - (int)(c - '0'));
                    }
                    digits_seen = true;
                }
                else
                {
                    if (Char.IsWhiteSpace(c))
                    {
                        for (i++; i < len; i++)
                        {
                            if (!Char.IsWhiteSpace(s [i]))
                            {
                                if (!tryParse)
                                {
                                    exc = Int32.GetFormatException();
                                }
                                return(false);
                            }
                        }
                        break;
                    }
                    else
                    {
                        if (!tryParse)
                        {
                            exc = Int32.GetFormatException();
                        }
                        return(false);
                    }
                }
            }
            if (!digits_seen)
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            ival = neg ? ival : -ival;
            if (ival < SByte.MinValue || ival > SByte.MaxValue)
            {
                if (!tryParse)
                {
                    exc = new OverflowException();
                }
                return(false);
            }

            result = (sbyte)ival;
            return(true);
        }
Example #13
0
        /// <summary>
        /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException.
        /// and in winrt and marshal APIs as Exception.
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="message"></param>
        /// <param name="createCOMException"></param>
        /// <returns></returns>
        internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo)
        {
            if (errorCode >= 0)
            {
                return null;
            }

            Exception exception = null;

            bool shouldDisplayHR = false;

            switch (errorCode)
            {
                case __HResults.COR_E_NOTFINITENUMBER: // NotFiniteNumberException
                case __HResults.COR_E_ARITHMETIC:
                    exception = new ArithmeticException();
                    break;
                case __HResults.COR_E_ARGUMENT:
                case unchecked((int)0x800A01C1):
                case unchecked((int)0x800A01C2):
                case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT:
                    exception = new ArgumentException();

                    if (errorCode != __HResults.COR_E_ARGUMENT)
                        shouldDisplayHR = true;

                    break;
                case __HResults.E_BOUNDS:
                case __HResults.COR_E_ARGUMENTOUTOFRANGE:
                case __HResults.ERROR_NO_UNICODE_TRANSLATION:
                    exception = new ArgumentOutOfRangeException();

                    if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_ARRAYTYPEMISMATCH:
                    exception = new ArrayTypeMismatchException();
                    break;
                case __HResults.COR_E_BADIMAGEFORMAT:
                case __HResults.CLDB_E_FILE_OLDVER:
                case __HResults.CLDB_E_INDEX_NOTFOUND:
                case __HResults.CLDB_E_FILE_CORRUPT:
                case __HResults.COR_E_NEWER_RUNTIME:
                case __HResults.COR_E_ASSEMBLYEXPECTED:
                case __HResults.ERROR_BAD_EXE_FORMAT:
                case __HResults.ERROR_EXE_MARKED_INVALID:
                case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT:
                case __HResults.ERROR_NOACCESS:
                case __HResults.ERROR_INVALID_ORDINAL:
                case __HResults.ERROR_INVALID_DLL:
                case __HResults.ERROR_FILE_CORRUPT:
                case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY:
                case __HResults.META_E_BAD_SIGNATURE:
                    exception = new BadImageFormatException();

                    // Always show HR for BadImageFormatException
                    shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT:
                    exception = new FormatException();
                    break; // CustomAttributeFormatException
                case __HResults.COR_E_DATAMISALIGNED:
                    exception = InteropExtensions.CreateDataMisalignedException(message); // TODO: Do we need to add msg here?
                    break;
                case __HResults.COR_E_DIVIDEBYZERO:
                case __HResults.CTL_E_DIVISIONBYZERO:
                    exception = new DivideByZeroException();

                    if (errorCode != __HResults.COR_E_DIVIDEBYZERO)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_DLLNOTFOUND:
#if ENABLE_WINRT
                    exception = new DllNotFoundException();
#endif
                    break;
                case __HResults.COR_E_DUPLICATEWAITOBJECT:
                    exception = new ArgumentException();
                    break; // DuplicateWaitObjectException
                case __HResults.COR_E_ENDOFSTREAM:
                case unchecked((int)0x800A003E):
                    exception = new System.IO.EndOfStreamException();

                    if (errorCode != __HResults.COR_E_ENDOFSTREAM)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_TYPEACCESS: // TypeAccessException
                case __HResults.COR_E_ENTRYPOINTNOTFOUND:
                    exception = new TypeLoadException();

                    break; // EntryPointNotFoundException
                case __HResults.COR_E_EXCEPTION:
                    exception = new Exception();
                    break;
                case __HResults.COR_E_DIRECTORYNOTFOUND:
                case __HResults.STG_E_PATHNOTFOUND:
                case __HResults.CTL_E_PATHNOTFOUND:
                    exception = new System.IO.DirectoryNotFoundException();

                    if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_FILELOAD:
                case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION:
                case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED:
                case __HResults.FUSION_E_LOADFROM_BLOCKED:
                case __HResults.FUSION_E_CACHEFILE_FAILED:
                case __HResults.FUSION_E_ASM_MODULE_MISSING:
                case __HResults.FUSION_E_INVALID_NAME:
                case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED:
                case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH:
                case __HResults.COR_E_MODULE_HASH_CHECK_FAILED:
                case __HResults.FUSION_E_REF_DEF_MISMATCH:
                case __HResults.SECURITY_E_INCOMPATIBLE_SHARE:
                case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE:
                case __HResults.SECURITY_E_UNVERIFIABLE:
                case __HResults.COR_E_FIXUPSINEXE:
                case __HResults.ERROR_TOO_MANY_OPEN_FILES:
                case __HResults.ERROR_SHARING_VIOLATION:
                case __HResults.ERROR_LOCK_VIOLATION:
                case __HResults.ERROR_OPEN_FAILED:
                case __HResults.ERROR_DISK_CORRUPT:
                case __HResults.ERROR_UNRECOGNIZED_VOLUME:
                case __HResults.ERROR_DLL_INIT_FAILED:
                case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED:
                case __HResults.CORSEC_E_MISSING_STRONGNAME:
                case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS:
                case __HResults.ERROR_FILE_INVALID:
                    exception = new System.IO.FileLoadException();

                    shouldDisplayHR = true;
                    break;
                case __HResults.COR_E_PATHTOOLONG:
                    exception = new System.IO.PathTooLongException();
                    break;
                case __HResults.COR_E_IO:
                case __HResults.CTL_E_DEVICEIOERROR:
                case unchecked((int)0x800A793C):
                case unchecked((int)0x800A793D):
                    exception = new System.IO.IOException();

                    if (errorCode != __HResults.COR_E_IO)
                        shouldDisplayHR = true;

                    break;
                case __HResults.ERROR_FILE_NOT_FOUND:
                case __HResults.ERROR_MOD_NOT_FOUND:
                case __HResults.ERROR_INVALID_NAME:
                case __HResults.CTL_E_FILENOTFOUND:
                case __HResults.ERROR_BAD_NET_NAME:
                case __HResults.ERROR_BAD_NETPATH:
                case __HResults.ERROR_NOT_READY:
                case __HResults.ERROR_WRONG_TARGET_NAME:
                case __HResults.INET_E_UNKNOWN_PROTOCOL:
                case __HResults.INET_E_CONNECTION_TIMEOUT:
                case __HResults.INET_E_CANNOT_CONNECT:
                case __HResults.INET_E_RESOURCE_NOT_FOUND:
                case __HResults.INET_E_OBJECT_NOT_FOUND:
                case __HResults.INET_E_DOWNLOAD_FAILURE:
                case __HResults.INET_E_DATA_NOT_AVAILABLE:
                case __HResults.ERROR_DLL_NOT_FOUND:
                case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW:
                case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH:
                case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND:
                    exception = new System.IO.FileNotFoundException();

                    shouldDisplayHR = true;
                    break;
                case __HResults.COR_E_FORMAT:
                    exception = new FormatException();
                    break;
                case __HResults.COR_E_INDEXOUTOFRANGE:
                case unchecked((int)0x800a0009):
                    exception = new IndexOutOfRangeException();

                    if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_INVALIDCAST:
                    exception = new InvalidCastException();
                    break;
                case __HResults.COR_E_INVALIDCOMOBJECT:
                    exception = new InvalidComObjectException();
                    break;
                case __HResults.COR_E_INVALIDOLEVARIANTTYPE:
                    exception = new InvalidOleVariantTypeException();
                    break;
                case __HResults.COR_E_INVALIDOPERATION:
                case __HResults.E_ILLEGAL_STATE_CHANGE:
                case __HResults.E_ILLEGAL_METHOD_CALL:
                case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT:
                case __HResults.APPMODEL_ERROR_NO_PACKAGE:
                    exception = new InvalidOperationException();

                    if (errorCode != __HResults.COR_E_INVALIDOPERATION)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_MARSHALDIRECTIVE:
                    exception = new MarshalDirectiveException();
                    break;
                case __HResults.COR_E_METHODACCESS: // MethodAccessException
                case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException
                case __HResults.COR_E_FIELDACCESS:
                case __HResults.COR_E_MEMBERACCESS:
                    exception = new MemberAccessException();

                    if (errorCode != __HResults.COR_E_METHODACCESS)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_MISSINGFIELD: // MissingFieldException
                case __HResults.COR_E_MISSINGMETHOD: // MissingMethodException
                case __HResults.COR_E_MISSINGMEMBER:
                case unchecked((int)0x800A01CD):
                    exception = new MissingMemberException();
                    break;
                case __HResults.COR_E_MISSINGMANIFESTRESOURCE:
                    exception = new System.Resources.MissingManifestResourceException();
                    break;
                case __HResults.COR_E_NOTSUPPORTED:
                case unchecked((int)0x800A01B6):
                case unchecked((int)0x800A01BD):
                case unchecked((int)0x800A01CA):
                case unchecked((int)0x800A01CB):
                    exception = new NotSupportedException();

                    if (errorCode != __HResults.COR_E_NOTSUPPORTED)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_NULLREFERENCE:
                    exception = new NullReferenceException();
                    break;
                case __HResults.COR_E_OBJECTDISPOSED:
                case __HResults.RO_E_CLOSED:
                    // No default constructor
                    exception = new ObjectDisposedException(String.Empty);
                    break;
                case __HResults.COR_E_OPERATIONCANCELED:
#if ENABLE_WINRT
                    exception = new OperationCanceledException();
#endif
                    break;
                case __HResults.COR_E_OVERFLOW:
                case __HResults.CTL_E_OVERFLOW:
                    exception = new OverflowException();
                    break;
                case __HResults.COR_E_PLATFORMNOTSUPPORTED:
                    exception = new PlatformNotSupportedException(message);
                    break;
                case __HResults.COR_E_RANK:
                    exception = new RankException();
                    break;
                case __HResults.COR_E_REFLECTIONTYPELOAD:
#if ENABLE_WINRT
                    exception = new System.Reflection.ReflectionTypeLoadException(null, null);
#endif
                    break;
                case __HResults.COR_E_SECURITY:
                case __HResults.CORSEC_E_INVALID_STRONGNAME:
                case __HResults.CTL_E_PERMISSIONDENIED:
                case unchecked((int)0x800A01A3):
                case __HResults.CORSEC_E_INVALID_PUBLICKEY:
                case __HResults.CORSEC_E_SIGNATURE_MISMATCH:
                    exception = new System.Security.SecurityException();
                    break;
                case __HResults.COR_E_SAFEARRAYRANKMISMATCH:
                    exception = new SafeArrayRankMismatchException();
                    break;
                case __HResults.COR_E_SAFEARRAYTYPEMISMATCH:
                    exception = new SafeArrayTypeMismatchException();
                    break;
                case __HResults.COR_E_SERIALIZATION:
                    exception = new System.Runtime.Serialization.SerializationException(message);
                    break;
                case __HResults.COR_E_SYNCHRONIZATIONLOCK:
                    exception = new System.Threading.SynchronizationLockException();
                    break;
                case __HResults.COR_E_TARGETINVOCATION:
                    exception = new System.Reflection.TargetInvocationException(null);
                    break;
                case __HResults.COR_E_TARGETPARAMCOUNT:
                    exception = new System.Reflection.TargetParameterCountException();
                    break;
                case __HResults.COR_E_TYPEINITIALIZATION:
                    exception = InteropExtensions.CreateTypeInitializationException(message);
                    break;
                case __HResults.COR_E_TYPELOAD:
                case __HResults.RO_E_METADATA_NAME_NOT_FOUND:
                case __HResults.CLR_E_BIND_TYPE_NOT_FOUND:
                    exception = new TypeLoadException();

                    if (errorCode != __HResults.COR_E_TYPELOAD)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_UNAUTHORIZEDACCESS:
                case __HResults.CTL_E_PATHFILEACCESSERROR:
                case unchecked((int)0x800A014F):
                    exception = new UnauthorizedAccessException();

                    shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_VERIFICATION:
                    exception = new System.Security.VerificationException();
                    break;
                case __HResults.E_NOTIMPL:
                    exception = new NotImplementedException();
                    break;
                case __HResults.E_OUTOFMEMORY:
                case __HResults.CTL_E_OUTOFMEMORY:
                case unchecked((int)0x800A7919):
                    exception = new OutOfMemoryException();

                    if (errorCode != __HResults.E_OUTOFMEMORY)
                        shouldDisplayHR = true;

                    break;
#if ENABLE_WINRT
                case __HResults.E_XAMLPARSEFAILED:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                        message);
                    break;
                case __HResults.E_ELEMENTNOTAVAILABLE:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                        message);
                    break;
                case __HResults.E_ELEMENTNOTENABLED:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", 
                        message);
                    break;
                case __HResults.E_LAYOUTCYCLE:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", 
                        message);
                    break;
#endif // ENABLE_WINRT
                case __HResults.COR_E_AMBIGUOUSMATCH: // AmbiguousMatchException
                case __HResults.COR_E_APPLICATION: // ApplicationException
                case __HResults.COR_E_APPDOMAINUNLOADED: // AppDomainUnloadedException
                case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN: // CannotUnloadAppDomainException
                case __HResults.COR_E_CODECONTRACTFAILED: // ContractException
                case __HResults.COR_E_CONTEXTMARSHAL: // ContextMarshalException
                case __HResults.CORSEC_E_CRYPTO: // CryptographicException
                case __HResults.CORSEC_E_CRYPTO_UNEX_OPER: // CryptographicUnexpectedOperationException
                case __HResults.COR_E_EXECUTIONENGINE: // ExecutionEngineException
                case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException
                case __HResults.COR_E_INVALIDFILTERCRITERIA: // InvalidFilterCriteriaException
                case __HResults.COR_E_INVALIDPROGRAM: // InvalidProgramException
                case __HResults.COR_E_MULTICASTNOTSUPPORTED: // MulticastNotSupportedException
                case __HResults.COR_E_REMOTING: // RemotingException
                case __HResults.COR_E_RUNTIMEWRAPPED: // RuntimeWrappedException
                case __HResults.COR_E_SERVER: // ServerException
                case __HResults.COR_E_STACKOVERFLOW: // StackOverflowException
                case __HResults.CTL_E_OUTOFSTACKSPACE: // StackOverflowException
                case __HResults.COR_E_SYSTEM: // SystemException
                case __HResults.COR_E_TARGET: // TargetException
                case __HResults.COR_E_THREADABORTED: // TargetException
                case __HResults.COR_E_THREADINTERRUPTED: // ThreadInterruptedException
                case __HResults.COR_E_THREADSTATE: // ThreadStateException
                case __HResults.COR_E_THREADSTART: // ThreadStartException
                case __HResults.COR_E_TYPEUNLOADED: // TypeUnloadedException
                case __HResults.CORSEC_E_POLICY_EXCEPTION: // PolicyException
                case __HResults.CORSEC_E_NO_EXEC_PERM: // PolicyException
                case __HResults.CORSEC_E_MIN_GRANT_FAIL: // PolicyException
                case __HResults.CORSEC_E_XMLSYNTAX: // XmlSyntaxException
                case __HResults.ISS_E_ALLOC_TOO_LARGE: // IsolatedStorageException
                case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL: // IsolatedStorageException
                case __HResults.ISS_E_CALLER: // IsolatedStorageException
                case __HResults.ISS_E_CORRUPTED_STORE_FILE: // IsolatedStorageException
                case __HResults.ISS_E_CREATE_DIR: // IsolatedStorageException
                case __HResults.ISS_E_CREATE_MUTEX: // IsolatedStorageException
                case __HResults.ISS_E_DEPRECATE: // IsolatedStorageException
                case __HResults.ISS_E_FILE_NOT_MAPPED: // IsolatedStorageException
                case __HResults.ISS_E_FILE_WRITE: // IsolatedStorageException
                case __HResults.ISS_E_GET_FILE_SIZE: // IsolatedStorageException
                case __HResults.ISS_E_ISOSTORE: // IsolatedStorageException
                case __HResults.ISS_E_LOCK_FAILED: // IsolatedStorageException
                case __HResults.ISS_E_MACHINE: // IsolatedStorageException
                case __HResults.ISS_E_MACHINE_DACL: // IsolatedStorageException
                case __HResults.ISS_E_MAP_VIEW_OF_FILE: // IsolatedStorageException
                case __HResults.ISS_E_OPEN_FILE_MAPPING: // IsolatedStorageException
                case __HResults.ISS_E_OPEN_STORE_FILE: // IsolatedStorageException
                case __HResults.ISS_E_PATH_LENGTH: // IsolatedStorageException
                case __HResults.ISS_E_SET_FILE_POINTER: // IsolatedStorageException
                case __HResults.ISS_E_STORE_NOT_OPEN: // IsolatedStorageException
                case __HResults.ISS_E_STORE_VERSION: // IsolatedStorageException
                case __HResults.ISS_E_TABLE_ROW_NOT_FOUND: // IsolatedStorageException
                case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA: // IsolatedStorageException
                case __HResults.E_FAIL:
                default:
                    break;
            }

            if (exception == null)
            {
                if (createCOMException)
                {
                    exception = new COMException();
                    if (errorCode != __HResults.E_FAIL)
                        shouldDisplayHR = true;
                }
                else
                {
                    exception = new Exception();
                    if (errorCode != __HResults.COR_E_EXCEPTION)
                        shouldDisplayHR = true;
                 }
            }

            bool shouldConstructMessage = false;
            if (hasErrorInfo)
            {
                // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if
                // the message is not available and do not use the shouldDisplayHR setting
                if (message == null)
                    shouldConstructMessage = true;
            }
            else
            {
                // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above
                shouldConstructMessage = shouldDisplayHR;
            }

            if (shouldConstructMessage)
            {
                //
                // Append the HR into error message, just in case the app wants to look at the HR in
                // message to determine behavior.  We didn't expose HResult property until v4.5 and
                // GetHRFromException has side effects so probably Message was their only choice.
                // This behavior is probably not exactly the same as in desktop but it is fine to append
                // more message at the end. In any case, having the HR in the error message are helpful
                // to developers.
                // This makes sure:
                // 1. We always have a HR 0xNNNNNNNN in the message
                // 2. Put in a nice "Exception thrown from HRESULT" message if we can
                // 3. Wrap it in () if there is an existing message
                //

                // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME
                string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString());

                message = ExternalInterop.GetMessage(errorCode);

                // Always make sure we have at least the HRESULT part in retail build or when the message
                // is empty.
                if (message == null)
                    message = hrMessage;
                else
                    message = message + " (" + hrMessage + ")";
            }

            if (message != null)
            {
                // Set message explicitly rather than calling constructor because certain ctors would append a
                // prefix to the message and that is not what we want
                InteropExtensions.SetExceptionMessage(exception, message);
            }

            InteropExtensions.SetExceptionErrorCode(exception, errorCode);

            return exception;
        }
Example #14
0
        internal static bool Parse(string s, NumberStyles style, IFormatProvider fp, bool tryParse, out int result, out Exception exc)
        {
            result = 0;
            exc    = null;

            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }

            if (s.Length == 0)
            {
                if (!tryParse)
                {
                    exc = GetFormatException();
                }
                return(false);
            }

            NumberFormatInfo nfi = null;

            if (fp != null)
            {
                Type typeNFI = typeof(System.Globalization.NumberFormatInfo);
                nfi = fp.GetFormat(typeNFI) as NumberFormatInfo;
            }
            if (nfi == null)
            {
                nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
            }

            if (!CheckStyle(style, tryParse, ref exc))
            {
                return(false);
            }

            bool AllowCurrencySymbol = (style & NumberStyles.AllowCurrencySymbol) != 0;
            bool AllowHexSpecifier   = (style & NumberStyles.AllowHexSpecifier) != 0;
            bool AllowThousands      = (style & NumberStyles.AllowThousands) != 0;
            bool AllowDecimalPoint   = (style & NumberStyles.AllowDecimalPoint) != 0;
            bool AllowParentheses    = (style & NumberStyles.AllowParentheses) != 0;
            bool AllowTrailingSign   = (style & NumberStyles.AllowTrailingSign) != 0;
            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;

            if (AllowLeadingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc))
            {
                return(false);
            }

            bool foundOpenParentheses = false;
            bool negative             = false;
            bool foundSign            = false;
            bool foundCurrency        = false;

            // Pre-number stuff
            if (AllowParentheses && s [pos] == '(')
            {
                foundOpenParentheses = true;
                foundSign            = true;
                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))
                {
                    return(false);
                }

                if (s.Substring(pos, nfi.NegativeSign.Length) == nfi.NegativeSign)
                {
                    if (!tryParse)
                    {
                        exc = GetFormatException();
                    }
                    return(false);
                }

                if (s.Substring(pos, nfi.PositiveSign.Length) == nfi.PositiveSign)
                {
                    if (!tryParse)
                    {
                        exc = GetFormatException();
                    }
                    return(false);
                }
            }

            if (AllowLeadingSign && !foundSign)
            {
                // Sign + Currency
                FindSign(ref pos, s, nfi, ref foundSign, ref negative);
                if (foundSign)
                {
                    if (AllowLeadingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (AllowCurrencySymbol)
                    {
                        FindCurrency(ref pos, s, nfi,
                                     ref foundCurrency);
                        if (foundCurrency && AllowLeadingWhite &&
                            !JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                        {
                            return(false);
                        }
                    }
                }
            }

            if (AllowCurrencySymbol && !foundCurrency)
            {
                // Currency + sign
                FindCurrency(ref pos, s, nfi, ref foundCurrency);
                if (foundCurrency)
                {
                    if (AllowLeadingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (foundCurrency)
                    {
                        if (!foundSign && AllowLeadingSign)
                        {
                            FindSign(ref pos, s, nfi, ref foundSign,
                                     ref negative);
                            if (foundSign && AllowLeadingWhite &&
                                !JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                            {
                                return(false);
                            }
                        }
                    }
                }
            }

            int  number          = 0;
            int  nDigits         = 0;
            int  decimalPointPos = -1;
            int  digitValue;
            char hexDigit;

            // Number stuff
            while (pos < s.Length)
            {
                if (!ValidDigit(s [pos], AllowHexSpecifier))
                {
                    if (AllowThousands &&
                        (FindOther(ref pos, s, nfi.NumberGroupSeparator) ||
                         FindOther(ref pos, s, nfi.CurrencyGroupSeparator)))
                    {
                        continue;
                    }

                    if (AllowDecimalPoint && decimalPointPos < 0 &&
                        (FindOther(ref pos, s, nfi.NumberDecimalSeparator) ||
                         FindOther(ref pos, s, nfi.CurrencyDecimalSeparator)))
                    {
                        decimalPointPos = nDigits;
                        continue;
                    }

                    break;
                }

                nDigits++;

                if (AllowHexSpecifier)
                {
                    hexDigit = s [pos++];
                    if (Char.IsDigit(hexDigit))
                    {
                        digitValue = (int)(hexDigit - '0');
                    }
                    else if (Char.IsLower(hexDigit))
                    {
                        digitValue = (int)(hexDigit - 'a' + 10);
                    }
                    else
                    {
                        digitValue = (int)(hexDigit - 'A' + 10);
                    }

                    uint unumber = (uint)number;
                    if (tryParse)
                    {
                        if ((unumber & 0xf0000000) != 0)
                        {
                            return(false);
                        }

                        number = (int)(unumber * 16u + (uint)digitValue);
                    }
                    else
                    {
                        number = (int)checked (unumber * 16u + (uint)digitValue);
                    }

                    continue;
                }

                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);
                }
            }

            // Post number stuff
            if (nDigits == 0)
            {
                if (!tryParse)
                {
                    exc = GetFormatException();
                }
                return(false);
            }

            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 && pos < s.Length)
                {
                    if (AllowTrailingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                }
            }

            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 && 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,
                                 ref negative);
                    }
                }
            }

            if (AllowTrailingWhite && pos < s.Length && !JumpOverWhite(ref pos, s, false, tryParse, ref exc))
            {
                return(false);
            }

            if (foundOpenParentheses)
            {
                if (pos >= s.Length || s [pos++] != ')')
                {
                    if (!tryParse)
                    {
                        exc = GetFormatException();
                    }
                    return(false);
                }
                if (AllowTrailingWhite && pos < s.Length && !JumpOverWhite(ref pos, s, false, tryParse, ref exc))
                {
                    return(false);
                }
            }

            if (pos < s.Length && s [pos] != '\u0000')
            {
                if (!tryParse)
                {
                    exc = GetFormatException();
                }
                return(false);
            }

            if (!negative && !AllowHexSpecifier)
            {
                if (tryParse)
                {
                    long lval = -((long)number);

                    if (lval < MinValue || lval > MaxValue)
                    {
                        return(false);
                    }
                    number = (int)lval;
                }
                else
                {
                    number = checked (-number);
                }
            }

            if (decimalPointPos >= 0)
            {
                exponent = exponent - nDigits + decimalPointPos;
            }

            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);
        }
Example #15
0
        internal static bool Parse(string s, bool tryParse, out sbyte result, out Exception exc)
        {
            int  num   = 0;
            bool flag  = false;
            bool flag2 = false;

            result = 0;
            exc    = null;
            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }
            int  length = s.Length;
            int  i;
            char c;

            for (i = 0; i < length; i++)
            {
                c = s[i];
                if (!char.IsWhiteSpace(c))
                {
                    break;
                }
            }
            if (i == length)
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            c = s[i];
            if (c == '+')
            {
                i++;
            }
            else if (c == '-')
            {
                flag = true;
                i++;
            }
            while (i < length)
            {
                c = s[i];
                if (c >= '0' && c <= '9')
                {
                    if (tryParse)
                    {
                        int num2 = num * 10 - (int)(c - '0');
                        if (num2 < -128)
                        {
                            return(false);
                        }
                        num = (int)((sbyte)num2);
                    }
                    else
                    {
                        num = checked (num * 10 - (int)(c - '0'));
                    }
                    flag2 = true;
                    i++;
                }
                else
                {
                    if (char.IsWhiteSpace(c))
                    {
                        for (i++; i < length; i++)
                        {
                            if (!char.IsWhiteSpace(s[i]))
                            {
                                if (!tryParse)
                                {
                                    exc = int.GetFormatException();
                                }
                                return(false);
                            }
                        }
                        break;
                    }
                    if (!tryParse)
                    {
                        exc = int.GetFormatException();
                    }
                    return(false);
                }
            }
            if (!flag2)
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            num = ((!flag) ? (-num) : num);
            if (num < -128 || num > 127)
            {
                if (!tryParse)
                {
                    exc = new OverflowException();
                }
                return(false);
            }
            result = (sbyte)num;
            return(true);
        }
Example #16
0
        internal static bool Parse(string s, bool tryParse, out uint result, out Exception exc)
        {
            uint val = 0;
            int  len;
            int  i;
            bool digits_seen       = false;
            bool has_negative_sign = false;

            result = 0;
            exc    = null;

            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }

            len = s.Length;

            char c;

            for (i = 0; i < len; i++)
            {
                c = s[i];
                if (!Char.IsWhiteSpace(c))
                {
                    break;
                }
            }

            if (i == len)
            {
                if (!tryParse)
                {
                    exc = IntParser.GetFormatException();
                }
                return(false);
            }

            if (s[i] == '+')
            {
                i++;
            }
            else
            if (s[i] == '-')
            {
                i++;
                has_negative_sign = true;
            }

            for (; i < len; i++)
            {
                c = s[i];

                if (c >= '0' && c <= '9')
                {
                    uint d = (uint)(c - '0');

                    ulong v = ((ulong)val) * 10 + d;
                    if (v > MaxValue)
                    {
                        if (!tryParse)
                        {
                            exc = IntParser.GetOverflowException();
                        }
                        return(false);
                    }
                    val         = (uint)v;
                    digits_seen = true;
                }
                else
                {
                    if (Char.IsWhiteSpace(c))
                    {
                        for (i++; i < len; i++)
                        {
                            if (!Char.IsWhiteSpace(s[i]))
                            {
                                if (!tryParse)
                                {
                                    exc = IntParser.GetFormatException();
                                }
                                return(false);
                            }
                        }
                        break;
                    }
                    else
                    {
                        if (!tryParse)
                        {
                            exc = IntParser.GetFormatException();
                        }
                        return(false);
                    }
                }
            }
            if (!digits_seen)
            {
                if (!tryParse)
                {
                    exc = IntParser.GetFormatException();
                }
                return(false);
            }

            // -0 is legal but other negative values are not
            if (has_negative_sign && (val > 0))
            {
                if (!tryParse)
                {
                    exc = new OverflowException(
                        Locale.GetText("Negative number"));
                }
                return(false);
            }

            result = val;
            return(true);
        }
Example #17
0
        internal static bool Parse(string s, bool tryParse, out long result, out Exception exc)
        {
            long num  = 0L;
            int  num2 = 1;
            bool flag = false;

            result = 0L;
            exc    = null;
            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }
            int  length = s.Length;
            int  i;
            char c;

            for (i = 0; i < length; i++)
            {
                c = s[i];
                if (!char.IsWhiteSpace(c))
                {
                    break;
                }
            }
            if (i == length)
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            c = s[i];
            if (c == '+')
            {
                i++;
            }
            else if (c == '-')
            {
                num2 = -1;
                i++;
            }
            while (i < length)
            {
                c = s[i];
                if (c >= '0' && c <= '9')
                {
                    byte b = (byte)(c - '0');
                    if (num <= 922337203685477580L)
                    {
                        if (num != 922337203685477580L)
                        {
                            num  = num * 10L + (long)b;
                            flag = true;
                            goto IL_166;
                        }
                        if ((long)b <= 7L || (num2 != 1 && (long)b <= 8L))
                        {
                            if (num2 == -1)
                            {
                                num = num * (long)num2 * 10L - (long)b;
                            }
                            else
                            {
                                num = num * 10L + (long)b;
                            }
                            if (int.ProcessTrailingWhitespace(tryParse, s, i + 1, ref exc))
                            {
                                result = num;
                                return(true);
                            }
                        }
                    }
                    if (!tryParse)
                    {
                        exc = new OverflowException("Value is too large");
                    }
                    return(false);
                }
                if (!int.ProcessTrailingWhitespace(tryParse, s, i, ref exc))
                {
                    return(false);
                }
IL_166:
                i++;
            }
            if (!flag)
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            if (num2 == -1)
            {
                result = num * (long)num2;
            }
            else
            {
                result = num;
            }
            return(true);
        }
Example #18
0
        internal static bool Parse(string s, NumberStyles style, IFormatProvider provider, bool tryParse, out uint result, out Exception exc)
        {
            result = 0u;
            exc    = null;
            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }
            if (s.Length == 0)
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            NumberFormatInfo numberFormatInfo = null;

            if (provider != null)
            {
                Type typeFromHandle = typeof(NumberFormatInfo);
                numberFormatInfo = (NumberFormatInfo)provider.GetFormat(typeFromHandle);
            }
            if (numberFormatInfo == null)
            {
                numberFormatInfo = Thread.CurrentThread.CurrentCulture.NumberFormat;
            }
            if (!int.CheckStyle(style, tryParse, ref exc))
            {
                return(false);
            }
            bool flag  = (style & NumberStyles.AllowCurrencySymbol) != NumberStyles.None;
            bool flag2 = (style & NumberStyles.AllowHexSpecifier) != NumberStyles.None;
            bool flag3 = (style & NumberStyles.AllowThousands) != NumberStyles.None;
            bool flag4 = (style & NumberStyles.AllowDecimalPoint) != NumberStyles.None;
            bool flag5 = (style & NumberStyles.AllowParentheses) != NumberStyles.None;
            bool flag6 = (style & NumberStyles.AllowTrailingSign) != NumberStyles.None;
            bool flag7 = (style & NumberStyles.AllowLeadingSign) != NumberStyles.None;
            bool flag8 = (style & NumberStyles.AllowTrailingWhite) != NumberStyles.None;
            bool flag9 = (style & NumberStyles.AllowLeadingWhite) != NumberStyles.None;
            int  num   = 0;

            if (flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
            {
                return(false);
            }
            bool flag10 = false;
            bool flag11 = false;
            bool flag12 = false;
            bool flag13 = false;

            if (flag5 && s[num] == '(')
            {
                flag10 = true;
                flag12 = true;
                flag11 = true;
                num++;
                if (flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                {
                    return(false);
                }
                if (s.Substring(num, numberFormatInfo.NegativeSign.Length) == numberFormatInfo.NegativeSign)
                {
                    if (!tryParse)
                    {
                        exc = int.GetFormatException();
                    }
                    return(false);
                }
                if (s.Substring(num, numberFormatInfo.PositiveSign.Length) == numberFormatInfo.PositiveSign)
                {
                    if (!tryParse)
                    {
                        exc = int.GetFormatException();
                    }
                    return(false);
                }
            }
            if (flag7 && !flag12)
            {
                int.FindSign(ref num, s, numberFormatInfo, ref flag12, ref flag11);
                if (flag12)
                {
                    if (flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (flag)
                    {
                        int.FindCurrency(ref num, s, numberFormatInfo, ref flag13);
                        if (flag13 && flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                        {
                            return(false);
                        }
                    }
                }
            }
            if (flag && !flag13)
            {
                int.FindCurrency(ref num, s, numberFormatInfo, ref flag13);
                if (flag13)
                {
                    if (flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (flag13 && !flag12 && flag7)
                    {
                        int.FindSign(ref num, s, numberFormatInfo, ref flag12, ref flag11);
                        if (flag12 && flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                        {
                            return(false);
                        }
                    }
                }
            }
            uint num2   = 0u;
            int  num3   = 0;
            bool flag14 = false;

            do
            {
                if (!int.ValidDigit(s[num], flag2))
                {
                    if (!flag3 || !int.FindOther(ref num, s, numberFormatInfo.NumberGroupSeparator))
                    {
                        if (flag14 || !flag4 || !int.FindOther(ref num, s, numberFormatInfo.NumberDecimalSeparator))
                        {
                            break;
                        }
                        flag14 = true;
                    }
                }
                else if (flag2)
                {
                    num3++;
                    char c = s[num++];
                    uint num4;
                    if (char.IsDigit(c))
                    {
                        num4 = (uint)(c - '0');
                    }
                    else if (char.IsLower(c))
                    {
                        num4 = (uint)(c - 'a' + '\n');
                    }
                    else
                    {
                        num4 = (uint)(c - 'A' + '\n');
                    }
                    if (tryParse)
                    {
                        ulong num5 = (ulong)(num2 * 16u + num4);
                        if (num5 > (ulong)-1)
                        {
                            return(false);
                        }
                        num2 = (uint)num5;
                    }
                    else
                    {
                        num2 = checked (num2 * 16u + num4);
                    }
                }
                else if (flag14)
                {
                    num3++;
                    if (s[num++] != '0')
                    {
                        goto Block_50;
                    }
                }
                else
                {
                    num3++;
                    try
                    {
                        num2 = checked (num2 * 10u + (uint)(s[num++] - '0'));
                    }
                    catch (OverflowException)
                    {
                        if (!tryParse)
                        {
                            exc = new OverflowException(Locale.GetText("Value too large or too small."));
                        }
                        return(false);
                    }
                }
            }while (num < s.Length);
            goto IL_435;
Block_50:
            if (!tryParse)
            {
                exc = new OverflowException(Locale.GetText("Value too large or too small."));
            }
            return(false);

IL_435:
            if (num3 == 0)
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            if (flag6 && !flag12)
            {
                int.FindSign(ref num, s, numberFormatInfo, ref flag12, ref flag11);
                if (flag12)
                {
                    if (flag8 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (flag)
                    {
                        int.FindCurrency(ref num, s, numberFormatInfo, ref flag13);
                    }
                }
            }
            if (flag && !flag13)
            {
                int.FindCurrency(ref num, s, numberFormatInfo, ref flag13);
                if (flag13)
                {
                    if (flag8 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (!flag12 && flag6)
                    {
                        int.FindSign(ref num, s, numberFormatInfo, ref flag12, ref flag11);
                    }
                }
            }
            if (flag8 && num < s.Length && !int.JumpOverWhite(ref num, s, false, tryParse, ref exc))
            {
                return(false);
            }
            if (flag10)
            {
                if (num >= s.Length || s[num++] != ')')
                {
                    if (!tryParse)
                    {
                        exc = int.GetFormatException();
                    }
                    return(false);
                }
                if (flag8 && num < s.Length && !int.JumpOverWhite(ref num, s, false, tryParse, ref exc))
                {
                    return(false);
                }
            }
            if (num < s.Length && s[num] != '\0')
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            if (flag11 && num2 > 0u)
            {
                if (!tryParse)
                {
                    exc = new OverflowException(Locale.GetText("Negative number"));
                }
                return(false);
            }
            result = num2;
            return(true);
        }
Example #19
0
        internal static bool Parse(string s, bool tryParse, out uint result, out Exception exc)
        {
            uint num   = 0u;
            bool flag  = false;
            bool flag2 = false;

            result = 0u;
            exc    = null;
            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }
            int length = s.Length;
            int i;

            for (i = 0; i < length; i++)
            {
                char c = s[i];
                if (!char.IsWhiteSpace(c))
                {
                    break;
                }
            }
            if (i == length)
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            if (s[i] == '+')
            {
                i++;
            }
            else if (s[i] == '-')
            {
                i++;
                flag2 = true;
            }
            while (i < length)
            {
                char c = s[i];
                if (c >= '0' && c <= '9')
                {
                    uint num2 = (uint)(c - '0');
                    if (num > 429496729u || (num == 429496729u && num2 > 5u))
                    {
                        if (!tryParse)
                        {
                            exc = new OverflowException(Locale.GetText("Value is too large"));
                        }
                        return(false);
                    }
                    num  = num * 10u + num2;
                    flag = true;
                }
                else if (!int.ProcessTrailingWhitespace(tryParse, s, i, ref exc))
                {
                    return(false);
                }
                i++;
            }
            if (!flag)
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            if (flag2 && num > 0u)
            {
                if (!tryParse)
                {
                    exc = new OverflowException(Locale.GetText("Negative number"));
                }
                return(false);
            }
            result = num;
            return(true);
        }
Example #20
0
        internal unsafe static bool Parse(string s, NumberStyles style, IFormatProvider provider, bool tryParse, out double result, out Exception exc)
        {
            result = 0.0;
            exc    = null;
            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }
            if (s.Length == 0)
            {
                if (!tryParse)
                {
                    exc = new FormatException();
                }
                return(false);
            }
            if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
            {
                string text = Locale.GetText("Double doesn't support parsing with '{0}'.", new object[]
                {
                    "AllowHexSpecifier"
                });
                throw new ArgumentException(text);
            }
            if (style > NumberStyles.Any)
            {
                if (!tryParse)
                {
                    exc = new ArgumentException();
                }
                return(false);
            }
            NumberFormatInfo instance = NumberFormatInfo.GetInstance(provider);

            if (instance == null)
            {
                throw new Exception("How did this happen?");
            }
            int  length = s.Length;
            int  num    = 0;
            int  i      = 0;
            bool flag   = (style & NumberStyles.AllowLeadingWhite) != NumberStyles.None;
            bool flag2  = (style & NumberStyles.AllowTrailingWhite) != NumberStyles.None;

            if (flag)
            {
                while (i < length && char.IsWhiteSpace(s[i]))
                {
                    i++;
                }
                if (i == length)
                {
                    if (!tryParse)
                    {
                        exc = int.GetFormatException();
                    }
                    return(false);
                }
            }
            int num2 = s.Length - 1;

            if (flag2)
            {
                while (char.IsWhiteSpace(s[num2]))
                {
                    num2--;
                }
            }
            if (double.TryParseStringConstant(instance.NaNSymbol, s, i, num2))
            {
                result = double.NaN;
                return(true);
            }
            if (double.TryParseStringConstant(instance.PositiveInfinitySymbol, s, i, num2))
            {
                result = double.PositiveInfinity;
                return(true);
            }
            if (double.TryParseStringConstant(instance.NegativeInfinitySymbol, s, i, num2))
            {
                result = double.NegativeInfinity;
                return(true);
            }
            byte[] array = new byte[length + 1];
            int    num3  = 1;
            string text2 = null;
            string text3 = null;
            string text4 = null;
            int    num4  = 0;
            int    num5  = 0;
            int    num6  = 0;

            if ((style & NumberStyles.AllowDecimalPoint) != NumberStyles.None)
            {
                text2 = instance.NumberDecimalSeparator;
                num4  = text2.Length;
            }
            if ((style & NumberStyles.AllowThousands) != NumberStyles.None)
            {
                text3 = instance.NumberGroupSeparator;
                num5  = text3.Length;
            }
            if ((style & NumberStyles.AllowCurrencySymbol) != NumberStyles.None)
            {
                text4 = instance.CurrencySymbol;
                num6  = text4.Length;
            }
            string positiveSign = instance.PositiveSign;
            string negativeSign = instance.NegativeSign;

            while (i < length)
            {
                char c = s[i];
                if (c == '\0')
                {
                    i = length;
                }
                else
                {
                    switch (num3)
                    {
                    case 1:
                        if ((style & NumberStyles.AllowLeadingSign) != NumberStyles.None)
                        {
                            if (c == positiveSign[0] && s.Substring(i, positiveSign.Length) == positiveSign)
                            {
                                num3 = 2;
                                i   += positiveSign.Length - 1;
                                goto IL_624;
                            }
                            if (c == negativeSign[0] && s.Substring(i, negativeSign.Length) == negativeSign)
                            {
                                num3         = 2;
                                array[num++] = 45;
                                i           += negativeSign.Length - 1;
                                goto IL_624;
                            }
                        }
                        num3 = 2;
                        goto IL_304;

                    case 2:
                        goto IL_304;

                    case 3:
                        goto IL_429;

                    case 4:
                        if (char.IsDigit(c))
                        {
                            num3 = 5;
                            goto IL_599;
                        }
                        if (c == positiveSign[0] && s.Substring(i, positiveSign.Length) == positiveSign)
                        {
                            num3 = 2;
                            i   += positiveSign.Length - 1;
                            goto IL_624;
                        }
                        if (c == negativeSign[0] && s.Substring(i, negativeSign.Length) == negativeSign)
                        {
                            num3         = 2;
                            array[num++] = 45;
                            i           += negativeSign.Length - 1;
                            goto IL_624;
                        }
                        if (char.IsWhiteSpace(c))
                        {
                            goto IL_5E7;
                        }
                        if (!tryParse)
                        {
                            exc = new FormatException("Unknown char: " + c);
                        }
                        return(false);

                    case 5:
                        goto IL_599;

                    case 6:
                        goto IL_5E7;
                    }
IL_617:
                    if (num3 == 7)
                    {
                        break;
                    }
                    goto IL_624;
IL_429:
                    if (char.IsDigit(c))
                    {
                        array[num++] = (byte)c;
                        goto IL_617;
                    }
                    if (c == 'e' || c == 'E')
                    {
                        if ((style & NumberStyles.AllowExponent) == NumberStyles.None)
                        {
                            if (!tryParse)
                            {
                                exc = new FormatException("Unknown char: " + c);
                            }
                            return(false);
                        }
                        array[num++] = (byte)c;
                        num3         = 4;
                        goto IL_617;
                    }
                    else
                    {
                        if (char.IsWhiteSpace(c))
                        {
                            goto IL_5E7;
                        }
                        if (!tryParse)
                        {
                            exc = new FormatException("Unknown char: " + c);
                        }
                        return(false);
                    }
IL_304:
                    if (char.IsDigit(c))
                    {
                        array[num++] = (byte)c;
                        goto IL_617;
                    }
                    if (c == 'e' || c == 'E')
                    {
                        goto IL_429;
                    }
                    if (num4 > 0 && text2[0] == c && string.CompareOrdinal(s, i, text2, 0, num4) == 0)
                    {
                        array[num++] = 46;
                        i           += num4 - 1;
                        num3         = 3;
                        goto IL_617;
                    }
                    if (num5 > 0 && text3[0] == c && s.Substring(i, num5) == text3)
                    {
                        i   += num5 - 1;
                        num3 = 2;
                        goto IL_617;
                    }
                    if (num6 > 0 && text4[0] == c && s.Substring(i, num6) == text4)
                    {
                        i   += num6 - 1;
                        num3 = 2;
                        goto IL_617;
                    }
                    if (char.IsWhiteSpace(c))
                    {
                        goto IL_5E7;
                    }
                    if (!tryParse)
                    {
                        exc = new FormatException("Unknown char: " + c);
                    }
                    return(false);

IL_599:
                    if (char.IsDigit(c))
                    {
                        array[num++] = (byte)c;
                        goto IL_617;
                    }
                    if (!char.IsWhiteSpace(c))
                    {
                        if (!tryParse)
                        {
                            exc = new FormatException("Unknown char: " + c);
                        }
                        return(false);
                    }
IL_5E7:
                    if (flag2 && char.IsWhiteSpace(c))
                    {
                        num3 = 6;
                        goto IL_617;
                    }
                    if (!tryParse)
                    {
                        exc = new FormatException("Unknown char");
                    }
                    return(false);
                }
IL_624:
                i++;
            }
            array[num] = 0;
            double num7;

            if (!double.ParseImpl(&array[0], out num7))
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            if (double.IsPositiveInfinity(num7) || double.IsNegativeInfinity(num7))
            {
                if (!tryParse)
                {
                    exc = new OverflowException();
                }
                return(false);
            }
            result = num7;
            return(true);
        }
Example #21
0
        internal static bool Parse(string s, NumberStyles style, IFormatProvider fp, bool tryParse, out int result, out Exception exc)
        {
            result = 0;
            exc    = null;
            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException();
                }
                return(false);
            }
            if (s.Length == 0)
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            NumberFormatInfo numberFormatInfo = null;

            if (fp != null)
            {
                Type typeFromHandle = typeof(NumberFormatInfo);
                numberFormatInfo = (NumberFormatInfo)fp.GetFormat(typeFromHandle);
            }
            if (numberFormatInfo == null)
            {
                numberFormatInfo = Thread.CurrentThread.CurrentCulture.NumberFormat;
            }
            if (!int.CheckStyle(style, tryParse, ref exc))
            {
                return(false);
            }
            bool flag   = (style & NumberStyles.AllowCurrencySymbol) != NumberStyles.None;
            bool flag2  = (style & NumberStyles.AllowHexSpecifier) != NumberStyles.None;
            bool flag3  = (style & NumberStyles.AllowThousands) != NumberStyles.None;
            bool flag4  = (style & NumberStyles.AllowDecimalPoint) != NumberStyles.None;
            bool flag5  = (style & NumberStyles.AllowParentheses) != NumberStyles.None;
            bool flag6  = (style & NumberStyles.AllowTrailingSign) != NumberStyles.None;
            bool flag7  = (style & NumberStyles.AllowLeadingSign) != NumberStyles.None;
            bool flag8  = (style & NumberStyles.AllowTrailingWhite) != NumberStyles.None;
            bool flag9  = (style & NumberStyles.AllowLeadingWhite) != NumberStyles.None;
            bool flag10 = (style & NumberStyles.AllowExponent) != NumberStyles.None;
            int  num    = 0;

            if (flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
            {
                return(false);
            }
            bool flag11 = false;
            bool flag12 = false;
            bool flag13 = false;
            bool flag14 = false;

            if (flag5 && s[num] == '(')
            {
                flag11 = true;
                flag13 = true;
                flag12 = true;
                num++;
                if (flag9 && int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                {
                    return(false);
                }
                if (s.Substring(num, numberFormatInfo.NegativeSign.Length) == numberFormatInfo.NegativeSign)
                {
                    if (!tryParse)
                    {
                        exc = int.GetFormatException();
                    }
                    return(false);
                }
                if (s.Substring(num, numberFormatInfo.PositiveSign.Length) == numberFormatInfo.PositiveSign)
                {
                    if (!tryParse)
                    {
                        exc = int.GetFormatException();
                    }
                    return(false);
                }
            }
            if (flag7 && !flag13)
            {
                int.FindSign(ref num, s, numberFormatInfo, ref flag13, ref flag12);
                if (flag13)
                {
                    if (flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (flag)
                    {
                        int.FindCurrency(ref num, s, numberFormatInfo, ref flag14);
                        if (flag14 && flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                        {
                            return(false);
                        }
                    }
                }
            }
            if (flag && !flag14)
            {
                int.FindCurrency(ref num, s, numberFormatInfo, ref flag14);
                if (flag14)
                {
                    if (flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (flag14 && !flag13 && flag7)
                    {
                        int.FindSign(ref num, s, numberFormatInfo, ref flag13, ref flag12);
                        if (flag13 && flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                        {
                            return(false);
                        }
                    }
                }
            }
            int  num2   = 0;
            int  num3   = 0;
            bool flag15 = false;
            int  num4   = 0;

            do
            {
                if (!int.ValidDigit(s[num], flag2))
                {
                    if (!flag3 || !int.FindOther(ref num, s, numberFormatInfo.NumberGroupSeparator))
                    {
                        if (flag15 || !flag4 || !int.FindOther(ref num, s, numberFormatInfo.NumberDecimalSeparator))
                        {
                            break;
                        }
                        flag15 = true;
                    }
                }
                else if (flag2)
                {
                    num3++;
                    char c = s[num++];
                    int  num5;
                    if (char.IsDigit(c))
                    {
                        num5 = (int)(c - '0');
                    }
                    else if (char.IsLower(c))
                    {
                        num5 = (int)(c - 'a' + '\n');
                    }
                    else
                    {
                        num5 = (int)(c - 'A' + '\n');
                    }
                    uint num6 = (uint)num2;
                    if (tryParse)
                    {
                        if ((num6 & 4026531840u) != 0u)
                        {
                            return(false);
                        }
                        num2 = (int)(num6 * 16u + (uint)num5);
                    }
                    else
                    {
                        num2 = (int)(checked (num6 * 16u + (uint)num5));
                    }
                }
                else if (flag15)
                {
                    num3++;
                    if (s[num++] != '0')
                    {
                        goto Block_50;
                    }
                }
                else
                {
                    num3++;
                    try
                    {
                        num2 = checked (num2 * 10 - (int)(s[num++] - '0'));
                    }
                    catch (OverflowException)
                    {
                        if (!tryParse)
                        {
                            exc = new OverflowException("Value too large or too small.");
                        }
                        return(false);
                    }
                }
            }while (num < s.Length);
            goto IL_43A;
Block_50:
            if (!tryParse)
            {
                exc = new OverflowException("Value too large or too small.");
            }
            return(false);

IL_43A:
            if (num3 == 0)
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            if (flag10 && int.FindExponent(ref num, s, ref num4, tryParse, ref exc) && exc != null)
            {
                return(false);
            }
            if (flag6 && !flag13)
            {
                int.FindSign(ref num, s, numberFormatInfo, ref flag13, ref flag12);
                if (flag13)
                {
                    if (flag8 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (flag)
                    {
                        int.FindCurrency(ref num, s, numberFormatInfo, ref flag14);
                    }
                }
            }
            if (flag && !flag14)
            {
                int.FindCurrency(ref num, s, numberFormatInfo, ref flag14);
                if (flag14)
                {
                    if (flag8 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (!flag13 && flag6)
                    {
                        int.FindSign(ref num, s, numberFormatInfo, ref flag13, ref flag12);
                    }
                }
            }
            if (flag8 && num < s.Length && !int.JumpOverWhite(ref num, s, false, tryParse, ref exc))
            {
                return(false);
            }
            if (flag11)
            {
                if (num >= s.Length || s[num++] != ')')
                {
                    if (!tryParse)
                    {
                        exc = int.GetFormatException();
                    }
                    return(false);
                }
                if (flag8 && num < s.Length && !int.JumpOverWhite(ref num, s, false, tryParse, ref exc))
                {
                    return(false);
                }
            }
            if (num < s.Length && s[num] != '\0')
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            if (!flag12 && !flag2)
            {
                if (tryParse)
                {
                    long num7 = -(long)num2;
                    if (num7 < -2147483648L || num7 > 2147483647L)
                    {
                        return(false);
                    }
                    num2 = (int)num7;
                }
                else
                {
                    num2 = checked (0 - num2);
                }
            }
            if (num4 > 0)
            {
                double num8 = Math.Pow(10.0, (double)num4) * (double)num2;
                if (num8 < -2147483648.0 || num8 > 2147483647.0)
                {
                    if (!tryParse)
                    {
                        exc = new OverflowException("Value too large or too small.");
                    }
                    return(false);
                }
                num2 = (int)num8;
            }
            result = num2;
            return(true);
        }
Example #22
0
        internal static bool Parse(string s, NumberStyles style, IFormatProvider provider, bool tryParse, out uint result, out Exception exc)
        {
            result = 0;
            exc    = null;

            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }

            if (s.Length == 0)
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            NumberFormatInfo nfi = null;

            if (provider != null)
            {
                Type typeNFI = typeof(NumberFormatInfo);
                nfi = (NumberFormatInfo)provider.GetFormat(typeNFI);
            }
            if (nfi == null)
            {
                nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
            }

            if (!Int32.CheckStyle(style, tryParse, ref exc))
            {
                return(false);
            }

            bool AllowCurrencySymbol = (style & NumberStyles.AllowCurrencySymbol) != 0;
            bool AllowHexSpecifier   = (style & NumberStyles.AllowHexSpecifier) != 0;
            bool AllowThousands      = (style & NumberStyles.AllowThousands) != 0;
            bool AllowDecimalPoint   = (style & NumberStyles.AllowDecimalPoint) != 0;
            bool AllowParentheses    = (style & NumberStyles.AllowParentheses) != 0;
            bool AllowTrailingSign   = (style & NumberStyles.AllowTrailingSign) != 0;
            bool AllowLeadingSign    = (style & NumberStyles.AllowLeadingSign) != 0;
            bool AllowTrailingWhite  = (style & NumberStyles.AllowTrailingWhite) != 0;
            bool AllowLeadingWhite   = (style & NumberStyles.AllowLeadingWhite) != 0;

            int pos = 0;

            if (AllowLeadingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
            {
                return(false);
            }

            bool foundOpenParentheses = false;
            bool negative             = false;
            bool foundSign            = false;
            bool foundCurrency        = false;

            // Pre-number stuff
            if (AllowParentheses && s [pos] == '(')
            {
                foundOpenParentheses = true;
                foundSign            = true;
                negative             = true;     // MS always make the number negative when there parentheses
                                                 // even when NumberFormatInfo.NumberNegativePattern != 0!!!
                pos++;
                if (AllowLeadingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                {
                    return(false);
                }

                if (s.Substring(pos, nfi.NegativeSign.Length) == nfi.NegativeSign)
                {
                    if (!tryParse)
                    {
                        exc = Int32.GetFormatException();
                    }
                    return(false);
                }
                if (s.Substring(pos, nfi.PositiveSign.Length) == nfi.PositiveSign)
                {
                    if (!tryParse)
                    {
                        exc = Int32.GetFormatException();
                    }
                    return(false);
                }
            }

            if (AllowLeadingSign && !foundSign)
            {
                // Sign + Currency
                Int32.FindSign(ref pos, s, nfi, ref foundSign, ref negative);
                if (foundSign)
                {
                    if (AllowLeadingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (AllowCurrencySymbol)
                    {
                        Int32.FindCurrency(ref pos, s, nfi, ref foundCurrency);
                        if (foundCurrency && AllowLeadingWhite &&
                            !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                        {
                            return(false);
                        }
                    }
                }
            }

            if (AllowCurrencySymbol && !foundCurrency)
            {
                // Currency + sign
                Int32.FindCurrency(ref pos, s, nfi, ref foundCurrency);
                if (foundCurrency)
                {
                    if (AllowLeadingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (foundCurrency)
                    {
                        if (!foundSign && AllowLeadingSign)
                        {
                            Int32.FindSign(ref pos, s, nfi, ref foundSign, ref negative);
                            if (foundSign && AllowLeadingWhite &&
                                !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                            {
                                return(false);
                            }
                        }
                    }
                }
            }

            uint number            = 0;
            int  nDigits           = 0;
            bool decimalPointFound = false;
            uint digitValue;
            char hexDigit;

            // Number stuff
            // Just the same as Int32, but this one adds instead of substract
            do
            {
                if (!Int32.ValidDigit(s [pos], AllowHexSpecifier))
                {
                    if (AllowThousands && Int32.FindOther(ref pos, s, nfi.NumberGroupSeparator))
                    {
                        continue;
                    }
                    else
                    if (!decimalPointFound && AllowDecimalPoint &&
                        Int32.FindOther(ref pos, s, nfi.NumberDecimalSeparator))
                    {
                        decimalPointFound = true;
                        continue;
                    }
                    break;
                }
                else if (AllowHexSpecifier)
                {
                    nDigits++;
                    hexDigit = s [pos++];
                    if (Char.IsDigit(hexDigit))
                    {
                        digitValue = (uint)(hexDigit - '0');
                    }
                    else if (Char.IsLower(hexDigit))
                    {
                        digitValue = (uint)(hexDigit - 'a' + 10);
                    }
                    else
                    {
                        digitValue = (uint)(hexDigit - 'A' + 10);
                    }

                    if (tryParse)
                    {
                        ulong l = number * 16 + digitValue;

                        if (l > MaxValue)
                        {
                            return(false);
                        }
                        number = (uint)l;
                    }
                    else
                    {
                        number = checked (number * 16 + digitValue);
                    }
                }
                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(Locale.GetText("Value too large or too small."));
                        }
                        return(false);
                    }
                }
                else
                {
                    nDigits++;

                    try {
                        number = checked (number * 10 + (uint)(s [pos++] - '0'));
                    }
                    catch (OverflowException) {
                        if (!tryParse)
                        {
                            exc = new OverflowException(Locale.GetText("Value too large or too small."));
                        }
                        return(false);
                    }
                }
            } while (pos < s.Length);

            // Post number stuff
            if (nDigits == 0)
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            if (AllowTrailingSign && !foundSign)
            {
                // Sign + Currency
                Int32.FindSign(ref pos, s, nfi, ref foundSign, ref negative);
                if (foundSign)
                {
                    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)
            {
                // Currency + sign
                Int32.FindCurrency(ref pos, s, nfi, ref foundCurrency);
                if (foundCurrency)
                {
                    if (AllowTrailingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (!foundSign && AllowTrailingSign)
                    {
                        Int32.FindSign(ref pos, s, nfi, ref foundSign, ref negative);
                    }
                }
            }

            if (AllowTrailingWhite && pos < s.Length && !Int32.JumpOverWhite(ref pos, s, false, tryParse, ref exc))
            {
                return(false);
            }

            if (foundOpenParentheses)
            {
                if (pos >= s.Length || s [pos++] != ')')
                {
                    if (!tryParse)
                    {
                        exc = Int32.GetFormatException();
                    }
                    return(false);
                }
                if (AllowTrailingWhite && pos < s.Length && !Int32.JumpOverWhite(ref pos, s, false, tryParse, ref exc))
                {
                    return(false);
                }
            }

            if (pos < s.Length && s [pos] != '\u0000')
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            // -0 is legal but other negative values are not
            if (negative && (number > 0))
            {
                if (!tryParse)
                {
                    exc = new OverflowException(
                        Locale.GetText("Negative number"));
                }
                return(false);
            }

            result = number;

            return(true);
        }
Example #23
0
File: Int32.cs Project: mdae/MonoRT
        internal static bool Parse(string s, NumberStyles style, IFormatProvider fp, bool tryParse, out int result, out Exception exc)
        {
            result = 0;
            exc    = null;

            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException();
                }
                return(false);
            }

            if (s.Length == 0)
            {
                if (!tryParse)
                {
                    exc = GetFormatException();
                }
                return(false);
            }

            NumberFormatInfo nfi = null;

            if (fp != null)
            {
                Type typeNFI = typeof(System.Globalization.NumberFormatInfo);
                nfi = (NumberFormatInfo)fp.GetFormat(typeNFI);
            }
            if (nfi == null)
            {
                nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
            }

            if (!CheckStyle(style, tryParse, ref exc))
            {
                return(false);
            }

            bool AllowCurrencySymbol = (style & NumberStyles.AllowCurrencySymbol) != 0;
            bool AllowHexSpecifier   = (style & NumberStyles.AllowHexSpecifier) != 0;
            bool AllowThousands      = (style & NumberStyles.AllowThousands) != 0;
            bool AllowDecimalPoint   = (style & NumberStyles.AllowDecimalPoint) != 0;
            bool AllowParentheses    = (style & NumberStyles.AllowParentheses) != 0;
            bool AllowTrailingSign   = (style & NumberStyles.AllowTrailingSign) != 0;
            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;

            if (AllowLeadingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc))
            {
                return(false);
            }

            bool foundOpenParentheses = false;
            bool negative             = false;
            bool foundSign            = false;
            bool foundCurrency        = false;

            // Pre-number stuff
            if (AllowParentheses && s [pos] == '(')
            {
                foundOpenParentheses = true;
                foundSign            = true;
                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))
                {
                    return(false);
                }

                if (s.Substring(pos, nfi.NegativeSign.Length) == nfi.NegativeSign)
                {
                    if (!tryParse)
                    {
                        exc = GetFormatException();
                    }
                    return(false);
                }

                if (s.Substring(pos, nfi.PositiveSign.Length) == nfi.PositiveSign)
                {
                    if (!tryParse)
                    {
                        exc = GetFormatException();
                    }
                    return(false);
                }
            }

            if (AllowLeadingSign && !foundSign)
            {
                // Sign + Currency
                FindSign(ref pos, s, nfi, ref foundSign, ref negative);
                if (foundSign)
                {
                    if (AllowLeadingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (AllowCurrencySymbol)
                    {
                        FindCurrency(ref pos, s, nfi,
                                     ref foundCurrency);
                        if (foundCurrency && AllowLeadingWhite &&
                            !JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                        {
                            return(false);
                        }
                    }
                }
            }

            if (AllowCurrencySymbol && !foundCurrency)
            {
                // Currency + sign
                FindCurrency(ref pos, s, nfi, ref foundCurrency);
                if (foundCurrency)
                {
                    if (AllowLeadingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (foundCurrency)
                    {
                        if (!foundSign && AllowLeadingSign)
                        {
                            FindSign(ref pos, s, nfi, ref foundSign,
                                     ref negative);
                            if (foundSign && AllowLeadingWhite &&
                                !JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                            {
                                return(false);
                            }
                        }
                    }
                }
            }

            int  number            = 0;
            int  nDigits           = 0;
            bool decimalPointFound = false;
            int  digitValue;
            char hexDigit;

            // Number stuff
            do
            {
                if (!ValidDigit(s [pos], AllowHexSpecifier))
                {
                    if (AllowThousands &&
                        FindOther(ref pos, s, nfi.NumberGroupSeparator))
                    {
                        continue;
                    }
                    else
                    if (!decimalPointFound && AllowDecimalPoint &&
                        FindOther(ref pos, s, nfi.NumberDecimalSeparator))
                    {
                        decimalPointFound = true;
                        continue;
                    }

                    break;
                }
                else if (AllowHexSpecifier)
                {
                    nDigits++;
                    hexDigit = s [pos++];
                    if (Char.IsDigit(hexDigit))
                    {
                        digitValue = (int)(hexDigit - '0');
                    }
                    else if (Char.IsLower(hexDigit))
                    {
                        digitValue = (int)(hexDigit - 'a' + 10);
                    }
                    else
                    {
                        digitValue = (int)(hexDigit - 'A' + 10);
                    }

                    uint unumber = (uint)number;
                    if (tryParse)
                    {
                        if ((unumber & 0xf0000000) != 0)
                        {
                            return(false);
                        }

                        number = (int)(unumber * 16u + (uint)digitValue);
                    }
                    else
                    {
                        number = (int)checked (unumber * 16u + (uint)digitValue);
                    }
                }
                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);
                    }
                }
            } while (pos < s.Length);

            // Post number stuff
            if (nDigits == 0)
            {
                if (!tryParse)
                {
                    exc = GetFormatException();
                }
                return(false);
            }

            if (AllowExponent)
            {
                FindExponent(ref pos, s);
            }

            if (AllowTrailingSign && !foundSign)
            {
                // Sign + Currency
                FindSign(ref pos, s, nfi, ref foundSign, ref negative);
                if (foundSign)
                {
                    if (AllowTrailingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (AllowCurrencySymbol)
                    {
                        FindCurrency(ref pos, s, nfi,
                                     ref foundCurrency);
                    }
                }
            }

            if (AllowCurrencySymbol && !foundCurrency)
            {
                // Currency + sign
                FindCurrency(ref pos, s, nfi, ref foundCurrency);
                if (foundCurrency)
                {
                    if (AllowTrailingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (!foundSign && AllowTrailingSign)
                    {
                        FindSign(ref pos, s, nfi, ref foundSign,
                                 ref negative);
                    }
                }
            }

            if (AllowTrailingWhite && pos < s.Length && !JumpOverWhite(ref pos, s, false, tryParse, ref exc))
            {
                return(false);
            }

            if (foundOpenParentheses)
            {
                if (pos >= s.Length || s [pos++] != ')')
                {
                    if (!tryParse)
                    {
                        exc = GetFormatException();
                    }
                    return(false);
                }
                if (AllowTrailingWhite && pos < s.Length &&
                    !JumpOverWhite(ref pos, s, false, tryParse, ref exc))
                {
                    return(false);
                }
            }

            if (pos < s.Length && s [pos] != '\u0000')
            {
                if (!tryParse)
                {
                    exc = GetFormatException();
                }
                return(false);
            }

            if (!negative && !AllowHexSpecifier)
            {
                if (tryParse)
                {
                    long lval = -number;

                    if (lval < MinValue || lval > MaxValue)
                    {
                        return(false);
                    }
                    number = (int)lval;
                }
                else
                {
                    number = checked (-number);
                }
            }

            result = number;

            return(true);
        }
Example #24
0
        internal Exception TryToTimeSpan(DurationType durationType, out TimeSpan result)
        {
            Exception exception = null;
            ulong ticks = 0;
            try
            {
                checked
                {
                    if (durationType != DurationType.DayTimeDuration)
                    {
                        ticks += ((ulong)this.years + ((ulong)this.months / 12)) * 365;
                        ticks += ((ulong)this.months % 12) * 30;
                    }

                    if (durationType != DurationType.YearMonthDuration)
                    {
                        ticks += (ulong)this.days;
                        ticks *= 24;
                        ticks += (ulong)this.hours;
                        ticks *= 60;
                        ticks += (ulong)this.minutes;
                        ticks *= 60;
                        ticks += (ulong)this.seconds;
                        ticks *= (ulong)TimeSpan.TicksPerSecond;
                        ticks += (ulong)Nanoseconds / 100;
                    }
                    else
                    {
                        ticks *= (ulong)TimeSpan.TicksPerDay;
                    }

                    if (IsNegative)
                    {
                        if (ticks == (ulong)Int64.MaxValue + 1)
                        {
                            result = new TimeSpan(Int64.MinValue);
                        }
                        else
                        {
                            result = new TimeSpan(-((long)ticks));
                        }
                    }
                    else
                    {
                        result = new TimeSpan((long)ticks);
                    }

                    return null;
                }
            }
            catch (OverflowException)
            {
                result = TimeSpan.MinValue;
                exception = new OverflowException();
            }

            return exception;
        }
Example #25
0
        internal static bool Parse(string s, bool tryParse, out long result, out Exception exc)
        {
            long val = 0;
            int  len;
            int  i, sign = 1;
            bool digits_seen = false;

            result = 0;
            exc    = null;
            NumberFormatInfo nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;

            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }

            len = s.Length;

            char c;

            for (i = 0; i < len; i++)
            {
                c = s [i];
                if (!Char.IsWhiteSpace(c))
                {
                    break;
                }
            }

            if (i == len)
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            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   += nfi.NegativeSign.Length;
            }

            for (; i < len; i++)
            {
                c = s [i];

                if (c >= '0' && c <= '9')
                {
                    byte d = (byte)(c - '0');

                    if (val > (MaxValue / 10))
                    {
                        goto overflow;
                    }

                    if (val == (MaxValue / 10))
                    {
                        if ((d > (MaxValue % 10)) && (sign == 1 || (d > ((MaxValue % 10) + 1))))
                        {
                            goto overflow;
                        }
                        if (sign == -1)
                        {
                            val = (val * sign * 10) - d;
                        }
                        else
                        {
                            val = (val * 10) + d;
                        }

                        if (Int32.ProcessTrailingWhitespace(tryParse, s, i + 1, ref exc))
                        {
                            result = val;
                            return(true);
                        }
                        goto overflow;
                    }
                    else
                    {
                        val = val * 10 + d;
                    }

                    digits_seen = true;
                }
                else if (!Int32.ProcessTrailingWhitespace(tryParse, s, i, ref exc))
                {
                    return(false);
                }
            }
            if (!digits_seen)
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            if (sign == -1)
            {
                result = val * sign;
            }
            else
            {
                result = val;
            }

            return(true);

overflow:
            if (!tryParse)
            {
                exc = new OverflowException("Value is too large");
            }
            return(false);
        }
Example #26
0
        // FIXME: check if digits are group in correct numbers between the group separators
        internal static bool Parse(string s, NumberStyles style, IFormatProvider provider, bool tryParse, out double result, out Exception exc)
        {
            result = 0;
            exc    = null;

            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }
            if (s.Length == 0)
            {
                if (!tryParse)
                {
                    exc = new FormatException();
                }
                return(false);
            }
            // yes it's counter intuitive (buggy?) but even TryParse actually throws in this case
            if ((style & NumberStyles.AllowHexSpecifier) != 0)
            {
                string msg = Locale.GetText("Double doesn't support parsing with '{0}'.", "AllowHexSpecifier");
                throw new ArgumentException(msg);
            }
            if (style > NumberStyles.Any)
            {
                if (!tryParse)
                {
                    exc = new ArgumentException();
                }
                return(false);
            }

            NumberFormatInfo format = NumberFormatInfo.GetInstance(provider);

            if (format == null)
            {
                throw new Exception("How did this happen?");
            }

            //
            // validate and prepare string for C
            //
            int  len  = s.Length;
            int  didx = 0;
            int  sidx = 0;
            char c;
            bool allow_leading_white  = (style & NumberStyles.AllowLeadingWhite) != 0;
            bool allow_trailing_white = ((style & NumberStyles.AllowTrailingWhite) != 0);

            if (allow_leading_white)
            {
                while (sidx < len && Char.IsWhiteSpace(s [sidx]))
                {
                    sidx++;
                }

                if (sidx == len)
                {
                    if (!tryParse)
                    {
                        exc = Int32.GetFormatException();
                    }
                    return(false);
                }
            }
            int sEndPos = s.Length - 1;

            if (allow_trailing_white)
            {
                while (Char.IsWhiteSpace(s [sEndPos]))
                {
                    sEndPos--;
                }
            }

            if (TryParseStringConstant(format.NaNSymbol, s, sidx, sEndPos))
            {
                result = double.NaN;
                return(true);
            }
            if (TryParseStringConstant(format.PositiveInfinitySymbol, s, sidx, sEndPos))
            {
                result = double.PositiveInfinity;
                return(true);
            }
            if (TryParseStringConstant(format.NegativeInfinitySymbol, s, sidx, sEndPos))
            {
                result = double.NegativeInfinity;
                return(true);
            }

            byte [] b = new byte [len + 1];

            //
            // Machine state
            //
            var state = ParseState.AllowSign;

            //
            // Setup
            //
            string decimal_separator     = null;
            string group_separator       = null;
            string currency_symbol       = null;
            int    decimal_separator_len = 0;
            int    group_separator_len   = 0;
            int    currency_symbol_len   = 0;

            if ((style & NumberStyles.AllowDecimalPoint) != 0)
            {
                decimal_separator     = format.NumberDecimalSeparator;
                decimal_separator_len = decimal_separator.Length;
            }
            if ((style & NumberStyles.AllowThousands) != 0)
            {
                group_separator     = format.NumberGroupSeparator;
                group_separator_len = group_separator.Length;
            }
            if ((style & NumberStyles.AllowCurrencySymbol) != 0)
            {
                currency_symbol     = format.CurrencySymbol;
                currency_symbol_len = currency_symbol.Length;
            }
            string positive = format.PositiveSign;
            string negative = format.NegativeSign;
            bool   allow_trailing_parenthes = false;

            for (; sidx < len; sidx++)
            {
                c = s [sidx];

                if (c == '\0')
                {
                    sidx = len;
                    continue;
                }

                switch (state)
                {
                case ParseState.AllowSign:
                    if ((style & NumberStyles.AllowLeadingSign) != 0)
                    {
                        if (c == positive [0] &&
                            s.Substring(sidx, positive.Length) == positive)
                        {
                            state = ParseState.Digits;
                            sidx += positive.Length - 1;
                            continue;
                        }

                        if (c == negative [0] &&
                            s.Substring(sidx, negative.Length) == negative)
                        {
                            state      = ParseState.Digits;
                            b [didx++] = (byte)'-';
                            sidx      += negative.Length - 1;
                            continue;
                        }
                    }

                    if ((style & NumberStyles.AllowParentheses) != 0 && c == '(')
                    {
                        b [didx++] = (byte)'-';
                        state      = ParseState.Digits;
                        allow_trailing_parenthes = true;
                        continue;
                    }

                    state = ParseState.Digits;
                    goto case ParseState.Digits;

                case ParseState.Digits:
                    if (Char.IsDigit(c))
                    {
                        b [didx++] = (byte)c;
                        break;
                    }

                    if (c == 'e' || c == 'E')
                    {
                        goto case ParseState.Decimal;
                    }

                    if (allow_trailing_parenthes && c == ')')
                    {
                        allow_trailing_parenthes = false;
                        state = ParseState.ConsumeWhiteSpace;
                        continue;
                    }

                    if (decimal_separator_len > 0 &&
                        decimal_separator [0] == c)
                    {
                        if (String.CompareOrdinal(s, sidx, decimal_separator, 0, decimal_separator_len) == 0)
                        {
                            b [didx++] = (byte)'.';
                            sidx      += decimal_separator_len - 1;
                            state      = ParseState.Decimal;
                            break;
                        }
                    }
                    if (group_separator_len > 0 &&
                        group_separator [0] == c)
                    {
                        if (s.Substring(sidx, group_separator_len) ==
                            group_separator)
                        {
                            sidx += group_separator_len - 1;
                            break;
                        }
                    }
                    if (currency_symbol_len > 0 &&
                        currency_symbol [0] == c)
                    {
                        if (s.Substring(sidx, currency_symbol_len) ==
                            currency_symbol)
                        {
                            sidx += currency_symbol_len - 1;
                            currency_symbol_len = 0;
                            break;
                        }
                    }

                    state = ParseState.TrailingSymbols;
                    goto case ParseState.TrailingSymbols;

                case ParseState.Decimal:
                    if (Char.IsDigit(c))
                    {
                        b [didx++] = (byte)c;
                        break;
                    }

                    if (c == 'e' || c == 'E')
                    {
                        if ((style & NumberStyles.AllowExponent) == 0)
                        {
                            if (!tryParse)
                            {
                                exc = new FormatException("Unknown char: " + c);
                            }
                            return(false);
                        }
                        b [didx++] = (byte)c;
                        state      = ParseState.ExponentSign;
                        break;
                    }

                    state = ParseState.TrailingSymbols;
                    goto case ParseState.TrailingSymbols;

                case ParseState.ExponentSign:
                    if (Char.IsDigit(c))
                    {
                        state = ParseState.Exponent;
                        goto case ParseState.Exponent;
                    }

                    if (c == positive [0] &&
                        s.Substring(sidx, positive.Length) == positive)
                    {
                        state = ParseState.Digits;
                        sidx += positive.Length - 1;
                        continue;
                    }

                    if (c == negative [0] &&
                        s.Substring(sidx, negative.Length) == negative)
                    {
                        state      = ParseState.Digits;
                        b [didx++] = (byte)'-';
                        sidx      += negative.Length - 1;
                        continue;
                    }

                    goto case ParseState.ConsumeWhiteSpace;

                case ParseState.Exponent:
                    if (Char.IsDigit(c))
                    {
                        b [didx++] = (byte)c;
                        break;
                    }

                    state = ParseState.TrailingSymbols;
                    goto case ParseState.TrailingSymbols;

                case ParseState.TrailingSymbols:
                    if ((style & NumberStyles.AllowTrailingSign) != 0)
                    {
                        if (positive != null && c == positive [0] &&
                            s.Substring(sidx, positive.Length) == positive)
                        {
                            state = ParseState.ConsumeWhiteSpace;
                            sidx += positive.Length - 1;
                            allow_trailing_parenthes = false;
                            positive = null;
                            continue;
                        }

                        if (negative != null && c == negative [0] &&
                            s.Substring(sidx, negative.Length) == negative)
                        {
                            state = ParseState.ConsumeWhiteSpace;
                            Array.Copy(b, 0, b, 1, didx);
                            b [0] = (byte)'-';
                            ++didx;
                            sidx += negative.Length - 1;
                            allow_trailing_parenthes = false;
                            negative = null;
                            continue;
                        }
                    }

                    if (currency_symbol_len > 0 &&
                        currency_symbol [0] == c)
                    {
                        if (s.Substring(sidx, currency_symbol_len) ==
                            currency_symbol)
                        {
                            sidx += currency_symbol_len - 1;
                            currency_symbol_len = 0;
                            break;
                        }
                    }

                    if (allow_trailing_white && Char.IsWhiteSpace(c))
                    {
                        break;
                    }

                    goto case ParseState.ConsumeWhiteSpace;

                case ParseState.ConsumeWhiteSpace:
                    if (allow_trailing_parenthes && c == ')')
                    {
                        allow_trailing_parenthes = false;
                        state = ParseState.ConsumeWhiteSpace;
                        break;
                    }

                    if (allow_trailing_white && Char.IsWhiteSpace(c))
                    {
                        state = ParseState.ConsumeWhiteSpace;
                        break;
                    }

                    if (!tryParse)
                    {
                        exc = new FormatException("Unknown char");
                    }
                    return(false);
                }

                if (state == ParseState.Exit)
                {
                    break;
                }
            }

            b [didx] = 0;
            unsafe
            {
                fixed(byte *p = &b[0])
                {
                    double retVal;

                    if (!ParseImpl(p, out retVal))
                    {
                        if (!tryParse)
                        {
                            exc = Int32.GetFormatException();
                        }
                        return(false);
                    }
                    if (IsPositiveInfinity(retVal) || IsNegativeInfinity(retVal))
                    {
                        if (!tryParse)
                        {
                            exc = new OverflowException();
                        }
                        return(false);
                    }

                    result = retVal;
                    return(true);
                }
            }
        }
Example #27
0
        internal static bool Parse(string s, NumberStyles style, IFormatProvider fp, bool tryParse, out long result, out Exception exc)
        {
            result = 0L;
            exc    = null;
            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }
            if (s.Length == 0)
            {
                if (!tryParse)
                {
                    exc = new FormatException("Input string was not in the correct format: s.Length==0.");
                }
                return(false);
            }
            NumberFormatInfo numberFormatInfo = null;

            if (fp != null)
            {
                Type typeFromHandle = typeof(NumberFormatInfo);
                numberFormatInfo = (NumberFormatInfo)fp.GetFormat(typeFromHandle);
            }
            if (numberFormatInfo == null)
            {
                numberFormatInfo = Thread.CurrentThread.CurrentCulture.NumberFormat;
            }
            if (!int.CheckStyle(style, tryParse, ref exc))
            {
                return(false);
            }
            bool flag  = (style & NumberStyles.AllowCurrencySymbol) != NumberStyles.None;
            bool flag2 = (style & NumberStyles.AllowHexSpecifier) != NumberStyles.None;
            bool flag3 = (style & NumberStyles.AllowThousands) != NumberStyles.None;
            bool flag4 = (style & NumberStyles.AllowDecimalPoint) != NumberStyles.None;
            bool flag5 = (style & NumberStyles.AllowParentheses) != NumberStyles.None;
            bool flag6 = (style & NumberStyles.AllowTrailingSign) != NumberStyles.None;
            bool flag7 = (style & NumberStyles.AllowLeadingSign) != NumberStyles.None;
            bool flag8 = (style & NumberStyles.AllowTrailingWhite) != NumberStyles.None;
            bool flag9 = (style & NumberStyles.AllowLeadingWhite) != NumberStyles.None;
            int  num   = 0;

            if (flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
            {
                return(false);
            }
            bool flag10 = false;
            bool flag11 = false;
            bool flag12 = false;
            bool flag13 = false;

            if (flag5 && s[num] == '(')
            {
                flag10 = true;
                flag12 = true;
                flag11 = true;
                num++;
                if (flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                {
                    return(false);
                }
                if (s.Substring(num, numberFormatInfo.NegativeSign.Length) == numberFormatInfo.NegativeSign)
                {
                    if (!tryParse)
                    {
                        exc = new FormatException("Input string was not in the correct format: Has Negative Sign.");
                    }
                    return(false);
                }
                if (s.Substring(num, numberFormatInfo.PositiveSign.Length) == numberFormatInfo.PositiveSign)
                {
                    if (!tryParse)
                    {
                        exc = new FormatException("Input string was not in the correct format: Has Positive Sign.");
                    }
                    return(false);
                }
            }
            if (flag7 && !flag12)
            {
                int.FindSign(ref num, s, numberFormatInfo, ref flag12, ref flag11);
                if (flag12)
                {
                    if (flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (flag)
                    {
                        int.FindCurrency(ref num, s, numberFormatInfo, ref flag13);
                        if (flag13 && flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                        {
                            return(false);
                        }
                    }
                }
            }
            if (flag && !flag13)
            {
                int.FindCurrency(ref num, s, numberFormatInfo, ref flag13);
                if (flag13)
                {
                    if (flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (flag13 && !flag12 && flag7)
                    {
                        int.FindSign(ref num, s, numberFormatInfo, ref flag12, ref flag11);
                        if (flag12 && flag9 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                        {
                            return(false);
                        }
                    }
                }
            }
            long num2   = 0L;
            int  num3   = 0;
            bool flag14 = false;

            do
            {
                if (!int.ValidDigit(s[num], flag2))
                {
                    if (!flag3 || (!int.FindOther(ref num, s, numberFormatInfo.NumberGroupSeparator) && !int.FindOther(ref num, s, numberFormatInfo.CurrencyGroupSeparator)))
                    {
                        if (flag14 || !flag4 || (!int.FindOther(ref num, s, numberFormatInfo.NumberDecimalSeparator) && !int.FindOther(ref num, s, numberFormatInfo.CurrencyDecimalSeparator)))
                        {
                            break;
                        }
                        flag14 = true;
                    }
                }
                else if (flag2)
                {
                    num3++;
                    char c = s[num++];
                    int  num4;
                    if (char.IsDigit(c))
                    {
                        num4 = (int)(c - '0');
                    }
                    else if (char.IsLower(c))
                    {
                        num4 = (int)(c - 'a' + '\n');
                    }
                    else
                    {
                        num4 = (int)(c - 'A' + '\n');
                    }
                    ulong num5 = (ulong)num2;
                    try
                    {
                        num2 = (long)(checked (num5 * 16UL + (ulong)num4));
                    }
                    catch (OverflowException ex)
                    {
                        if (!tryParse)
                        {
                            exc = ex;
                        }
                        return(false);
                    }
                }
                else if (flag14)
                {
                    num3++;
                    if (s[num++] != '0')
                    {
                        goto Block_49;
                    }
                }
                else
                {
                    num3++;
                    try
                    {
                        num2 = checked (num2 * 10L - unchecked ((long)(checked (s[num++] - '0'))));
                    }
                    catch (OverflowException)
                    {
                        if (!tryParse)
                        {
                            exc = new OverflowException("Value too large or too small.");
                        }
                        return(false);
                    }
                }
            }while (num < s.Length);
            goto IL_462;
Block_49:
            if (!tryParse)
            {
                exc = new OverflowException("Value too large or too small.");
            }
            return(false);

IL_462:
            if (num3 == 0)
            {
                if (!tryParse)
                {
                    exc = new FormatException("Input string was not in the correct format: nDigits == 0.");
                }
                return(false);
            }
            if (flag6 && !flag12)
            {
                int.FindSign(ref num, s, numberFormatInfo, ref flag12, ref flag11);
                if (flag12)
                {
                    if (flag8 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (flag)
                    {
                        int.FindCurrency(ref num, s, numberFormatInfo, ref flag13);
                    }
                }
            }
            if (flag && !flag13)
            {
                if (numberFormatInfo.CurrencyPositivePattern == 3 && s[num++] != ' ')
                {
                    if (tryParse)
                    {
                        return(false);
                    }
                    throw new FormatException("Input string was not in the correct format: no space between number and currency symbol.");
                }
                else
                {
                    int.FindCurrency(ref num, s, numberFormatInfo, ref flag13);
                    if (flag13 && num < s.Length)
                    {
                        if (flag8 && !int.JumpOverWhite(ref num, s, true, tryParse, ref exc))
                        {
                            return(false);
                        }
                        if (!flag12 && flag6)
                        {
                            int.FindSign(ref num, s, numberFormatInfo, ref flag12, ref flag11);
                        }
                    }
                }
            }
            if (flag8 && num < s.Length && !int.JumpOverWhite(ref num, s, false, tryParse, ref exc))
            {
                return(false);
            }
            if (flag10)
            {
                if (num >= s.Length || s[num++] != ')')
                {
                    if (!tryParse)
                    {
                        exc = new FormatException("Input string was not in the correct format: No room for close parens.");
                    }
                    return(false);
                }
                if (flag8 && num < s.Length && !int.JumpOverWhite(ref num, s, false, tryParse, ref exc))
                {
                    return(false);
                }
            }
            if (num < s.Length && s[num] != '\0')
            {
                if (!tryParse)
                {
                    exc = new FormatException(string.Concat(new object[]
                    {
                        "Input string was not in the correct format: Did not parse entire string. pos = ",
                        num,
                        " s.Length = ",
                        s.Length
                    }));
                }
                return(false);
            }
            if (!flag11 && !flag2)
            {
                try
                {
                    num2 = (long)(checked (unchecked ((ulong)0) - (ulong)num2));
                }
                catch (OverflowException ex2)
                {
                    if (!tryParse)
                    {
                        exc = ex2;
                    }
                    return(false);
                }
            }
            result = num2;
            return(true);
        }
Example #28
0
        internal static bool Parse(string s, bool tryParse, out int result, out Exception exc)
        {
            int  num  = 0;
            int  num2 = 1;
            bool flag = false;

            result = 0;
            exc    = null;
            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }
            int  length = s.Length;
            int  i;
            char c;

            for (i = 0; i < length; i++)
            {
                c = s[i];
                if (!char.IsWhiteSpace(c))
                {
                    break;
                }
            }
            if (i == length)
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            c = s[i];
            if (c == '+')
            {
                i++;
            }
            else if (c == '-')
            {
                num2 = -1;
                i++;
            }
            while (i < length)
            {
                c = s[i];
                if (c == '\0')
                {
                    i = length;
                }
                else
                {
                    if (c >= '0' && c <= '9')
                    {
                        byte b = (byte)(c - '0');
                        if (num <= 214748364)
                        {
                            if (num != 214748364)
                            {
                                num  = num * 10 + (int)b;
                                flag = true;
                                goto IL_15F;
                            }
                            if (b <= 7 || (num2 != 1 && b <= 8))
                            {
                                if (num2 == -1)
                                {
                                    num = num * num2 * 10 - (int)b;
                                }
                                else
                                {
                                    num = num * 10 + (int)b;
                                }
                                if (int.ProcessTrailingWhitespace(tryParse, s, i + 1, ref exc))
                                {
                                    result = num;
                                    return(true);
                                }
                            }
                        }
                        if (!tryParse)
                        {
                            exc = new OverflowException("Value is too large");
                        }
                        return(false);
                    }
                    if (!int.ProcessTrailingWhitespace(tryParse, s, i, ref exc))
                    {
                        return(false);
                    }
                }
IL_15F:
                i++;
            }
            if (!flag)
            {
                if (!tryParse)
                {
                    exc = int.GetFormatException();
                }
                return(false);
            }
            if (num2 == -1)
            {
                result = num * num2;
            }
            else
            {
                result = num;
            }
            return(true);
        }
 internal static OverflowException Overflow(string error, Exception inner)
 {
     OverflowException e = new OverflowException(error, inner);
     TraceExceptionAsReturnValue(e);
     return e;
 }
Example #30
0
File: Int32.cs Project: mdae/MonoRT
        internal static bool Parse(string s, bool tryParse, out int result, out Exception exc)
        {
            int  val = 0;
            int  len;
            int  i, sign = 1;
            bool digits_seen = false;

            result = 0;
            exc    = null;

            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }

            len = s.Length;

            char c;

            for (i = 0; i < len; i++)
            {
                c = s [i];
                if (!Char.IsWhiteSpace(c))
                {
                    break;
                }
            }

            if (i == len)
            {
                if (!tryParse)
                {
                    exc = GetFormatException();
                }
                return(false);
            }

            c = s [i];
            if (c == '+')
            {
                i++;
            }
            else if (c == '-')
            {
                sign = -1;
                i++;
            }

            for (; i < len; i++)
            {
                c = s [i];

                if (c == '\0')
                {
                    i = len;
                    continue;
                }

                if (c >= '0' && c <= '9')
                {
                    byte d = (byte)(c - '0');

                    if (val > (MaxValue / 10))
                    {
                        goto overflow;
                    }

                    if (val == (MaxValue / 10))
                    {
                        if ((d > (MaxValue % 10)) && (sign == 1 || (d > ((MaxValue % 10) + 1))))
                        {
                            goto overflow;
                        }
                        if (sign == -1)
                        {
                            val = (val * sign * 10) - d;
                        }
                        else
                        {
                            val = (val * 10) + d;
                        }

                        if (ProcessTrailingWhitespace(tryParse, s, i + 1, ref exc))
                        {
                            result = val;
                            return(true);
                        }
                        goto overflow;
                    }
                    else
                    {
                        val = val * 10 + d;
                    }

                    digits_seen = true;
                }
                else if (!ProcessTrailingWhitespace(tryParse, s, i, ref exc))
                {
                    return(false);
                }
            }
            if (!digits_seen)
            {
                if (!tryParse)
                {
                    exc = GetFormatException();
                }
                return(false);
            }

            if (sign == -1)
            {
                result = val * sign;
            }
            else
            {
                result = val;
            }

            return(true);

overflow:
            if (!tryParse)
            {
                exc = new OverflowException("Value is too large");
            }
            return(false);
        }
 internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner)
 {
     Exception exception;
     string message = System.Data.Res.GetString("ADP_ParameterConversionFailed", new object[] { value.GetType().Name, destType.Name });
     if (inner is ArgumentException)
     {
         exception = new ArgumentException(message, inner);
     }
     else if (inner is FormatException)
     {
         exception = new FormatException(message, inner);
     }
     else if (inner is InvalidCastException)
     {
         exception = new InvalidCastException(message, inner);
     }
     else if (inner is OverflowException)
     {
         exception = new OverflowException(message, inner);
     }
     else
     {
         exception = inner;
     }
     TraceExceptionAsReturnValue(exception);
     return exception;
 }
Example #32
0
	public static bool SetExplicitException(OverflowException e) {
	    return typeof(OverflowException).IsInstanceOfType(e);
	}
 static private OverflowException _Overflow(string error) {
     OverflowException e = new OverflowException(error);
     ExceptionBuilder.TraceExceptionAsReturnValue(e);
     return e;
 }
Example #34
0
        internal static bool Parse(string s, NumberStyles style, IFormatProvider fp, bool tryParse, out long result, out Exception exc)
        {
            result = 0;
            exc    = null;

            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }

            if (s.Length == 0)
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            NumberFormatInfo nfi = null;

            if (fp != null)
            {
                Type typeNFI = typeof(System.Globalization.NumberFormatInfo);
                nfi = (NumberFormatInfo)fp.GetFormat(typeNFI);
            }
            if (nfi == null)
            {
                nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
            }

            if (!Int32.CheckStyle(style, tryParse, ref exc))
            {
                return(false);
            }

            bool AllowCurrencySymbol = (style & NumberStyles.AllowCurrencySymbol) != 0;
            bool AllowHexSpecifier   = (style & NumberStyles.AllowHexSpecifier) != 0;
            bool AllowThousands      = (style & NumberStyles.AllowThousands) != 0;
            bool AllowDecimalPoint   = (style & NumberStyles.AllowDecimalPoint) != 0;
            bool AllowParentheses    = (style & NumberStyles.AllowParentheses) != 0;
            bool AllowTrailingSign   = (style & NumberStyles.AllowTrailingSign) != 0;
            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;

            if (AllowLeadingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
            {
                return(false);
            }

            bool foundOpenParentheses = false;
            bool negative             = false;
            bool foundSign            = false;
            bool foundCurrency        = false;

            // Pre-number stuff
            if (AllowParentheses && s [pos] == '(')
            {
                foundOpenParentheses = true;
                foundSign            = true;
                negative             = true;     // MS always make the number negative when there parentheses
                                                 // even when NumberFormatInfo.NumberNegativePattern != 0!!!
                pos++;
                if (AllowLeadingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                {
                    return(false);
                }

                if (s.Substring(pos, nfi.NegativeSign.Length) == nfi.NegativeSign)
                {
                    if (!tryParse)
                    {
                        exc = Int32.GetFormatException();
                    }
                    return(false);
                }

                if (s.Substring(pos, nfi.PositiveSign.Length) == nfi.PositiveSign)
                {
                    if (!tryParse)
                    {
                        exc = Int32.GetFormatException();
                    }
                    return(false);
                }
            }

            if (AllowLeadingSign && !foundSign)
            {
                // Sign + Currency
                Int32.FindSign(ref pos, s, nfi, ref foundSign, ref negative);
                if (foundSign)
                {
                    if (AllowLeadingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (AllowCurrencySymbol)
                    {
                        Int32.FindCurrency(ref pos, s, nfi,
                                           ref foundCurrency);
                        if (foundCurrency && AllowLeadingWhite &&
                            !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                        {
                            return(false);
                        }
                    }
                }
            }

            if (AllowCurrencySymbol && !foundCurrency)
            {
                // Currency + sign
                Int32.FindCurrency(ref pos, s, nfi, ref foundCurrency);
                if (foundCurrency)
                {
                    if (AllowLeadingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (foundCurrency)
                    {
                        if (!foundSign && AllowLeadingSign)
                        {
                            Int32.FindSign(ref pos, s, nfi, ref foundSign,
                                           ref negative);
                            if (foundSign && AllowLeadingWhite &&
                                !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                            {
                                return(false);
                            }
                        }
                    }
                }
            }

            long number            = 0;
            int  nDigits           = 0;
            bool decimalPointFound = false;
            int  digitValue;
            char hexDigit;
            int  exponent = 0;

            // Number stuff
            do
            {
                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 &&
                        (Int32.FindOther(ref pos, s, nfi.NumberDecimalSeparator) ||
                         Int32.FindOther(ref pos, s, nfi.CurrencyDecimalSeparator)))
                    {
                        decimalPointFound = true;
                        continue;
                    }

                    break;
                }
                if (AllowHexSpecifier)
                {
                    nDigits++;
                    hexDigit = s [pos++];
                    if (Char.IsDigit(hexDigit))
                    {
                        digitValue = (int)(hexDigit - '0');
                    }
                    else if (Char.IsLower(hexDigit))
                    {
                        digitValue = (int)(hexDigit - 'a' + 10);
                    }
                    else
                    {
                        digitValue = (int)(hexDigit - 'A' + 10);
                    }

                    ulong unumber = (ulong)number;

                    // IMPROVME: We could avoid catching OverflowException
                    try {
                        number = (long)checked (unumber * 16ul + (ulong)digitValue);
                    } catch (OverflowException e) {
                        if (!tryParse)
                        {
                            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);
                    }
                }
            } while (pos < s.Length);

            // Post number stuff
            if (nDigits == 0)
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            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 && pos < s.Length)
                {
                    if (AllowTrailingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                }
            }

            if (AllowCurrencySymbol && !foundCurrency)
            {
                if (AllowTrailingWhite && pos < s.Length && !Int32.JumpOverWhite(ref pos, s, false, tryParse, ref exc))
                {
                    return(false);
                }

                // Currency + sign
                Int32.FindCurrency(ref pos, s, nfi, ref foundCurrency);
                if (foundCurrency && pos < s.Length)
                {
                    if (AllowTrailingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (!foundSign && AllowTrailingSign)
                    {
                        Int32.FindSign(ref pos, s, nfi, ref foundSign,
                                       ref negative);
                    }
                }
            }

            if (AllowTrailingWhite && pos < s.Length && !Int32.JumpOverWhite(ref pos, s, false, tryParse, ref exc))
            {
                return(false);
            }

            if (foundOpenParentheses)
            {
                if (pos >= s.Length || s [pos++] != ')')
                {
                    if (!tryParse)
                    {
                        exc = Int32.GetFormatException();
                    }
                    return(false);
                }
                if (AllowTrailingWhite && pos < s.Length && !Int32.JumpOverWhite(ref pos, s, false, tryParse, ref exc))
                {
                    return(false);
                }
            }

            if (pos < s.Length && s [pos] != '\u0000')
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            if (!negative && !AllowHexSpecifier)
            {
                try {
                    number = checked (-number);
                } catch (OverflowException e) {
                    if (!tryParse)
                    {
                        exc = e;
                    }
                    return(false);
                }
            }

            // result *= 10^exponent
            if (exponent > 0)
            {
                // Reduce the risk of throwing an overflow exc
                double res = checked (Math.Pow(10, exponent) * number);
                if (res < Int32.MinValue || res > Int32.MaxValue)
                {
                    if (!tryParse)
                    {
                        exc = new OverflowException("Value too large or too small.");
                    }
                    return(false);
                }

                number = (long)res;
            }

            result = number;
            return(true);
        }
Example #35
0
		internal static bool Parse(string s, NumberStyles style, IFormatProvider fp, bool tryParse, out int result, out Exception exc) {
			result = 0;
			exc = null;

			if (s == null) {
				if (!tryParse) {
					exc = GetFormatException();
				}
				return false;
			}

			if (s == null) {
				if (!tryParse) {
					exc = new ArgumentNullException();
				}
				return false;
			}

			if (s.Length == 0) {
				if (!tryParse) {
					exc = GetFormatException();
				}
				return false;
			}

			NumberFormatInfo nfi;
			if (fp != null) {
				Type typeNFI = typeof(System.Globalization.NumberFormatInfo);
				nfi = (NumberFormatInfo)fp.GetFormat(typeNFI);
			} else {
				nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
			}
			if (!CheckStyle(style, tryParse, ref exc)) {
				return false;
			}
			bool AllowCurrencySymbol = (style & NumberStyles.AllowCurrencySymbol) != 0;
			bool AllowHexSpecifier = (style & NumberStyles.AllowHexSpecifier) != 0;
			bool AllowThousands = (style & NumberStyles.AllowThousands) != 0;
			bool AllowDecimalPoint = (style & NumberStyles.AllowDecimalPoint) != 0;
			bool AllowParentheses = (style & NumberStyles.AllowParentheses) != 0;
			bool AllowTrailingSign = (style & NumberStyles.AllowTrailingSign) != 0;
			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;

			if (AllowLeadingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc)) {
				return false;
			}

			bool foundOpenParentheses = false;
			bool negative = false;
			bool foundSign = false;
			bool foundCurrency = false;

			// Pre-number stuff
			if (AllowParentheses && s[pos] == '(') {
				foundOpenParentheses = true;
				foundSign = true;
				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)) {
					return false;
				}
				if (s.Substring(pos, nfi.NegativeSign.Length) == nfi.NegativeSign) {
					if (!tryParse) {
						exc = GetFormatException();
					}
					return false;
				}

				if (s.Substring(pos, nfi.PositiveSign.Length) == nfi.PositiveSign) {
					if (!tryParse) {
						exc = GetFormatException();
					}
					return false;
				}
			}

			if (AllowLeadingSign && !foundSign) {
				// Sign + Currency
				FindSign(ref pos, s, nfi, ref foundSign, ref negative);
				if (foundSign) {
					if (AllowLeadingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc)) {
						return false;
					}
					if (AllowCurrencySymbol) {
						FindCurrency(ref pos, s, nfi, ref foundCurrency);
						if (foundCurrency && AllowLeadingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc)) {
							return false;
						}
					}
				}
			}

			if (AllowCurrencySymbol && !foundCurrency) {
				// Currency + sign
				FindCurrency(ref pos, s, nfi, ref foundCurrency);
				if (foundCurrency) {
					if (AllowLeadingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc)) {
						return false;
					}
					if (foundCurrency) {
						if (!foundSign && AllowLeadingSign) {
							FindSign(ref pos, s, nfi, ref foundSign, ref negative);
							if (foundSign && AllowLeadingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc)) {
								return false;
							}
						}
					}
				}
			}

			int number = 0;
			int nDigits = 0;
			bool decimalPointFound = false;
			int digitValue;
			char hexDigit;

			// Number stuff
			do {
				if (!ValidDigit(s[pos], AllowHexSpecifier)) {
					if (AllowThousands && FindOther(ref pos, s, nfi.NumberGroupSeparator)) {
						continue;
					} else {
						if (!decimalPointFound && AllowDecimalPoint && FindOther(ref pos, s, nfi.NumberDecimalSeparator)) {
							decimalPointFound = true;
							continue;
						}
					}
					break;
				} else if (AllowHexSpecifier) {
					nDigits++;
					hexDigit = s[pos++];
					if (Char.IsDigit(hexDigit)) {
						digitValue = (int)(hexDigit - '0');
					} else if (Char.IsLower(hexDigit)) {
						digitValue = (int)(hexDigit - 'a' + 10);
					} else {
						digitValue = (int)(hexDigit - 'A' + 10);
					}
					uint unumber = (uint)number;
					try {
						number = (int)checked(unumber * 16u + (uint)digitValue);
					} catch (OverflowException e) {
						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 -
							(int)(s[pos++] - '0')
							);
					} catch (OverflowException) {
						if (!tryParse) {
							exc = new OverflowException("Value too large or too small.");
						}
						return false;
					}
				}
			} while (pos < s.Length);

			// Post number stuff
			if (nDigits == 0) {
				if (!tryParse) {
					exc = GetFormatException();
				}
				return false;
			}

			if (AllowExponent) {
				FindExponent(ref pos, s);
			}
			if (AllowTrailingSign && !foundSign) {
				// Sign + Currency
				FindSign(ref pos, s, nfi, ref foundSign, ref negative);
				if (foundSign) {
					if (AllowTrailingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc)) {
						return false;
					}
					if (AllowCurrencySymbol) {
						FindCurrency(ref pos, s, nfi, ref foundCurrency);
					}
				}
			}

			if (AllowCurrencySymbol && !foundCurrency) {
				// Currency + sign
				FindCurrency(ref pos, s, nfi, ref foundCurrency);
				if (foundCurrency) {
					if (AllowTrailingWhite && !JumpOverWhite(ref pos, s, true, tryParse, ref exc)) {
						return false;
					}
					if (!foundSign && AllowTrailingSign) {
						FindSign(ref pos, s, nfi, ref foundSign, ref negative);
					}
				}
			}

			if (AllowTrailingWhite && pos < s.Length && !JumpOverWhite(ref pos, s, false, tryParse, ref exc)) {
				return false;
			}

			if (foundOpenParentheses) {
				if (pos >= s.Length || s[pos++] != ')') {
					if (!tryParse) {
						exc = GetFormatException();
					}
					return false;
				}
				if (AllowTrailingWhite && pos < s.Length && !JumpOverWhite(ref pos, s, false, tryParse, ref exc)) {
					return false;
				}
			}

			if (pos < s.Length && s[pos] != '\u0000') {
				if (!tryParse) {
					exc = GetFormatException();
				}
				return false;
			}

			if (!negative && !AllowHexSpecifier) {
				number = checked(-number);
			}

			result = number;

			return true;
		}
Example #36
0
        internal static bool Parse(string s, NumberStyles style, IFormatProvider provider, bool tryParse, out uint result, out Exception exc)
        {
            result = 0;
            exc    = null;

            if (s == null)
            {
                if (!tryParse)
                {
                    exc = new ArgumentNullException("s");
                }
                return(false);
            }

            if (s.Length == 0)
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            NumberFormatInfo nfi = null;

            if (provider != null)
            {
                Type typeNFI = typeof(NumberFormatInfo);
                nfi = (NumberFormatInfo)provider.GetFormat(typeNFI);
            }
            if (nfi == null)
            {
                nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
            }

            if (!Int32.CheckStyle(style, tryParse, ref exc))
            {
                return(false);
            }

            bool AllowCurrencySymbol = (style & NumberStyles.AllowCurrencySymbol) != 0;
            bool AllowHexSpecifier   = (style & NumberStyles.AllowHexSpecifier) != 0;
            bool AllowThousands      = (style & NumberStyles.AllowThousands) != 0;
            bool AllowDecimalPoint   = (style & NumberStyles.AllowDecimalPoint) != 0;
            bool AllowParentheses    = (style & NumberStyles.AllowParentheses) != 0;
            bool AllowTrailingSign   = (style & NumberStyles.AllowTrailingSign) != 0;
            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;

            if (AllowLeadingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
            {
                return(false);
            }

            bool foundOpenParentheses = false;
            bool negative             = false;
            bool foundSign            = false;
            bool foundCurrency        = false;

            // Pre-number stuff
            if (AllowParentheses && s [pos] == '(')
            {
                foundOpenParentheses = true;
                foundSign            = true;
                negative             = true;     // MS always make the number negative when there parentheses
                                                 // even when NumberFormatInfo.NumberNegativePattern != 0!!!
                pos++;
                if (AllowLeadingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                {
                    return(false);
                }

                if (s.Substring(pos, nfi.NegativeSign.Length) == nfi.NegativeSign)
                {
                    if (!tryParse)
                    {
                        exc = Int32.GetFormatException();
                    }
                    return(false);
                }

                if (s.Substring(pos, nfi.PositiveSign.Length) == nfi.PositiveSign)
                {
                    if (!tryParse)
                    {
                        exc = Int32.GetFormatException();
                    }
                    return(false);
                }
            }

            if (AllowLeadingSign && !foundSign)
            {
                // Sign + Currency
                Int32.FindSign(ref pos, s, nfi, ref foundSign, ref negative);
                if (foundSign)
                {
                    if (AllowLeadingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (AllowCurrencySymbol)
                    {
                        Int32.FindCurrency(ref pos, s, nfi,
                                           ref foundCurrency);
                        if (foundCurrency && AllowLeadingWhite &&
                            !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                        {
                            return(false);
                        }
                    }
                }
            }

            if (AllowCurrencySymbol && !foundCurrency)
            {
                // Currency + sign
                Int32.FindCurrency(ref pos, s, nfi, ref foundCurrency);
                if (foundCurrency)
                {
                    if (AllowLeadingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (foundCurrency)
                    {
                        if (!foundSign && AllowLeadingSign)
                        {
                            Int32.FindSign(ref pos, s, nfi, ref foundSign,
                                           ref negative);
                            if (foundSign && AllowLeadingWhite &&
                                !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                            {
                                return(false);
                            }
                        }
                    }
                }
            }

            uint number          = 0;
            int  nDigits         = 0;
            int  decimalPointPos = -1;
            uint digitValue;
            char hexDigit;

            // Number stuff
            // Just the same as Int32, but this one adds instead of substract
            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;
                    }

                    if (AllowDecimalPoint && decimalPointPos < 0 &&
                        (Int32.FindOther(ref pos, s, nfi.NumberDecimalSeparator) ||
                         Int32.FindOther(ref pos, s, nfi.CurrencyDecimalSeparator)))
                    {
                        decimalPointPos = nDigits;
                        continue;
                    }

                    break;
                }

                nDigits++;

                if (AllowHexSpecifier)
                {
                    hexDigit = s [pos++];
                    if (Char.IsDigit(hexDigit))
                    {
                        digitValue = (uint)(hexDigit - '0');
                    }
                    else if (Char.IsLower(hexDigit))
                    {
                        digitValue = (uint)(hexDigit - 'a' + 10);
                    }
                    else
                    {
                        digitValue = (uint)(hexDigit - 'A' + 10);
                    }

                    if (tryParse)
                    {
                        ulong l = number * 16 + digitValue;

                        if (l > MaxValue)
                        {
                            return(false);
                        }
                        number = (uint)l;
                    }
                    else
                    {
                        number = checked (number * 16 + digitValue);
                    }

                    continue;
                }

                try {
                    number = checked (number * 10 + (uint)(s [pos++] - '0'));
                } catch (OverflowException) {
                    if (!tryParse)
                    {
                        exc = new OverflowException(Locale.GetText("Value too large or too small."));
                    }
                    return(false);
                }
            }

            // Post number stuff
            if (nDigits == 0)
            {
                if (!tryParse)
                {
                    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 && pos < s.Length)
                {
                    if (AllowTrailingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                }
            }

            if (AllowCurrencySymbol && !foundCurrency)
            {
                if (AllowTrailingWhite && pos < s.Length && !Int32.JumpOverWhite(ref pos, s, false, tryParse, ref exc))
                {
                    return(false);
                }

                // Currency + sign
                Int32.FindCurrency(ref pos, s, nfi, ref foundCurrency);
                if (foundCurrency && pos < s.Length)
                {
                    if (AllowTrailingWhite && !Int32.JumpOverWhite(ref pos, s, true, tryParse, ref exc))
                    {
                        return(false);
                    }
                    if (!foundSign && AllowTrailingSign)
                    {
                        Int32.FindSign(ref pos, s, nfi, ref foundSign,
                                       ref negative);
                    }
                }
            }

            if (AllowTrailingWhite && pos < s.Length && !Int32.JumpOverWhite(ref pos, s, false, tryParse, ref exc))
            {
                return(false);
            }

            if (foundOpenParentheses)
            {
                if (pos >= s.Length || s [pos++] != ')')
                {
                    if (!tryParse)
                    {
                        exc = Int32.GetFormatException();
                    }
                    return(false);
                }
                if (AllowTrailingWhite && pos < s.Length && !Int32.JumpOverWhite(ref pos, s, false, tryParse, ref exc))
                {
                    return(false);
                }
            }

            if (pos < s.Length && s [pos] != '\u0000')
            {
                if (!tryParse)
                {
                    exc = Int32.GetFormatException();
                }
                return(false);
            }

            // -0 is legal but other negative values are not
            if (negative && (number > 0))
            {
                if (!tryParse)
                {
                    exc = new OverflowException(
                        Locale.GetText("Negative number"));
                }
                return(false);
            }

            if (decimalPointPos >= 0)
            {
                exponent = exponent - nDigits + decimalPointPos;
            }

            if (exponent < 0)
            {
                //
                // Any non-zero values after decimal point are not allowed
                //
                long remainder;
                number = (uint)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 = (uint)res;
            }

            result = number;
            return(true);
        }
Example #37
0
        public static void Main()
        {
            Console.WriteLine ("Please enter an integer from 0 to 999 inclusive:");
            ushort number = 0;

            try
            {
                number = ushort.Parse (Console.ReadLine());
            }
            catch (Exception e)
            {
                if (e is FormatException)
                {
                    Exception fe = new FormatException ("Error! Input was not in the correct format!");
                    Console.WriteLine (fe.Message);
                }
                else if (e is OverflowException)
                {
                    Exception oe = new OverflowException("Error! Input should be a positive 16-bit integer!");
                    Console.WriteLine (oe.Message);
                }
                else
                {
                    Console.WriteLine ("Error occured!!!");
                }
                return;
            }

            if (number < 0 || number > 999)
            {
                Console.WriteLine ("Invalid Input! Number should be in the range 0 - 999!");
                return;
            }

            // Declare the output...
            string output = "";

            // Set some important values (I'll use arrays)...
            /*-------------------------------------------------*/
            // First array will store the names of the first 20 numbers (from 0 to 19).
            string[] singles = {
                "Zero", "One", "Two",
                "Three", "Four", "Five",
                "Six", "Seven", "Eight",
                "Nine", "Ten", "Eleven",
                "Twelve", "Thirteen", "Fourteen",
                "Fifteen", "Sixteen", "Seventeen",
                "Eighteen", "Nineteen"
            };
            // Second array will store the names of the decimals (20, 30, ..., 90).
            string[] decimals = {
                "Twenty", "Thirty", "Fourty",
                "Fifty", "Sixty", "Seventy",
                "Eighty", "Ninety"
            };

            // Here comes the Magic... :-)

            // Some bools to make it easier...
            bool isBetween0and19 = (number >= 0) && (number <= 19);
            bool isBetween19and99 = (number > 19) && (number <= 99);
            bool isBeween100and999 = (number >= 100) && (number <= 999);

            // Now, we have 3 cases...
            // Range(0-19), Range(19-99) and Range(100-999)

            // 0-19
            if (isBetween0and19)
            {
                output = TransformLowRangeNumber (number, singles);
            }
            // 19-99
            else if (isBetween19and99)
            {
                output = TransformMiddleRangeNumber (number, singles, decimals);
            }
            // 100-999
            else if (isBeween100and999)
            {
                output = TransformHighRangeNumber (number, singles, decimals);
            }

            Console.WriteLine (output);
        }