UuidConstructor.cs 2.4 KB

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