UuidConstructor.cs 2.2 KB

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