ConstraintsOptionsExtensions.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System.Threading;
  2. using Jint.Constraints;
  3. // ReSharper disable once CheckNamespace
  4. namespace Jint;
  5. public static class ConstraintsOptionsExtensions
  6. {
  7. /// <summary>
  8. /// Limits the allowed statement count that can be run as part of the program.
  9. /// </summary>
  10. public static Options MaxStatements(this Options options, int maxStatements = 0)
  11. {
  12. options.WithoutConstraint(x => x is MaxStatementsConstraint);
  13. if (maxStatements > 0 && maxStatements < int.MaxValue)
  14. {
  15. options.Constraint(new MaxStatementsConstraint(maxStatements));
  16. }
  17. return options;
  18. }
  19. /// <summary>
  20. /// Sets constraint based on memory usage in bytes.
  21. /// </summary>
  22. public static Options LimitMemory(this Options options, long memoryLimit)
  23. {
  24. options.WithoutConstraint(x => x is MemoryLimitConstraint);
  25. if (memoryLimit > 0 && memoryLimit < long.MaxValue)
  26. {
  27. options.Constraint(new MemoryLimitConstraint(memoryLimit));
  28. }
  29. return options;
  30. }
  31. /// <summary>
  32. /// Sets constraint based on fixed time interval.
  33. /// </summary>
  34. public static Options TimeoutInterval(this Options options, TimeSpan timeoutInterval)
  35. {
  36. if (timeoutInterval > TimeSpan.Zero && timeoutInterval < TimeSpan.MaxValue)
  37. {
  38. options.Constraint(new TimeConstraint(timeoutInterval));
  39. }
  40. return options;
  41. }
  42. /// <summary>
  43. /// Sets cancellation token to be observed. NOTE that this can be unreliable/imprecise on full framework due to timer logic.
  44. /// </summary>
  45. public static Options CancellationToken(this Options options, CancellationToken cancellationToken)
  46. {
  47. options.WithoutConstraint(x => x is CancellationConstraint);
  48. if (cancellationToken != default)
  49. {
  50. options.Constraint(new CancellationConstraint(cancellationToken));
  51. }
  52. return options;
  53. }
  54. }