Browse Source

Fix: extract

AnnulusGames 1 year ago
parent
commit
1305ccceb8

+ 3 - 20
src/Lua/Standard/Bitwise/Bit32Helper.cs

@@ -4,16 +4,6 @@ namespace Lua.Standard.Bitwise;
 
 internal static class Bit32Helper
 {
-    static readonly uint[] Masks = [
-        0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF,
-        0x1FF, 0x3FF, 0x7FF, 0xFFF,
-        0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF,
-        0x1FFFF, 0x3FFFF, 0x7FFFF, 0xFFFFF,
-        0x1FFFFF, 0x3FFFFF, 0x7FFFFF, 0xFFFFFF,
-        0x1FFFFFF, 0x3FFFFFF, 0x7FFFFFF, 0xFFFFFFF,
-        0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF,
-    ];
-
     static readonly double Bit32 = 4294967296;
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -28,19 +18,12 @@ internal static class Bit32Helper
         return (int)(long)Math.IEEERemainder(d, Bit32);
     }
 
-    public static uint GetNBitMask(int bits)
-    {
-        if (bits <= 0) return 0;
-        if (bits >= 32) return Masks[31];
-        return Masks[bits - 1];
-    }
-
-    public static void ValidateFieldAndWidth(LuaState state, LuaFunction function, int argumentId, int pos, int width)
+    public static void ValidateFieldAndWidth(LuaState state, LuaFunction function, int argumentId, int field, int width)
     {
-        if (pos > 31 || (pos + width) > 31)
+        if (field > 31 || (field + width) > 32)
             throw new LuaRuntimeException(state.GetTraceback(), "trying to access non-existent bits");
 
-        if (pos < 0)
+        if (field < 0)
             throw new LuaRuntimeException(state.GetTraceback(), $"bad argument #{argumentId} to '{function.Name}' (field cannot be negative)");
 
         if (width <= 0)

+ 11 - 3
src/Lua/Standard/Bitwise/ExtractFunction.cs

@@ -17,14 +17,22 @@ public sealed class ExtractFunction : LuaFunction
         LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.State, this, 2, arg1);
         LuaRuntimeException.ThrowBadArgumentIfNumberIsNotInteger(context.State, this, 3, arg2);
 
-        var n = (int)arg0;
+        var n = Bit32Helper.ToUInt32(arg0);
         var field = (int)arg1;
         var width = (int)arg2;
 
         Bit32Helper.ValidateFieldAndWidth(context.State, this, 2, field, width);
+        
+        if (field == 0 && width == 32)
+        {
+            buffer.Span[0] = n;
+        }
+        else
+        {
+            var mask = (uint)((1 << width) - 1);
+            buffer.Span[0] = (n >> field) & mask;
+        }
 
-        var result = (n >> field) & Bit32Helper.GetNBitMask(width);
-        buffer.Span[0] = result;
         return new(1);
     }
 }

+ 1 - 1
src/Lua/Standard/Bitwise/ReplaceFunction.cs

@@ -26,7 +26,7 @@ public sealed class ReplaceFunction : LuaFunction
 
         Bit32Helper.ValidateFieldAndWidth(context.State, this, 2, field, width);
 
-        var mask = Bit32Helper.GetNBitMask(width) << field;
+        var mask = (uint)((1 << width) - 1);
         n &= ~mask;
         v &= mask;
         n |= v;