JsValueExtensions.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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._type != InternalTypes.String)
  35. {
  36. ThrowWrongTypeException(value, "string");
  37. }
  38. return AsStringWithoutTypeCheck(value);
  39. }
  40. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  41. internal static string AsStringWithoutTypeCheck(this JsValue value)
  42. {
  43. return value.ToString();
  44. }
  45. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  46. public static string AsSymbol(this JsValue value)
  47. {
  48. if (value._type != InternalTypes.Symbol)
  49. {
  50. ThrowWrongTypeException(value, "symbol");
  51. }
  52. return ((JsSymbol) value).ToPropertyKey();
  53. }
  54. private static void ThrowWrongTypeException(JsValue value, string expectedType)
  55. {
  56. ExceptionHelper.ThrowArgumentException($"Expected {expectedType} but got {value._type}");
  57. }
  58. }
  59. }