JsValueExtensions.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System.Runtime.CompilerServices;
  2. using Jint.Native;
  3. using Jint.Native.Promise;
  4. using Jint.Runtime;
  5. namespace Jint
  6. {
  7. public static class JsValueExtensions
  8. {
  9. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  10. public static bool AsBoolean(this JsValue value)
  11. {
  12. if (value._type != InternalTypes.Boolean)
  13. {
  14. ThrowWrongTypeException(value, "boolean");
  15. }
  16. return ((JsBoolean) value)._value;
  17. }
  18. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  19. public static double AsNumber(this JsValue value)
  20. {
  21. if (!value.IsNumber())
  22. {
  23. ThrowWrongTypeException(value, "number");
  24. }
  25. return ((JsNumber) value)._value;
  26. }
  27. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  28. internal static int AsInteger(this JsValue value)
  29. {
  30. return (int) ((JsNumber) value)._value;
  31. }
  32. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  33. public static string AsString(this JsValue value)
  34. {
  35. if (!value.IsString())
  36. {
  37. ThrowWrongTypeException(value, "string");
  38. }
  39. return value.ToString();
  40. }
  41. /// <summary>
  42. /// If the value is a Promise
  43. /// 1. If "Fulfilled" returns the value it was fulfilled with
  44. /// 2. If "Rejected" throws "PromiseRejectedException" with the rejection reason
  45. /// 3. If "Pending" throws "InvalidOperationException". Should be called only in "Settled" state
  46. /// Else
  47. /// returns the value intact
  48. /// </summary>
  49. /// <param name="value">value to unwrap</param>
  50. /// <returns>inner value if Promise the value itself otherwise</returns>
  51. public static JsValue UnwrapIfPromise(this JsValue value)
  52. {
  53. if (value is PromiseInstance promise)
  54. {
  55. switch (promise.State)
  56. {
  57. case PromiseState.Pending:
  58. ExceptionHelper.ThrowInvalidOperationException("'UnwrapIfPromise' called before Promise was settled");
  59. return null;
  60. case PromiseState.Fulfilled:
  61. return promise.Value;
  62. case PromiseState.Rejected:
  63. ExceptionHelper.ThrowPromiseRejectedException(promise.Value);
  64. return null;
  65. default:
  66. ExceptionHelper.ThrowArgumentOutOfRangeException();
  67. return null;
  68. }
  69. }
  70. return value;
  71. }
  72. [MethodImpl(MethodImplOptions.NoInlining)]
  73. private static void ThrowWrongTypeException(JsValue value, string expectedType)
  74. {
  75. ExceptionHelper.ThrowArgumentException($"Expected {expectedType} but got {value._type}");
  76. }
  77. }
  78. }