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