UuidConstructor.cs 2.4 KB

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