Browse Source

Add: bit32.lrotate/rrotate

AnnulusGames 1 year ago
parent
commit
f0666d43ba

+ 31 - 0
src/Lua/Standard/Bitwise/LRotateFunciton.cs

@@ -0,0 +1,31 @@
+namespace Lua.Standard.Bitwise;
+
+public sealed class LRotateFunction : LuaFunction
+{
+    public override string Name => "lrotate";
+    public static readonly LRotateFunction Instance = new();
+
+    protected override ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
+    {
+        var x = context.GetArgument<double>(0);
+        var disp = context.GetArgument<double>(1);
+
+        LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.State, this, 1, x);
+        LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.State, this, 2, disp);
+
+        var v = Bit32Helper.ToInt32(x);
+        var a = ((int)disp) % 32;
+
+        if (a < 0)
+        {
+            v = (v >> (-a)) | (v << (32 + a));
+        }
+        else
+        {
+            v = (v << a) | (v >> (32 - a));
+        }
+
+        buffer.Span[0] = v;
+        return new(1);
+    }
+}

+ 31 - 0
src/Lua/Standard/Bitwise/RRotateFunction.cs

@@ -0,0 +1,31 @@
+namespace Lua.Standard.Bitwise;
+
+public sealed class RRotateFunction : LuaFunction
+{
+    public override string Name => "rrotate";
+    public static readonly RRotateFunction Instance = new();
+
+    protected override ValueTask<int> InvokeAsyncCore(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
+    {
+        var x = context.GetArgument<double>(0);
+        var disp = context.GetArgument<double>(1);
+
+        LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.State, this, 1, x);
+        LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.State, this, 2, disp);
+
+        var v = Bit32Helper.ToInt32(x);
+        var a = ((int)disp) % 32;
+
+        if (a < 0)
+        {
+            v = (v << (-a)) | (v >> (32 + a));
+        }
+        else
+        {
+            v = (v >> a) | (v << (32 - a));
+        }
+
+        buffer.Span[0] = v;
+        return new(1);
+    }
+}

+ 2 - 0
src/Lua/Standard/OpenLibExtensions.cs

@@ -107,7 +107,9 @@ public static class OpenLibExtensions
         BtestFunction.Instance,
         BxorFunction.Instance,
         ExtractFunction.Instance,
+        LRotateFunction.Instance,
         ReplaceFunction.Instance,
+        RRotateFunction.Instance,
     ];
 
     public static void OpenBasicLibrary(this LuaState state)