JsValueExtensions.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 != Types.Boolean)
  12. {
  13. ExceptionHelper.ThrowArgumentException($"Expected boolean but got {value._type}");
  14. }
  15. return ((JsBoolean) value)._value;
  16. }
  17. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  18. public static double AsNumber(this JsValue value)
  19. {
  20. if (value._type != Types.Number)
  21. {
  22. ExceptionHelper.ThrowArgumentException($"Expected number but got {value._type}");
  23. }
  24. return ((JsNumber) value)._value;
  25. }
  26. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  27. public static string AsString(this JsValue value)
  28. {
  29. if (value._type != Types.String)
  30. {
  31. ExceptionHelper.ThrowArgumentException($"Expected string but got {value._type}");
  32. }
  33. return AsStringWithoutTypeCheck(value);
  34. }
  35. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  36. internal static string AsStringWithoutTypeCheck(this JsValue value)
  37. {
  38. return value.ToString();
  39. }
  40. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  41. public static string AsSymbol(this JsValue value)
  42. {
  43. if (value._type != Types.Symbol)
  44. {
  45. ExceptionHelper.ThrowArgumentException($"Expected symbol but got {value._type}");
  46. }
  47. return ((JsSymbol) value)._value;
  48. }
  49. }
  50. }