StringInstance.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using Jint.Native.Object;
  2. using Jint.Runtime;
  3. using Jint.Runtime.Descriptors;
  4. namespace Jint.Native.String
  5. {
  6. public class StringInstance : ObjectInstance, IPrimitiveInstance
  7. {
  8. public StringInstance(Engine engine)
  9. : base(engine)
  10. {
  11. }
  12. public override string Class => "String";
  13. Types IPrimitiveInstance.Type => Types.String;
  14. JsValue IPrimitiveInstance.PrimitiveValue => PrimitiveValue;
  15. public JsValue PrimitiveValue { get; set; }
  16. private static bool IsInt(double d)
  17. {
  18. if (d >= long.MinValue && d <= long.MaxValue)
  19. {
  20. var l = (long) d;
  21. return l >= int.MinValue && l <= int.MaxValue;
  22. }
  23. return false;
  24. }
  25. public override PropertyDescriptor GetOwnProperty(string propertyName)
  26. {
  27. if (propertyName == "Infinity")
  28. {
  29. return PropertyDescriptor.Undefined;
  30. }
  31. var desc = base.GetOwnProperty(propertyName);
  32. if (desc != PropertyDescriptor.Undefined)
  33. {
  34. return desc;
  35. }
  36. var integer = TypeConverter.ToInteger(propertyName);
  37. if (integer == 0 && propertyName != "0" || propertyName != System.Math.Abs(integer).ToString())
  38. {
  39. return PropertyDescriptor.Undefined;
  40. }
  41. var str = PrimitiveValue;
  42. var dIndex = integer;
  43. if (!IsInt(dIndex))
  44. return PropertyDescriptor.Undefined;
  45. var index = (int) dIndex;
  46. var len = str.AsString().Length;
  47. if (len <= index || index < 0)
  48. {
  49. return PropertyDescriptor.Undefined;
  50. }
  51. var resultStr = TypeConverter.ToString(str.AsString()[index]);
  52. return new PropertyDescriptor(resultStr, false, true, false);
  53. }
  54. }
  55. }