12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- using System.Runtime.CompilerServices;
- using Jint.Native;
- using Jint.Runtime;
- namespace Jint
- {
- public static class JsValueExtensions
- {
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static bool AsBoolean(this JsValue value)
- {
- if (value._type != InternalTypes.Boolean)
- {
- ThrowWrongTypeException(value, "boolean");
- }
- return ((JsBoolean) value)._value;
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static double AsNumber(this JsValue value)
- {
- if (!value.IsNumber())
- {
- ThrowWrongTypeException(value, "number");
- }
- return ((JsNumber) value)._value;
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal static int AsInteger(this JsValue value)
- {
- return (int) ((JsNumber) value)._value;
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static string AsString(this JsValue value)
- {
- if (value._type != InternalTypes.String)
- {
- ThrowWrongTypeException(value, "string");
- }
- return AsStringWithoutTypeCheck(value);
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal static string AsStringWithoutTypeCheck(this JsValue value)
- {
- return value.ToString();
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static string AsSymbol(this JsValue value)
- {
- if (value._type != InternalTypes.Symbol)
- {
- ThrowWrongTypeException(value, "symbol");
- }
- return ((JsSymbol) value).ToPropertyKey();
- }
- private static void ThrowWrongTypeException(JsValue value, string expectedType)
- {
- ExceptionHelper.ThrowArgumentException($"Expected {expectedType} but got {value._type}");
- }
- }
- }
|