JsValueExtensions.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.Runtime.CompilerServices;
  2. using Jint.Native;
  3. using Jint.Runtime;
  4. namespace Jint
  5. {
  6. public static class JsValueExtensions
  7. {
  8. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  9. public static bool AsBoolean(this JsValue value)
  10. {
  11. if (value._type != InternalTypes.Boolean)
  12. {
  13. ThrowWrongTypeException(value, "boolean");
  14. }
  15. return ((JsBoolean) value)._value;
  16. }
  17. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  18. public static double AsNumber(this JsValue value)
  19. {
  20. if (!value.IsNumber())
  21. {
  22. ThrowWrongTypeException(value, "number");
  23. }
  24. return ((JsNumber) value)._value;
  25. }
  26. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  27. internal static int AsInteger(this JsValue value)
  28. {
  29. return (int) ((JsNumber) value)._value;
  30. }
  31. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  32. public static string AsString(this JsValue value)
  33. {
  34. if (!value.IsString())
  35. {
  36. ThrowWrongTypeException(value, "string");
  37. }
  38. return value.ToString();
  39. }
  40. private static void ThrowWrongTypeException(JsValue value, string expectedType)
  41. {
  42. ExceptionHelper.ThrowArgumentException($"Expected {expectedType} but got {value._type}");
  43. }
  44. }
  45. }