JsBigInt.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System.Numerics;
  2. using Jint.Runtime;
  3. namespace Jint.Native;
  4. public sealed class JsBigInt : JsValue, IEquatable<JsBigInt>
  5. {
  6. internal readonly BigInteger _value;
  7. public static readonly JsBigInt Zero = new(0);
  8. public static readonly JsBigInt One = new(1);
  9. private static readonly JsBigInt[] _bigIntegerToJsValue;
  10. static JsBigInt()
  11. {
  12. var bigIntegers = new JsBigInt[1024];
  13. for (uint i = 0; i < bigIntegers.Length; i++)
  14. {
  15. bigIntegers[i] = new JsBigInt(i);
  16. }
  17. _bigIntegerToJsValue = bigIntegers;
  18. }
  19. public JsBigInt(BigInteger value) : base(Types.BigInt)
  20. {
  21. _value = value;
  22. }
  23. internal static JsBigInt Create(BigInteger bigInt)
  24. {
  25. var temp = _bigIntegerToJsValue;
  26. if (bigInt >= 0 && bigInt < (uint) temp.Length)
  27. {
  28. return temp[(int) bigInt];
  29. }
  30. return new JsBigInt(bigInt);
  31. }
  32. internal static JsBigInt Create(JsValue value)
  33. {
  34. return value as JsBigInt ?? Create(TypeConverter.ToBigInt(value));
  35. }
  36. public override object ToObject() => _value;
  37. internal override bool ToBoolean() => _value != 0;
  38. public static bool operator ==(JsBigInt a, double b)
  39. {
  40. return TypeConverter.IsIntegralNumber(b) && a._value == (long) b;
  41. }
  42. public static bool operator !=(JsBigInt a, double b)
  43. {
  44. return !(a == b);
  45. }
  46. public override string ToString()
  47. {
  48. return TypeConverter.ToString(_value);
  49. }
  50. protected internal override bool IsLooselyEqual(JsValue value)
  51. {
  52. if (value is JsBigInt bigInt)
  53. {
  54. return Equals(bigInt);
  55. }
  56. if (value is JsNumber number && TypeConverter.IsIntegralNumber(number._value) && _value == new BigInteger(number._value))
  57. {
  58. return true;
  59. }
  60. if (value is JsBoolean b)
  61. {
  62. return b._value && _value == BigInteger.One || !b._value && _value == BigInteger.Zero;
  63. }
  64. if (value is JsString s && TypeConverter.TryStringToBigInt(s.ToString(), out var temp) && temp == _value)
  65. {
  66. return true;
  67. }
  68. if (value.IsObject())
  69. {
  70. return IsLooselyEqual(TypeConverter.ToPrimitive(value, Types.Number));
  71. }
  72. return false;
  73. }
  74. public override bool Equals(object? obj) => Equals(obj as JsBigInt);
  75. public override bool Equals(JsValue? other) => Equals(other as JsBigInt);
  76. public bool Equals(JsBigInt? other)
  77. {
  78. if (ReferenceEquals(null, other))
  79. {
  80. return false;
  81. }
  82. return ReferenceEquals(this, other) || _value == other._value;
  83. }
  84. public override int GetHashCode() => _value.GetHashCode();
  85. }