UuidConstructor.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using Jint.Native;
  2. using Jint.Native.Function;
  3. using Jint.Native.Object;
  4. using Jint.Runtime;
  5. using Jint.Runtime.Descriptors;
  6. using Jint.Runtime.Interop;
  7. namespace Jint.Tests.Runtime.Domain
  8. {
  9. internal sealed class UuidConstructor : FunctionInstance, IConstructor
  10. {
  11. private static readonly JsString _functionName = new JsString("Uuid");
  12. private UuidConstructor(Engine engine) : base(engine, engine.Realm, _functionName)
  13. {
  14. }
  15. private JsValue Parse(JsValue @this, JsValue[] arguments)
  16. {
  17. switch (arguments.At(0))
  18. {
  19. case JsUuid uid:
  20. return Construct(uid);
  21. case JsValue js when Guid.TryParse(js.AsString(), out var res):
  22. return Construct(res);
  23. }
  24. return Undefined;
  25. }
  26. protected internal override ObjectInstance GetPrototypeOf() => _prototype;
  27. internal new ObjectInstance _prototype;
  28. public UuidPrototype PrototypeObject { get; private set; }
  29. public static UuidConstructor CreateUuidConstructor(Engine engine)
  30. {
  31. var obj = new UuidConstructor(engine)
  32. {
  33. // The value of the [[Prototype]] internal property of the Uuid constructor is the Function prototype object
  34. _prototype = engine.Realm.Intrinsics.Function.PrototypeObject
  35. };
  36. obj.PrototypeObject = UuidPrototype.CreatePrototypeObject(engine, obj);
  37. // The initial value of Uuid.prototype is the Date prototype object
  38. obj.SetOwnProperty("prototype", new PropertyDescriptor(obj.PrototypeObject, false, false, false));
  39. engine.SetValue("Uuid", obj);
  40. obj.Configure();
  41. obj.PrototypeObject.Configure();
  42. return obj;
  43. }
  44. protected internal override JsValue Call(JsValue thisObject, JsValue[] arguments) => Construct(arguments, null);
  45. public void Configure()
  46. {
  47. FastAddProperty("parse", new ClrFunctionInstance(Engine, "parse", Parse), true, false, true);
  48. FastAddProperty("Empty", JsUuid.Empty, true, false, true);
  49. }
  50. public UuidInstance Construct(JsUuid uuid) => new UuidInstance(Engine) { PrimitiveValue = uuid, _prototype = PrototypeObject };
  51. public ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) => Construct(Guid.NewGuid());
  52. }
  53. }