Bump corefx
[mono.git] / mcs / class / referencesource / mscorlib / system / single.cs
1 // ==++==
2 //
3 //   Copyright (c) Microsoft Corporation.  All rights reserved.
4 //
5 // ==--==
6 /*============================================================
7 **
8 ** Class:  Single
9 **
10 **
11 ** Purpose: A wrapper class for the primitive type float.
12 **
13 **
14 ===========================================================*/
15 namespace System {
16
17     using System.Globalization;
18     using System;
19 ///#if GENERICS_WORK
20 ///    using System.Numerics;
21 ///#endif
22     using System.Runtime.InteropServices;
23     using System.Runtime.CompilerServices;
24     using System.Runtime.ConstrainedExecution;
25     using System.Diagnostics.Contracts;
26
27 [Serializable]
28 [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
29 [System.Runtime.InteropServices.ComVisible(true)]
30 #if GENERICS_WORK
31     public struct Single : IComparable, IFormattable, IConvertible
32         , IComparable<Single>, IEquatable<Single> 
33 ///     , IArithmetic<Single>
34 #else
35     public struct Single : IComparable, IFormattable, IConvertible
36 #endif
37     {
38         internal float m_value;
39
40         //
41         // Public constants
42         //
43         public const float MinValue = (float)-3.40282346638528859e+38;
44         public const float Epsilon = (float)1.4e-45;
45         public const float MaxValue = (float)3.40282346638528859e+38;
46         public const float PositiveInfinity = (float)1.0 / (float)0.0;
47         public const float NegativeInfinity = (float)-1.0 / (float)0.0;
48         public const float NaN = (float)0.0 / (float)0.0;
49
50         [Pure]
51         [System.Security.SecuritySafeCritical]  // auto-generated
52         [System.Runtime.Versioning.NonVersionable]
53         public unsafe static bool IsInfinity(float f) {
54             return (*(int*)(&f) & 0x7FFFFFFF) == 0x7F800000;
55         }
56
57         [Pure]
58         [System.Security.SecuritySafeCritical]  // auto-generated
59         [System.Runtime.Versioning.NonVersionable]
60         public unsafe static bool IsPositiveInfinity(float f) {
61             return *(int*)(&f) == 0x7F800000;
62         }
63
64         [Pure]
65         [System.Security.SecuritySafeCritical]  // auto-generated
66         [System.Runtime.Versioning.NonVersionable]
67         public unsafe static bool IsNegativeInfinity(float f) {
68             return *(int*)(&f) == unchecked((int)0xFF800000);
69         }
70
71         [Pure]
72         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
73         [System.Security.SecuritySafeCritical]
74         [System.Runtime.Versioning.NonVersionable]
75         public unsafe static bool IsNaN(float f) {
76             return (*(int*)(&f) & 0x7FFFFFFF) > 0x7F800000;
77         }
78
79 #if MONO
80         [Pure]
81         [System.Runtime.Versioning.NonVersionable]
82         [MethodImpl(MethodImplOptions.AggressiveInlining)]
83         public unsafe static bool IsFinite(float f) {
84             return (*(int*)(&f) & 0x7FFFFFFF) < 0x7F800000;
85         }
86 #endif
87
88         // Compares this object to another object, returning an integer that
89         // indicates the relationship.
90         // Returns a value less than zero if this  object
91         // null is considered to be less than any instance.
92         // If object is not of type Single, this method throws an ArgumentException.
93         //
94         public int CompareTo(Object value) {
95             if (value == null) {
96                 return 1;
97             }
98             if (value is Single) {
99                 float f = (float)value;
100                 if (m_value < f) return -1;
101                 if (m_value > f) return 1;
102                 if (m_value == f) return 0;
103
104                 // At least one of the values is NaN.
105                 if (IsNaN(m_value))
106                     return (IsNaN(f) ? 0 : -1);
107                 else // f is NaN.
108                     return 1;
109             }
110             throw new ArgumentException (Environment.GetResourceString("Arg_MustBeSingle"));
111         }
112
113
114         public int CompareTo(Single value) {
115             if (m_value < value) return -1;
116             if (m_value > value) return 1;
117             if (m_value == value) return 0;
118
119             // At least one of the values is NaN.
120             if (IsNaN(m_value))
121                 return (IsNaN(value) ? 0 : -1);
122             else // f is NaN.
123                 return 1;
124         }
125
126         [System.Runtime.Versioning.NonVersionable]
127         public static bool operator ==(Single left, Single right) {
128             return left == right;
129         }
130
131         [System.Runtime.Versioning.NonVersionable]
132         public static bool operator !=(Single left, Single right) {
133             return left != right;
134         }
135
136         [System.Runtime.Versioning.NonVersionable]
137         public static bool operator <(Single left, Single right) {
138             return left < right;
139         }
140
141         [System.Runtime.Versioning.NonVersionable]
142         public static bool operator >(Single left, Single right) {
143             return left > right;
144         }
145
146         [System.Runtime.Versioning.NonVersionable]
147         public static bool operator <=(Single left, Single right) {
148             return left <= right;
149         }
150
151         [System.Runtime.Versioning.NonVersionable]
152         public static bool operator >=(Single left, Single right) {
153             return left >= right;
154         }
155
156         public override bool Equals(Object obj) {
157             if (!(obj is Single)) {
158                 return false;
159             }
160             float temp = ((Single)obj).m_value;
161             if (temp == m_value) {
162                 return true;
163             }
164
165             return IsNaN(temp) && IsNaN(m_value);
166         }
167
168         public bool Equals(Single obj)
169         {
170             if (obj == m_value) {
171                 return true;
172             }
173
174             return IsNaN(obj) && IsNaN(m_value);
175         }
176
177         [System.Security.SecuritySafeCritical]  // auto-generated
178         public unsafe override int GetHashCode() {
179             float f = m_value;
180             if (f == 0) {
181                 // Ensure that 0 and -0 have the same hash code
182                 return 0;
183             }
184             int v = *(int*)(&f);
185             return v;
186         }
187
188         [System.Security.SecuritySafeCritical]  // auto-generated
189         public override String ToString() {
190             Contract.Ensures(Contract.Result<String>() != null);
191             return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo);
192         }
193
194         [System.Security.SecuritySafeCritical]  // auto-generated
195         public String ToString(IFormatProvider provider) {
196             Contract.Ensures(Contract.Result<String>() != null);
197             return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider));
198         }
199
200         [System.Security.SecuritySafeCritical]  // auto-generated
201         public String ToString(String format) {
202             Contract.Ensures(Contract.Result<String>() != null);
203             return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo);
204         }
205
206         [System.Security.SecuritySafeCritical]  // auto-generated
207         public String ToString(String format, IFormatProvider provider) {
208             Contract.Ensures(Contract.Result<String>() != null);
209             return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider));
210         }
211
212         // Parses a float from a String in the given style.  If
213         // a NumberFormatInfo isn't specified, the current culture's
214         // NumberFormatInfo is assumed.
215         //
216         // This method will not throw an OverflowException, but will return
217         // PositiveInfinity or NegativeInfinity for a number that is too
218         // large or too small.
219         //
220         public static float Parse(String s) {
221             return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
222         }
223
224         public static float Parse(String s, NumberStyles style) {
225             NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
226             return Parse(s, style, NumberFormatInfo.CurrentInfo);
227         }
228
229         public static float Parse(String s, IFormatProvider provider) {
230             return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
231         }
232
233         public static float Parse(String s, NumberStyles style, IFormatProvider provider) {
234             NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
235             return Parse(s, style, NumberFormatInfo.GetInstance(provider));
236         }
237         
238         private static float Parse(String s, NumberStyles style, NumberFormatInfo info) {
239             return Number.ParseSingle(s, style, info);
240         }
241
242         public static Boolean TryParse(String s, out Single result) {
243             return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
244         }
245
246         public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Single result) {
247             NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
248             return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
249         }
250         
251         private static Boolean TryParse(String s, NumberStyles style, NumberFormatInfo info, out Single result) {
252             if (s == null) {
253                 result = 0;
254                 return false;
255             }
256             bool success = Number.TryParseSingle(s, style, info, out result);
257             if (!success) {
258                 String sTrim = s.Trim();
259                 if (sTrim.Equals(info.PositiveInfinitySymbol)) {
260                     result = PositiveInfinity;
261                 } else if (sTrim.Equals(info.NegativeInfinitySymbol)) {
262                     result = NegativeInfinity;
263                 } else if (sTrim.Equals(info.NaNSymbol)) {
264                     result = NaN;
265                 } else
266                     return false; // We really failed
267             }
268             return true;
269
270         }
271
272         //
273         // IConvertible implementation
274         //
275
276         public TypeCode GetTypeCode() {
277             return TypeCode.Single;
278         }
279
280
281         /// <internalonly/>
282         bool IConvertible.ToBoolean(IFormatProvider provider) {
283             return Convert.ToBoolean(m_value);
284         }
285
286         /// <internalonly/>
287         char IConvertible.ToChar(IFormatProvider provider) {
288             throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Single", "Char"));
289         }
290
291         /// <internalonly/>
292         sbyte IConvertible.ToSByte(IFormatProvider provider) {
293             return Convert.ToSByte(m_value);
294         }
295
296         /// <internalonly/>
297         byte IConvertible.ToByte(IFormatProvider provider) {
298             return Convert.ToByte(m_value);
299         }
300
301         /// <internalonly/>
302         short IConvertible.ToInt16(IFormatProvider provider) {
303             return Convert.ToInt16(m_value);
304         }
305
306         /// <internalonly/>
307         ushort IConvertible.ToUInt16(IFormatProvider provider) {
308             return Convert.ToUInt16(m_value);
309         }
310
311         /// <internalonly/>
312         int IConvertible.ToInt32(IFormatProvider provider) {
313             return Convert.ToInt32(m_value);
314         }
315
316         /// <internalonly/>
317         uint IConvertible.ToUInt32(IFormatProvider provider) {
318             return Convert.ToUInt32(m_value);
319         }
320
321         /// <internalonly/>
322         long IConvertible.ToInt64(IFormatProvider provider) {
323             return Convert.ToInt64(m_value);
324         }
325
326         /// <internalonly/>
327         ulong IConvertible.ToUInt64(IFormatProvider provider) {
328             return Convert.ToUInt64(m_value);
329         }
330
331         /// <internalonly/>
332         float IConvertible.ToSingle(IFormatProvider provider) {
333             return m_value;
334         }
335
336         /// <internalonly/>
337         double IConvertible.ToDouble(IFormatProvider provider) {
338             return Convert.ToDouble(m_value);
339         }
340
341         /// <internalonly/>
342         Decimal IConvertible.ToDecimal(IFormatProvider provider) {
343             return Convert.ToDecimal(m_value);
344         }
345
346         /// <internalonly/>
347         DateTime IConvertible.ToDateTime(IFormatProvider provider) {
348             throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Single", "DateTime"));
349         }
350
351         /// <internalonly/>
352         Object IConvertible.ToType(Type type, IFormatProvider provider) {
353             return Convert.DefaultToType((IConvertible)this, type, provider);
354         }
355 ///#if GENERICS_WORK
356 ///        //
357 ///        // IArithmetic<Single> implementation
358 ///        //
359 ///
360 ///        /// <internalonly/>
361 ///        Single IArithmetic<Single>.AbsoluteValue(out bool overflowed) {
362 ///            Single abs = (m_value < 0 ? -m_value : m_value);
363 ///            overflowed = IsInfinity(abs) || IsNaN(abs);
364 ///            return abs;
365 ///        }
366 ///
367 ///        /// <internalonly/>
368 ///        Single IArithmetic<Single>.Negate(out bool overflowed) {
369 ///            Single neg= -m_value;
370 ///            overflowed = IsInfinity(neg) || IsNaN(neg);
371 ///            return neg;
372 ///        }
373 ///
374 ///        /// <internalonly/>
375 ///        Single IArithmetic<Single>.Sign(out bool overflowed) {
376 ///            overflowed = IsNaN(m_value);
377 ///            if (overflowed) {
378 ///                return m_value;
379 ///            }
380 ///            return (m_value >= 0 ? (m_value == 0 ? 0 : 1) : -1);
381 ///        }
382 ///
383 ///        /// <internalonly/>
384 ///        Single IArithmetic<Single>.Add(Single addend, out bool overflowed) {
385 ///            Single s = m_value + addend;
386 ///            overflowed = IsInfinity(s) || IsNaN(s);
387 ///            return s;
388 ///        }
389 ///
390 ///        /// <internalonly/>
391 ///        Single IArithmetic<Single>.Subtract(Single subtrahend, out bool overflowed) {
392 ///            Single s = m_value - subtrahend;
393 ///            overflowed = IsInfinity(s) || IsNaN(s);
394 ///            return s;
395 ///        }
396 ///
397 ///        /// <internalonly/>
398 ///        Single IArithmetic<Single>.Multiply(Single multiplier, out bool overflowed) {
399 ///            Single s = m_value * multiplier;
400 ///            overflowed = IsInfinity(s) || IsNaN(s);
401 ///            return s;
402 ///        }
403 ///
404 ///
405 ///        /// <internalonly/>
406 ///        Single IArithmetic<Single>.Divide(Single divisor, out bool overflowed) {
407 ///            Single s = m_value / divisor;
408 ///            overflowed = IsInfinity(s) || IsNaN(s);
409 ///            return s;
410 ///        }
411 ///
412 ///        /// <internalonly/>
413 ///        Single IArithmetic<Single>.DivideRemainder(Single divisor, out Single remainder, out bool overflowed) {
414 ///            remainder = m_value % divisor;
415 ///            Single s = m_value / divisor;
416 ///            overflowed = IsInfinity(s) || IsInfinity(remainder) || IsNaN(s) || IsNaN(remainder);
417 ///            return s;
418 ///        }
419 ///
420 ///        /// <internalonly/>
421 ///        Single IArithmetic<Single>.Remainder(Single divisor, out bool overflowed) {
422 ///            Single s = m_value % divisor;
423 ///            overflowed = IsInfinity(s) || IsNaN(s);
424 ///            return s;
425 ///        }
426 ///
427 ///        /// <internalonly/>
428 ///        ArithmeticDescriptor<Single> IArithmetic<Single>.GetDescriptor() {
429 ///            if (s_descriptor == null) {
430 ///                s_descriptor = new SingleArithmeticDescriptor( ArithmeticCapabilities.One
431 ///                                                             | ArithmeticCapabilities.Zero
432 ///                                                             | ArithmeticCapabilities.MaxValue
433 ///                                                             | ArithmeticCapabilities.MinValue
434 ///                                                             | ArithmeticCapabilities.PositiveInfinity
435 ///                                                             | ArithmeticCapabilities.NegativeInfinity);
436 ///            }
437 ///            return s_descriptor;
438 ///        }
439 ///
440 ///        private static SingleArithmeticDescriptor s_descriptor;
441 /// 
442 ///        class SingleArithmeticDescriptor : ArithmeticDescriptor<Single> {
443 ///            public SingleArithmeticDescriptor(ArithmeticCapabilities capabilities) : base(capabilities) {}
444 ///            public override Single One {
445 ///                get {
446 ///                    return (Single) 1;
447 ///                }
448 ///            }
449 ///
450 ///            public override Single Zero {
451 ///                get {
452 ///                    return (Single) 0;
453 ///                }
454 ///            }
455 ///
456 ///            public override Single MinValue {
457 ///                get {
458 ///                    return Single.MinValue;
459 ///                }
460 ///            }
461 ///
462 ///            public override Single MaxValue {
463 ///                get {
464 ///                    return Single.MaxValue;
465 ///                }
466 ///            }
467 ///
468 ///            public override Single PositiveInfinity {
469 ///                get {
470 ///                    return Single.PositiveInfinity;
471 ///                }
472 ///            }
473 ///
474 ///            public override Single NegativeInfinity {
475 ///                get {
476 ///                    return Single.NegativeInfinity;
477 ///                }
478 ///            }
479 ///
480 ///        }
481 ///#endif // #if GENERICS_WORK
482     }
483 }