ExtractFunction.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. namespace Lua.Standard.Bitwise;
  2. public sealed class ExtractFunction : LuaFunction
  3. {
  4. public override string Name => "extract";
  5. public static readonly ExtractFunction Instance = new();
  6. protected override ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  7. {
  8. var arg0 = context.GetArgument<double>(0);
  9. var arg1 = context.GetArgument<double>(1);
  10. var arg2 = context.HasArgument(2)
  11. ? context.GetArgument<double>(2)
  12. : 1;
  13. LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.State, this, 1, arg0);
  14. LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.State, this, 2, arg1);
  15. LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.State, this, 3, arg2);
  16. var n = Bit32Helper.ToUInt32(arg0);
  17. var field = (int)arg1;
  18. var width = (int)arg2;
  19. Bit32Helper.ValidateFieldAndWidth(context.State, this, 2, field, width);
  20. if (field == 0 && width == 32)
  21. {
  22. buffer.Span[0] = n;
  23. }
  24. else
  25. {
  26. var mask = (uint)((1 << width) - 1);
  27. buffer.Span[0] = (n >> field) & mask;
  28. }
  29. return new(1);
  30. }
  31. }