Browse Source

Add: bit32.lshift/rshift

AnnulusGames 1 year ago
parent
commit
e4aeb4e990

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

@@ -0,0 +1,31 @@
+namespace Lua.Standard.Bitwise;
+
+public sealed class LShiftFunction : LuaFunction
+{
+    public override string Name => "lshift";
+    public static readonly LShiftFunction 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;
+
+        if (a < 0)
+        {
+            v >>= -a;
+        }
+        else
+        {
+            v <<= a;
+        }
+
+        buffer.Span[0] = v;
+        return new(1);
+    }
+}

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

@@ -0,0 +1,31 @@
+namespace Lua.Standard.Bitwise;
+
+public sealed class RShiftFunction : LuaFunction
+{
+    public override string Name => "rshift";
+    public static readonly RShiftFunction 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;
+
+        if (a < 0)
+        {
+            v <<= -a;
+        }
+        else
+        {
+            v >>= a;
+        }
+
+        buffer.Span[0] = v;
+        return new(1);
+    }
+}

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

@@ -108,8 +108,10 @@ public static class OpenLibExtensions
         BxorFunction.Instance,
         BxorFunction.Instance,
         ExtractFunction.Instance,
         ExtractFunction.Instance,
         LRotateFunction.Instance,
         LRotateFunction.Instance,
+        LShiftFunction.Instance,
         ReplaceFunction.Instance,
         ReplaceFunction.Instance,
         RRotateFunction.Instance,
         RRotateFunction.Instance,
+        RShiftFunction.Instance,
     ];
     ];
 
 
     public static void OpenBasicLibrary(this LuaState state)
     public static void OpenBasicLibrary(this LuaState state)