JsValueExtensions.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. return promise.State switch
  56. {
  57. PromiseState.Pending => ExceptionHelper.ThrowInvalidOperationException<JsValue>(
  58. "'UnwrapIfPromise' called before Promise was settled"),
  59. PromiseState.Fulfilled => promise.Value,
  60. PromiseState.Rejected => ExceptionHelper.ThrowPromiseRejectedException<JsValue>(promise.Value),
  61. _ => ExceptionHelper.ThrowArgumentOutOfRangeException<JsValue>()
  62. };
  63. }
  64. return value;
  65. }
  66. private static void ThrowWrongTypeException(JsValue value, string expectedType)
  67. {
  68. ExceptionHelper.ThrowArgumentException($"Expected {expectedType} but got {value._type}");
  69. }
  70. }
  71. }