2007-11-14 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mcs / class / corlib / System / TimeSpan.cs
index 6dfde515c20675e2d738e0452d5c230367bd8d62..9ae9da02a9444e0b7cb81e033bc606f478aafafa 100644 (file)
@@ -1,12 +1,33 @@
 //
 // System.TimeSpan.cs
 //
-// Author:
+// Authors:
 //   Duco Fijma (duco@lorentz.xs4all.nl)
 //   Andreas Nahr (ClassDevelopment@A-SoftTech.com)
+//   Sebastien Pouliot  <sebastien@ximian.com>
 //
 // (C) 2001 Duco Fijma
 // (C) 2004 Andreas Nahr
+// Copyright (C) 2004 Novell (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
 using System.Text;
@@ -14,7 +35,13 @@ using System.Text;
 namespace System
 {
        [Serializable]
+#if NET_2_0
+       [System.Runtime.InteropServices.ComVisible (true)]
+#endif
        public struct TimeSpan : IComparable
+#if NET_2_0
+               , IComparable<TimeSpan>, IEquatable <TimeSpan>
+#endif
        {
                public static readonly TimeSpan MaxValue = new TimeSpan (long.MaxValue);
                public static readonly TimeSpan MinValue = new TimeSpan (long.MinValue);
@@ -34,48 +61,66 @@ namespace System
                }
 
                public TimeSpan (int hours, int minutes, int seconds)
-                       : this (0, hours, minutes, seconds, 0)
                {
+                       _ticks = CalculateTicks (0, hours, minutes, seconds, 0);
                }
 
                public TimeSpan (int days, int hours, int minutes, int seconds)
-                       : this (days, hours, minutes, seconds, 0)
                {
+                       _ticks = CalculateTicks (days, hours, minutes, seconds, 0);
                }
 
                public TimeSpan (int days, int hours, int minutes, int seconds, int milliseconds)
                {
-                       try {
-                               checked {
-                                       _ticks = TicksPerDay * days + 
-                                               TicksPerHour * hours +
-                                               TicksPerMinute * minutes +
-                                               TicksPerSecond * seconds +
-                                               TicksPerMillisecond * milliseconds;
+                       _ticks = CalculateTicks (days, hours, minutes, seconds, milliseconds);
+               }
+
+               internal static long CalculateTicks (int days, int hours, int minutes, int seconds, int milliseconds)
+               {
+                       // there's no overflow checks for hours, minutes, ...
+                       // so big hours/minutes values can overflow at some point and change expected values
+                       int hrssec = (hours * 3600); // break point at (Int32.MaxValue - 596523)
+                       int minsec = (minutes * 60);
+                       long t = ((long)(hrssec + minsec + seconds) * 1000L + (long)milliseconds);
+                       t *= 10000;
+
+                       bool overflow = false;
+                       // days is problematic because it can overflow but that overflow can be 
+                       // "legal" (i.e. temporary) (e.g. if other parameters are negative) or 
+                       // illegal (e.g. sign change).
+                       if (days > 0) {
+                               long td = TicksPerDay * days;
+                               if (t < 0) {
+                                       long ticks = t;
+                                       t += td;
+                                       // positive days -> total ticks should be lower
+                                       overflow = (ticks > t);
+                               }
+                               else {
+                                       t += td;
+                                       // positive + positive != negative result
+                                       overflow = (t < 0);
                                }
                        }
-                       catch {
-                               throw new ArgumentOutOfRangeException (Locale.GetText ("The timespan is too big or too small."));
-                       }
-               }
-
-               private TimeSpan (bool sign, int days, int hours, int minutes, int seconds, long ticks)
-               {
-                       try {
-                               checked {
-                                       _ticks = TicksPerDay * days + 
-                                               TicksPerHour * hours +
-                                               TicksPerMinute * minutes +
-                                               TicksPerSecond * seconds +
-                                               ticks;
-                                       if ( sign ) {
-                                               _ticks = -_ticks;
-                                       }
+                       else if (days < 0) {
+                               long td = TicksPerDay * days;
+                               if (t <= 0) {
+                                       t += td;
+                                       // negative + negative != positive result
+                                       overflow = (t > 0);
+                               }
+                               else {
+                                       long ticks = t;
+                                       t += td;
+                                       // negative days -> total ticks should be lower
+                                       overflow = (t > ticks);
                                }
                        }
-                       catch {
+
+                       if (overflow)
                                throw new ArgumentOutOfRangeException (Locale.GetText ("The timespan is too big or too small."));
-                       }
+
+                       return t;
                }
 
                public int Days {
@@ -151,7 +196,7 @@ namespace System
                                        return new TimeSpan (_ticks + ts.Ticks);
                                }
                        }
-                       catch {
+                       catch (OverflowException) {
                                throw new OverflowException (Locale.GetText ("Resulting timespan is too big."));
                        }
                }
@@ -177,6 +222,18 @@ namespace System
                        return Compare (this, (TimeSpan) value);
                }
 
+#if NET_2_0
+               public int CompareTo (TimeSpan value)
+               {
+                       return Compare (this, value);
+               }
+
+               public bool Equals (TimeSpan value)
+               {
+                       return value._ticks == _ticks;
+               }
+#endif
+
                public TimeSpan Duration ()
                {
                        try {
@@ -184,7 +241,7 @@ namespace System
                                        return new TimeSpan (Math.Abs (_ticks));
                                }
                        }
-                       catch {
+                       catch (OverflowException) {
                                throw new OverflowException (Locale.GetText (
                                        "This TimeSpan value is MinValue so you cannot get the duration."));
                        }
@@ -205,40 +262,46 @@ namespace System
 
                public static TimeSpan FromDays (double value)
                {
-                       return FromMilliseconds (value * (TicksPerDay / TicksPerMillisecond));
+                       return From (value, TicksPerDay);
                }
 
                public static TimeSpan FromHours (double value)
                {
-                       return FromMilliseconds (value * (TicksPerHour / TicksPerMillisecond));
+                       return From (value, TicksPerHour);
                }
 
                public static TimeSpan FromMinutes (double value)
                {
-                       return FromMilliseconds (value * (TicksPerMinute / TicksPerMillisecond));
+                       return From (value, TicksPerMinute);
                }
 
                public static TimeSpan FromSeconds (double value)
                {
-                       return FromMilliseconds (value * (TicksPerSecond / TicksPerMillisecond));
+                       return From (value, TicksPerSecond);
                }
 
                public static TimeSpan FromMilliseconds (double value)
+               {
+                       return From (value, TicksPerMillisecond);
+               }
+
+               private static TimeSpan From (double value, long tickMultiplicator) 
                {
                        if (Double.IsNaN (value))
                                throw new ArgumentException (Locale.GetText ("Value cannot be NaN."), "value");
-                       if (Double.IsNegativeInfinity (value))
-                               return MinValue;
-                       if (Double.IsPositiveInfinity (value))
-                               return MaxValue;
+                       if (Double.IsNegativeInfinity (value) || Double.IsPositiveInfinity (value) ||
+                               (value < MinValue.Ticks) || (value > MaxValue.Ticks))
+                               throw new OverflowException (Locale.GetText ("Outside range [MinValue,MaxValue]"));
 
                        try {
+                               value = (value * (tickMultiplicator / TicksPerMillisecond));
+
                                checked {
                                        long val = (long) Math.Round(value);
                                        return new TimeSpan (val * TicksPerMillisecond);
                                }
                        }
-                       catch {
+                       catch (OverflowException) {
                                throw new OverflowException (Locale.GetText ("Resulting timespan is too big."));
                        }
                }
@@ -271,6 +334,19 @@ namespace System
                        return p.Execute ();
                }
 
+#if NET_2_0
+               public static bool TryParse (string s, out TimeSpan result)
+               {
+                       try {
+                               result = Parse (s);
+                               return true;
+                       } catch {
+                               result = TimeSpan.Zero;
+                               return false;
+                       }
+               }
+#endif
+
                public TimeSpan Subtract (TimeSpan ts)
                {
                        try {
@@ -278,7 +354,7 @@ namespace System
                                        return new TimeSpan (_ticks - ts.Ticks);
                                }
                        }
-                       catch {
+                       catch (OverflowException) {
                                throw new OverflowException (Locale.GetText ("Resulting timespan is too big."));
                        }
                }
@@ -299,16 +375,17 @@ namespace System
                                sb.Append ('.');
                        }
 
-                       sb.Append (IntegerFormatter.FormatDecimal (Math.Abs (Hours), 2, 4));
+                       System.Globalization.NumberFormatInfo nfi = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
+                       sb.Append (NumberFormatter.FormatDecimal (new NumberFormatter.NumberStore ((int)Math.Abs (Hours)), 2, nfi));
                        sb.Append (':');
-                       sb.Append (IntegerFormatter.FormatDecimal (Math.Abs (Minutes), 2, 4));
+                       sb.Append (NumberFormatter.FormatDecimal (new NumberFormatter.NumberStore ((int)Math.Abs (Minutes)), 2, nfi));
                        sb.Append (':');
-                       sb.Append (IntegerFormatter.FormatDecimal (Math.Abs (Seconds), 2, 4));
+                       sb.Append (NumberFormatter.FormatDecimal (new NumberFormatter.NumberStore ((int)Math.Abs (Seconds)), 2, nfi));
 
                        int fractional = (int) Math.Abs (_ticks % TicksPerSecond);
                        if (fractional != 0) {
                                sb.Append ('.');
-                               sb.Append (IntegerFormatter.FormatDecimal (Math.Abs (fractional), 7, 4));
+                               sb.Append (NumberFormatter.FormatDecimal (new NumberFormatter.NumberStore (fractional), 7, nfi));
                        }
 
                        return sb.ToString ();
@@ -370,6 +447,7 @@ namespace System
                        private string _src;
                        private int _cur = 0;
                        private int _length;
+                       private bool formatError;
 
                        public Parser (string src)
                        {
@@ -383,11 +461,6 @@ namespace System
                                }
                        }
 
-                       private void ThrowFormatException ()
-                       {
-                               throw new FormatException (Locale.GetText ("Invalid format for TimeSpan.Parse."));
-                       }
-
                        // All "Parse" functions throw a FormatException on syntax error.
                        // Their return value is semantic value of the item parsed.
 
@@ -421,8 +494,11 @@ namespace System
                        }
 
                        // Parse simple int value
-                       private int ParseInt ()
+                       private int ParseInt (bool optional)
                        {
+                               if (optional && AtEnd)
+                                       return 0;
+
                                int res = 0;
                                int count = 0;
 
@@ -435,7 +511,7 @@ namespace System
                                }
 
                                if (count == 0)
-                                       ThrowFormatException ();
+                                       formatError = true;
 
                                return res;
                        }
@@ -453,13 +529,15 @@ namespace System
                                return false;
                        }       
 
-                       // Parse NON-optional colon
-                       private void ParseColon ()
+                       // Parse optional (LAMESPEC) colon
+                       private void ParseOptColon ()
                        {
-                               if (!AtEnd && _src[_cur] == ':')
-                                       _cur++;
-                               else 
-                                       ThrowFormatException ();
+                               if (!AtEnd) {
+                                       if (_src[_cur] == ':')
+                                               _cur++;
+                                       else 
+                                               formatError = true;
+                               }
                        }
 
                        // Parse [1..7] digits, representing fractional seconds (ticks)
@@ -477,7 +555,7 @@ namespace System
                                }
 
                                if (!digitseen)
-                                       ThrowFormatException ();
+                                       formatError = true;
 
                                return res;
                        }
@@ -486,26 +564,29 @@ namespace System
                        {
                                bool sign;
                                int days;
-                               int hours;
+                               int hours = 0;
                                int minutes;
                                int seconds;
                                long ticks;
 
+                               // documented as...
                                // Parse [ws][-][dd.]hh:mm:ss[.ff][ws]
+                               // ... but not entirely true as an lonely 
+                               // integer will be parsed as a number of days
                                ParseWhiteSpace ();
                                sign = ParseSign ();
-                               days = ParseInt ();
+                               days = ParseInt (false);
                                if (ParseOptDot ()) {
-                                       hours = ParseInt ();
+                                       hours = ParseInt (true);
                                }
-                               else {
+                               else if (!AtEnd) {
                                        hours = days;
                                        days = 0;
                                }
-                               ParseColon();
-                               minutes = ParseInt ();
-                               ParseColon ();
-                               seconds = ParseInt ();
+                               ParseOptColon();
+                               minutes = ParseInt (true);
+                               ParseOptColon ();
+                               seconds = ParseInt (true);
                                if ( ParseOptDot () ) {
                                        ticks = ParseTicks ();
                                }
@@ -515,16 +596,21 @@ namespace System
                                ParseWhiteSpace ();
        
                                if (!AtEnd)
-                                       ThrowFormatException ();
+                                       formatError = true;
 
+                               // Overflow has presceance over FormatException
                                if (hours > 23 || minutes > 59 || seconds > 59) {
-                                       throw new OverflowException (Locale.GetText (
-                                               "Invalid time data."));
+                                       throw new OverflowException (
+                                               Locale.GetText ("Invalid time data."));
+                               }
+                               else if (formatError) {
+                                       throw new FormatException (
+                                               Locale.GetText ("Invalid format for TimeSpan.Parse."));
                                }
 
-                               TimeSpan ts = new TimeSpan (sign, days, hours, minutes, seconds, ticks);
-
-                               return ts;
+                               long t = TimeSpan.CalculateTicks (days, hours, minutes, seconds, 0);
+                               t = checked ((sign) ? (-t - ticks) : (t + ticks));
+                               return new TimeSpan (t);
                        }
                }
        }