2005-12-15 Sebastien Pouliot <sebastien@ximian.com>
[mono.git] / mcs / class / corlib / System / Double.cs
1 //
2 // System.Double.cs
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Bob Smith       (bob@thestuff.net)
7 //
8 // (C) Ximian, Inc.  http://www.ximian.com
9 // (C) Bob Smith.    http://www.thestuff.net
10 //
11
12 //
13 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
14 //
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
22 // 
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
25 // 
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 //
34
35 using System.Globalization;
36 using System.Runtime.CompilerServices;
37
38 #if NET_2_0
39 using System.Runtime.ConstrainedExecution;
40 #endif
41
42 namespace System {
43         
44         [Serializable]
45         public struct Double : IComparable, IFormattable, IConvertible
46 #if NET_2_0
47                 , IComparable <double>, IEquatable <double>
48 #endif
49         {
50                 public const double Epsilon = 4.9406564584124650e-324;
51                 public const double MaxValue =  1.7976931348623157e308;
52                 public const double MinValue = -1.7976931348623157e308;
53                 public const double NaN = 0.0d / 0.0d;
54                 public const double NegativeInfinity = -1.0d / 0.0d;
55                 public const double PositiveInfinity = 1.0d / 0.0d;
56                 
57                 internal double m_value;
58
59                 public int CompareTo (object v)
60                 {
61                         if (v == null)
62                                 return 1;
63                         
64                         if (!(v is System.Double))
65                                 throw new ArgumentException (Locale.GetText ("Value is not a System.Double"));
66
67                         double dv = (double)v;
68
69                         if (IsPositiveInfinity(m_value) && IsPositiveInfinity(dv))
70                                 return 0;
71
72                         if (IsNegativeInfinity(m_value) && IsNegativeInfinity(dv))
73                                 return 0;
74
75                         if (IsNaN(dv))
76                                 if (IsNaN(m_value))
77                                         return 0;
78                                 else
79                                         return 1;
80
81                         if (IsNaN(m_value))
82                                 if (IsNaN(dv))
83                                         return 0;
84                                 else
85                                         return -1;
86
87                         if (m_value > dv) return 1;
88                         else if (m_value < dv) return -1;
89                         else return 0;
90                 }
91
92                 public override bool Equals (object o)
93                 {
94                         if (!(o is System.Double))
95                                 return false;
96
97                         if (IsNaN ((double)o)) {
98                                 if (IsNaN(m_value))
99                                         return true;
100                                 else
101                                         return false;
102                         }
103
104                         return ((double) o) == m_value;
105                 }
106
107 #if NET_2_0
108                 public int CompareTo (double value)
109                 {
110                         if (IsPositiveInfinity(m_value) && IsPositiveInfinity(value))
111                                 return 0;
112
113                         if (IsNegativeInfinity(m_value) && IsNegativeInfinity(value))
114                                 return 0;
115
116                         if (IsNaN(value))
117                                 if (IsNaN(m_value))
118                                         return 0;
119                                 else
120                                         return 1;
121
122                         if (IsNaN(m_value))
123                                 if (IsNaN(value))
124                                         return 0;
125                                 else
126                                         return -1;
127
128                         if (m_value > value) return 1;
129                         else if (m_value < value) return -1;
130                         else return 0;
131                 }
132
133                 public bool Equals (double value)
134                 {
135                         if (IsNaN (value)) {
136                                 if (IsNaN(m_value))
137                                         return true;
138                                 else
139                                         return false;
140                         }
141
142                         return value == m_value;
143                 }
144 #endif
145
146                 public override unsafe int GetHashCode ()
147                 {
148                         double d = m_value;
149                         return (*((long*)&d)).GetHashCode ();
150                 }
151
152                 public static bool IsInfinity (double d)
153                 {
154                         return (d == PositiveInfinity || d == NegativeInfinity);
155                 }
156
157 #if NET_2_0
158                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
159 #endif
160                 public static bool IsNaN (double d)
161                 {
162 #pragma warning disable 1718
163                         return (d != d);
164 #pragma warning restore
165                 }
166
167                 public static bool IsNegativeInfinity (double d)
168                 {
169                         return (d < 0.0d && (d == NegativeInfinity || d == PositiveInfinity));
170                 }
171
172                 public static bool IsPositiveInfinity (double d)
173                 {
174                         return (d > 0.0d && (d == NegativeInfinity || d == PositiveInfinity));
175                 }
176
177                 public static double Parse (string s)
178                 {
179                         return Parse (s, (NumberStyles.Float | NumberStyles.AllowThousands), null);
180                 }
181
182                 public static double Parse (string s, IFormatProvider fp)
183                 {
184                         return Parse (s, (NumberStyles.Float | NumberStyles.AllowThousands), fp);
185                 }
186
187                 public static double Parse (string s, NumberStyles style) 
188                 {
189                         return Parse (s, style, null);
190                 }
191
192                 // We're intentionally using constants here to avoid some bigger headaches in mcs.
193                 // This struct must be compiled before System.Enum so we can't use enums here.
194                 private const int State_AllowSign = 1;
195                 private const int State_Digits = 2;
196                 private const int State_Decimal = 3;
197                 private const int State_ExponentSign = 4;
198                 private const int State_Exponent = 5;
199                 private const int State_ConsumeWhiteSpace = 6;
200                 
201                 public static double Parse (string s, NumberStyles style, IFormatProvider provider)
202                 {
203                         Exception exc;
204                         double result;
205                         
206                         if (!Parse (s, style, provider, false, out result, out exc))
207                                 throw exc;
208
209                         return result;
210                 }
211                 
212                 [MonoTODO("check if digits are group in correct numbers between the group separators")]
213                 internal static bool Parse (string s, NumberStyles style, IFormatProvider provider, bool tryParse, out double result, out Exception exc)
214                 {
215                         result = 0;
216                         exc = null;
217                         
218                         if (s == null) {
219                                 if (!tryParse)
220                                         exc = new ArgumentNullException ("s");
221                                 return false;
222                         }
223 #if NET_2_0
224                         // yes it's counter intuitive (buggy?) but even TryParse actually throws in this case
225                         if ((style & NumberStyles.AllowHexSpecifier) != 0) {
226                                 string msg = Locale.GetText ("Double doesn't support parsing with '{0}'.", "AllowHexSpecifier");
227                                 throw new ArgumentException (msg);
228                         }
229 #endif
230                         if (style > NumberStyles.Any) {
231                                 if (!tryParse)
232                                         exc = new ArgumentException();
233                                 return false;
234                         }
235
236                         NumberFormatInfo format = NumberFormatInfo.GetInstance(provider);
237                         if (format == null) throw new Exception("How did this happen?");
238                         
239                         if (s == format.NaNSymbol) {
240                                 result = Double.NaN;
241                                 return true;
242                         }
243                         if (s == format.PositiveInfinitySymbol) {
244                                 result = Double.PositiveInfinity;
245                                 return true;
246                         }
247                         if (s == format.NegativeInfinitySymbol) {
248                                 result = Double.NegativeInfinity;
249                                 return true;
250                         }
251
252                         //
253                         // validate and prepare string for C
254                         //
255                         int len = s.Length;
256                         byte [] b = new byte [len + 1];
257                         int didx = 0;
258                         int sidx = 0;
259                         char c;
260                         
261                         if ((style & NumberStyles.AllowLeadingWhite) != 0){
262                                 while (sidx < len && Char.IsWhiteSpace (c = s [sidx]))
263                                        sidx++;
264
265                                 if (sidx == len) {
266                                         if (!tryParse)
267                                                 exc = Int32.GetFormatException ();
268                                         return true;
269                                 }
270                         }
271
272                         bool allow_trailing_white = ((style & NumberStyles.AllowTrailingWhite) != 0);
273
274                         //
275                         // Machine state
276                         //
277                         int state = State_AllowSign;
278
279                         //
280                         // Setup
281                         //
282                         string decimal_separator = null;
283                         string group_separator = null;
284                         int decimal_separator_len = 0;
285                         int group_separator_len = 0;
286                         if ((style & NumberStyles.AllowDecimalPoint) != 0){
287                                 decimal_separator = format.NumberDecimalSeparator;
288                                 decimal_separator_len = decimal_separator.Length;
289                         }
290                         if ((style & NumberStyles.AllowThousands) != 0){
291                                 group_separator = format.NumberGroupSeparator;
292                                 group_separator_len = group_separator.Length;
293                         }
294                         string positive = format.PositiveSign;
295                         string negative = format.NegativeSign;
296                         
297                         for (; sidx < len; sidx++){
298                                 c = s [sidx];
299
300                                 if (c == '\0') {
301                                         sidx = len;
302                                         continue;
303                                 }
304                                 switch (state){
305                                 case State_AllowSign:
306                                         if ((style & NumberStyles.AllowLeadingSign) != 0){
307                                                 if (c == positive [0] &&
308                                                     s.Substring (sidx, positive.Length) == positive){
309                                                         state = State_Digits;
310                                                         sidx += positive.Length-1;
311                                                         continue;
312                                                 }
313
314                                                 if (c == negative [0] &&
315                                                     s.Substring (sidx, negative.Length) == negative){
316                                                         state = State_Digits;
317                                                         b [didx++] = (byte) '-';
318                                                         sidx += negative.Length-1;
319                                                         continue;
320                                                 }
321                                         }
322                                         state = State_Digits;
323                                         goto case State_Digits;
324                                         
325                                 case State_Digits:
326                                         if (Char.IsDigit (c)){
327                                                 b [didx++] = (byte) c;
328                                                 break;
329                                         }
330                                         if (c == 'e' || c == 'E')
331                                                 goto case State_Decimal;
332                                         
333                                         if (decimal_separator != null &&
334                                             decimal_separator [0] == c){
335                                                 if (s.Substring (sidx, decimal_separator_len) ==
336                                                     decimal_separator){
337                                                         b [didx++] = (byte) '.';
338                                                         sidx += decimal_separator_len-1;
339                                                         state = State_Decimal; 
340                                                         break;
341                                                 }
342                                         }
343                                         if (group_separator != null &&
344                                             group_separator [0] == c){
345                                                 if (s.Substring (sidx, group_separator_len) ==
346                                                     group_separator){
347                                                         sidx += group_separator_len-1;
348                                                         state = State_Digits; 
349                                                         break;
350                                                 }
351                                         }
352                                         
353                                         if (Char.IsWhiteSpace (c))
354                                                 goto case State_ConsumeWhiteSpace;
355
356                                         if (!tryParse)
357                                                 exc = new FormatException ("Unknown char: " + c);
358                                         return false;
359
360                                 case State_Decimal:
361                                         if (Char.IsDigit (c)){
362                                                 b [didx++] = (byte) c;
363                                                 break;
364                                         }
365
366                                         if (c == 'e' || c == 'E'){
367                                                 if ((style & NumberStyles.AllowExponent) == 0)
368                                                         throw new FormatException ("Unknown char: " + c);
369                                                 b [didx++] = (byte) c;
370                                                 state = State_ExponentSign;
371                                                 break;
372                                         }
373                                         
374                                         if (Char.IsWhiteSpace (c))
375                                                 goto case State_ConsumeWhiteSpace;
376                                         
377                                         if (!tryParse)
378                                                 exc = new FormatException ("Unknown char: " + c);
379                                         return false;
380
381                                 case State_ExponentSign:
382                                         if (Char.IsDigit (c)){
383                                                 state = State_Exponent;
384                                                 goto case State_Exponent;
385                                         }
386
387                                         if (c == positive [0] &&
388                                             s.Substring (sidx, positive.Length) == positive){
389                                                 state = State_Digits;
390                                                 sidx += positive.Length-1;
391                                                 continue;
392                                         }
393
394                                         if (c == negative [0] &&
395                                             s.Substring (sidx, negative.Length) == negative){
396                                                 state = State_Digits;
397                                                 b [didx++] = (byte) '-';
398                                                 sidx += negative.Length-1;
399                                                 continue;
400                                         }
401
402                                         if (Char.IsWhiteSpace (c))
403                                                 goto case State_ConsumeWhiteSpace;
404                                         
405                                         if (!tryParse)
406                                                 exc = new FormatException ("Unknown char: " + c);
407                                         return false;
408                                         
409                                 case State_Exponent:
410                                         if (Char.IsDigit (c)){
411                                                 b [didx++] = (byte) c;
412                                                 break;
413                                         }
414                                         
415                                         if (Char.IsWhiteSpace (c))
416                                                 goto case State_ConsumeWhiteSpace;
417                                         
418                                         if (!tryParse)
419                                                 exc = new FormatException ("Unknown char: " + c);
420                                         return false;
421
422                                 case State_ConsumeWhiteSpace:
423                                         if (allow_trailing_white && Char.IsWhiteSpace (c))
424                                                 break;
425                                         
426                                         if (!tryParse)
427                                                 exc = new FormatException ("Unknown char");
428                                         return false;
429                                 }
430                         }
431
432                         b [didx] = 0;
433                         unsafe {
434                                 fixed (byte *p = &b [0]){
435                                         double retVal;
436                                         if (!ParseImpl (p, out retVal)) {
437                                                 if (!tryParse)
438                                                         exc = Int32.GetFormatException ();
439                                                 return false;
440                                         }
441                                         if (IsPositiveInfinity(retVal) || IsNegativeInfinity(retVal)) {
442                                                 if (!tryParse)
443                                                         exc = new OverflowException ();
444                                                 return false;
445                                         }
446
447                                         result = retVal;
448                                         return true;
449                                 }
450                         }
451                 }
452
453                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
454                 unsafe private static extern bool ParseImpl (byte *byte_ptr, out double value);
455                 
456                 public static bool TryParse (string s,
457                                              NumberStyles style,
458                                              IFormatProvider provider,
459                                              out double result)
460                 {
461                         Exception exc;
462                         if (!Parse (s, style, provider, true, out result, out exc)) {
463                                 result = 0;
464                                 return false;
465                         }
466
467                         return true;
468                 }
469 #if NET_2_0
470                 public static bool TryParse (string s, out double result)
471                 {
472                         return TryParse (s, NumberStyles.Any, null, out result);
473                 }
474 #endif
475                 public override string ToString ()
476                 {
477                         return ToString (null, null);
478                 }
479
480                 public string ToString (IFormatProvider fp)
481                 {
482                         return ToString (null, fp);
483                 }
484
485                 public string ToString (string format)
486                 {
487                         return ToString (format, null);
488                 }
489
490                 public string ToString (string format, IFormatProvider fp)
491                 {
492                         NumberFormatInfo nfi = NumberFormatInfo.GetInstance (fp);
493                         return NumberFormatter.NumberToString (format, m_value, nfi);
494                 }
495
496                 // =========== IConvertible Methods =========== //
497
498                 public TypeCode GetTypeCode ()
499                 {
500                         return TypeCode.Double;
501                 }
502
503                 object IConvertible.ToType (Type conversionType, IFormatProvider provider)
504                 {
505                         return System.Convert.ToType(m_value, conversionType, provider);
506                 }
507                 
508                 bool IConvertible.ToBoolean (IFormatProvider provider)
509                 {
510                         return System.Convert.ToBoolean(m_value);
511                 }
512                 
513                 byte IConvertible.ToByte (IFormatProvider provider)
514                 {
515                         return System.Convert.ToByte(m_value);
516                 }
517                 
518                 char IConvertible.ToChar (IFormatProvider provider)
519                 {
520                         throw new InvalidCastException();
521                 }
522                 
523                 DateTime IConvertible.ToDateTime (IFormatProvider provider)
524                 {
525                         throw new InvalidCastException();
526                 }
527                 
528                 decimal IConvertible.ToDecimal (IFormatProvider provider)
529                 {
530                         return System.Convert.ToDecimal(m_value);
531                 }
532                 
533                 double IConvertible.ToDouble (IFormatProvider provider)
534                 {
535                         return System.Convert.ToDouble(m_value);
536                 }
537                 
538                 short IConvertible.ToInt16 (IFormatProvider provider)
539                 {
540                         return System.Convert.ToInt16(m_value);
541                 }
542                 
543                 int IConvertible.ToInt32 (IFormatProvider provider)
544                 {
545                         return System.Convert.ToInt32(m_value);
546                 }
547                 
548                 long IConvertible.ToInt64 (IFormatProvider provider)
549                 {
550                         return System.Convert.ToInt64(m_value);
551                 }
552                 
553                 sbyte IConvertible.ToSByte (IFormatProvider provider)
554                 {
555                         return System.Convert.ToSByte(m_value);
556                 }
557                 
558                 float IConvertible.ToSingle (IFormatProvider provider)
559                 {
560                         return System.Convert.ToSingle(m_value);
561                 }
562                 
563 /*
564                 string IConvertible.ToString (IFormatProvider provider)
565                 {
566                         return ToString(provider);
567                 }
568 */
569
570                 ushort IConvertible.ToUInt16 (IFormatProvider provider)
571                 {
572                         return System.Convert.ToUInt16(m_value);
573                 }
574                 
575                 uint IConvertible.ToUInt32 (IFormatProvider provider)
576                 {
577                         return System.Convert.ToUInt32(m_value);
578                 }
579                 
580                 ulong IConvertible.ToUInt64 (IFormatProvider provider)
581                 {
582                         return System.Convert.ToUInt64(m_value);
583                 }
584         }
585 }