2005-12-07 Zoltan Varga <vargaz@gmail.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                         
224                         if (style > NumberStyles.Any) {
225                                 if (!tryParse)
226                                         exc = new ArgumentException();
227                                 return false;
228                         }
229                         
230                         NumberFormatInfo format = NumberFormatInfo.GetInstance(provider);
231                         if (format == null) throw new Exception("How did this happen?");
232                         
233                         if (s == format.NaNSymbol) {
234                                 result = Double.NaN;
235                                 return true;
236                         }
237                         if (s == format.PositiveInfinitySymbol) {
238                                 result = Double.PositiveInfinity;
239                                 return true;
240                         }
241                         if (s == format.NegativeInfinitySymbol) {
242                                 result = Double.NegativeInfinity;
243                                 return true;
244                         }
245
246                         //
247                         // validate and prepare string for C
248                         //
249                         int len = s.Length;
250                         byte [] b = new byte [len + 1];
251                         int didx = 0;
252                         int sidx = 0;
253                         char c;
254                         
255                         if ((style & NumberStyles.AllowLeadingWhite) != 0){
256                                 while (sidx < len && Char.IsWhiteSpace (c = s [sidx]))
257                                        sidx++;
258
259                                 if (sidx == len) {
260                                         if (!tryParse)
261                                                 exc = Int32.GetFormatException ();
262                                         return true;
263                                 }
264                         }
265
266                         bool allow_trailing_white = ((style & NumberStyles.AllowTrailingWhite) != 0);
267
268                         //
269                         // Machine state
270                         //
271                         int state = State_AllowSign;
272
273                         //
274                         // Setup
275                         //
276                         string decimal_separator = null;
277                         string group_separator = null;
278                         int decimal_separator_len = 0;
279                         int group_separator_len = 0;
280                         if ((style & NumberStyles.AllowDecimalPoint) != 0){
281                                 decimal_separator = format.NumberDecimalSeparator;
282                                 decimal_separator_len = decimal_separator.Length;
283                         }
284                         if ((style & NumberStyles.AllowThousands) != 0){
285                                 group_separator = format.NumberGroupSeparator;
286                                 group_separator_len = group_separator.Length;
287                         }
288                         string positive = format.PositiveSign;
289                         string negative = format.NegativeSign;
290                         
291                         for (; sidx < len; sidx++){
292                                 c = s [sidx];
293
294                                 if (c == '\0') {
295                                         sidx = len;
296                                         continue;
297                                 }
298                                 switch (state){
299                                 case State_AllowSign:
300                                         if ((style & NumberStyles.AllowLeadingSign) != 0){
301                                                 if (c == positive [0] &&
302                                                     s.Substring (sidx, positive.Length) == positive){
303                                                         state = State_Digits;
304                                                         sidx += positive.Length-1;
305                                                         continue;
306                                                 }
307
308                                                 if (c == negative [0] &&
309                                                     s.Substring (sidx, negative.Length) == negative){
310                                                         state = State_Digits;
311                                                         b [didx++] = (byte) '-';
312                                                         sidx += negative.Length-1;
313                                                         continue;
314                                                 }
315                                         }
316                                         state = State_Digits;
317                                         goto case State_Digits;
318                                         
319                                 case State_Digits:
320                                         if (Char.IsDigit (c)){
321                                                 b [didx++] = (byte) c;
322                                                 break;
323                                         }
324                                         if (c == 'e' || c == 'E')
325                                                 goto case State_Decimal;
326                                         
327                                         if (decimal_separator != null &&
328                                             decimal_separator [0] == c){
329                                                 if (s.Substring (sidx, decimal_separator_len) ==
330                                                     decimal_separator){
331                                                         b [didx++] = (byte) '.';
332                                                         sidx += decimal_separator_len-1;
333                                                         state = State_Decimal; 
334                                                         break;
335                                                 }
336                                         }
337                                         if (group_separator != null &&
338                                             group_separator [0] == c){
339                                                 if (s.Substring (sidx, group_separator_len) ==
340                                                     group_separator){
341                                                         sidx += group_separator_len-1;
342                                                         state = State_Digits; 
343                                                         break;
344                                                 }
345                                         }
346                                         
347                                         if (Char.IsWhiteSpace (c))
348                                                 goto case State_ConsumeWhiteSpace;
349
350                                         if (!tryParse)
351                                                 exc = new FormatException ("Unknown char: " + c);
352                                         return false;
353
354                                 case State_Decimal:
355                                         if (Char.IsDigit (c)){
356                                                 b [didx++] = (byte) c;
357                                                 break;
358                                         }
359
360                                         if (c == 'e' || c == 'E'){
361                                                 if ((style & NumberStyles.AllowExponent) == 0)
362                                                         throw new FormatException ("Unknown char: " + c);
363                                                 b [didx++] = (byte) c;
364                                                 state = State_ExponentSign;
365                                                 break;
366                                         }
367                                         
368                                         if (Char.IsWhiteSpace (c))
369                                                 goto case State_ConsumeWhiteSpace;
370                                         
371                                         if (!tryParse)
372                                                 exc = new FormatException ("Unknown char: " + c);
373                                         return false;
374
375                                 case State_ExponentSign:
376                                         if (Char.IsDigit (c)){
377                                                 state = State_Exponent;
378                                                 goto case State_Exponent;
379                                         }
380
381                                         if (c == positive [0] &&
382                                             s.Substring (sidx, positive.Length) == positive){
383                                                 state = State_Digits;
384                                                 sidx += positive.Length-1;
385                                                 continue;
386                                         }
387
388                                         if (c == negative [0] &&
389                                             s.Substring (sidx, negative.Length) == negative){
390                                                 state = State_Digits;
391                                                 b [didx++] = (byte) '-';
392                                                 sidx += negative.Length-1;
393                                                 continue;
394                                         }
395
396                                         if (Char.IsWhiteSpace (c))
397                                                 goto case State_ConsumeWhiteSpace;
398                                         
399                                         if (!tryParse)
400                                                 exc = new FormatException ("Unknown char: " + c);
401                                         return false;
402                                         
403                                 case State_Exponent:
404                                         if (Char.IsDigit (c)){
405                                                 b [didx++] = (byte) c;
406                                                 break;
407                                         }
408                                         
409                                         if (Char.IsWhiteSpace (c))
410                                                 goto case State_ConsumeWhiteSpace;
411                                         
412                                         if (!tryParse)
413                                                 exc = new FormatException ("Unknown char: " + c);
414                                         return false;
415
416                                 case State_ConsumeWhiteSpace:
417                                         if (allow_trailing_white && Char.IsWhiteSpace (c))
418                                                 break;
419                                         
420                                         if (!tryParse)
421                                                 exc = new FormatException ("Unknown char");
422                                         return false;
423                                 }
424                         }
425
426                         b [didx] = 0;
427                         unsafe {
428                                 fixed (byte *p = &b [0]){
429                                         double retVal;
430                                         if (!ParseImpl (p, out retVal)) {
431                                                 if (!tryParse)
432                                                         exc = Int32.GetFormatException ();
433                                                 return false;
434                                         }
435                                         if (IsPositiveInfinity(retVal) || IsNegativeInfinity(retVal)) {
436                                                 if (!tryParse)
437                                                         exc = new OverflowException ();
438                                                 return false;
439                                         }
440
441                                         result = retVal;
442                                         return true;
443                                 }
444                         }
445                 }
446
447                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
448                 unsafe private static extern bool ParseImpl (byte *byte_ptr, out double value);
449                 
450                 public static bool TryParse (string s,
451                                              NumberStyles style,
452                                              IFormatProvider provider,
453                                              out double result)
454                 {
455                         Exception exc;
456                         if (!Parse (s, style, provider, true, out result, out exc)) {
457                                 result = 0;
458                                 return false;
459                         }
460
461                         return true;
462                 }
463
464                 public override string ToString ()
465                 {
466                         return ToString (null, null);
467                 }
468
469                 public string ToString (IFormatProvider fp)
470                 {
471                         return ToString (null, fp);
472                 }
473
474                 public string ToString (string format)
475                 {
476                         return ToString (format, null);
477                 }
478
479                 public string ToString (string format, IFormatProvider fp)
480                 {
481                         NumberFormatInfo nfi = NumberFormatInfo.GetInstance (fp);
482                         return NumberFormatter.NumberToString (format, m_value, nfi);
483                 }
484
485                 // =========== IConvertible Methods =========== //
486
487                 public TypeCode GetTypeCode ()
488                 {
489                         return TypeCode.Double;
490                 }
491
492                 object IConvertible.ToType (Type conversionType, IFormatProvider provider)
493                 {
494                         return System.Convert.ToType(m_value, conversionType, provider);
495                 }
496                 
497                 bool IConvertible.ToBoolean (IFormatProvider provider)
498                 {
499                         return System.Convert.ToBoolean(m_value);
500                 }
501                 
502                 byte IConvertible.ToByte (IFormatProvider provider)
503                 {
504                         return System.Convert.ToByte(m_value);
505                 }
506                 
507                 char IConvertible.ToChar (IFormatProvider provider)
508                 {
509                         throw new InvalidCastException();
510                 }
511                 
512                 DateTime IConvertible.ToDateTime (IFormatProvider provider)
513                 {
514                         throw new InvalidCastException();
515                 }
516                 
517                 decimal IConvertible.ToDecimal (IFormatProvider provider)
518                 {
519                         return System.Convert.ToDecimal(m_value);
520                 }
521                 
522                 double IConvertible.ToDouble (IFormatProvider provider)
523                 {
524                         return System.Convert.ToDouble(m_value);
525                 }
526                 
527                 short IConvertible.ToInt16 (IFormatProvider provider)
528                 {
529                         return System.Convert.ToInt16(m_value);
530                 }
531                 
532                 int IConvertible.ToInt32 (IFormatProvider provider)
533                 {
534                         return System.Convert.ToInt32(m_value);
535                 }
536                 
537                 long IConvertible.ToInt64 (IFormatProvider provider)
538                 {
539                         return System.Convert.ToInt64(m_value);
540                 }
541                 
542                 sbyte IConvertible.ToSByte (IFormatProvider provider)
543                 {
544                         return System.Convert.ToSByte(m_value);
545                 }
546                 
547                 float IConvertible.ToSingle (IFormatProvider provider)
548                 {
549                         return System.Convert.ToSingle(m_value);
550                 }
551                 
552 /*
553                 string IConvertible.ToString (IFormatProvider provider)
554                 {
555                         return ToString(provider);
556                 }
557 */
558
559                 ushort IConvertible.ToUInt16 (IFormatProvider provider)
560                 {
561                         return System.Convert.ToUInt16(m_value);
562                 }
563                 
564                 uint IConvertible.ToUInt32 (IFormatProvider provider)
565                 {
566                         return System.Convert.ToUInt32(m_value);
567                 }
568                 
569                 ulong IConvertible.ToUInt64 (IFormatProvider provider)
570                 {
571                         return System.Convert.ToUInt64(m_value);
572                 }
573         }
574 }