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