StringInstance.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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
  13. {
  14. get
  15. {
  16. return "String";
  17. }
  18. }
  19. Types IPrimitiveInstance.Type
  20. {
  21. get { return Types.String; }
  22. }
  23. JsValue IPrimitiveInstance.PrimitiveValue
  24. {
  25. get { return PrimitiveValue; }
  26. }
  27. public JsValue PrimitiveValue { get; set; }
  28. private static bool IsInt(double d)
  29. {
  30. if (d >= long.MinValue && d <= long.MaxValue)
  31. {
  32. var l = (long)d;
  33. return l >= int.MinValue && l <= int.MaxValue;
  34. }
  35. else
  36. return false;
  37. }
  38. public override PropertyDescriptor GetOwnProperty(string propertyName)
  39. {
  40. if(propertyName == "Infinity")
  41. return PropertyDescriptor.Undefined;
  42. var desc = base.GetOwnProperty(propertyName);
  43. if (desc != PropertyDescriptor.Undefined)
  44. {
  45. return desc;
  46. }
  47. if (propertyName != System.Math.Abs(TypeConverter.ToInteger(propertyName)).ToString())
  48. {
  49. return PropertyDescriptor.Undefined;
  50. }
  51. var str = PrimitiveValue;
  52. var dIndex = TypeConverter.ToInteger(propertyName);
  53. if(!IsInt(dIndex))
  54. return PropertyDescriptor.Undefined;
  55. var index = (int)dIndex;
  56. var len = str.AsString().Length;
  57. if (len <= index || index < 0)
  58. {
  59. return PropertyDescriptor.Undefined;
  60. }
  61. var resultStr = str.AsString()[index].ToString();
  62. return new PropertyDescriptor(new JsValue(resultStr), false, true, false);
  63. }
  64. }
  65. }