From e34b0160f185b61a5f5411a9b198421a0387efae Mon Sep 17 00:00:00 2001 From: Dekkonot Date: Mon, 16 Oct 2023 17:34:40 -0700 Subject: [PATCH] Add normal implementation of bit32.byteswap --- Analysis/src/EmbeddedBuiltinDefinitions.cpp | 1 + VM/src/lbitlib.cpp | 13 +++++++++++++ docs/_pages/library.md | 6 ++++++ 3 files changed, 20 insertions(+) diff --git a/Analysis/src/EmbeddedBuiltinDefinitions.cpp b/Analysis/src/EmbeddedBuiltinDefinitions.cpp index 65b04d62..dd2a5d19 100644 --- a/Analysis/src/EmbeddedBuiltinDefinitions.cpp +++ b/Analysis/src/EmbeddedBuiltinDefinitions.cpp @@ -21,6 +21,7 @@ declare bit32: { replace: (n: number, v: number, field: number, width: number?) -> number, countlz: (n: number) -> number, countrz: (n: number) -> number, + byteswap: (n: number) -> number, } declare math: { diff --git a/VM/src/lbitlib.cpp b/VM/src/lbitlib.cpp index 47445b80..65572501 100644 --- a/VM/src/lbitlib.cpp +++ b/VM/src/lbitlib.cpp @@ -5,6 +5,8 @@ #include "lcommon.h" #include "lnumutils.h" +LUAU_FASTFLAG(LuauBit32Byteswap) + #define ALLONES ~0u #define NBITS int(8 * sizeof(unsigned)) @@ -210,6 +212,16 @@ static int b_countrz(lua_State* L) return 1; } +static int b_swap(lua_State* L) +{ + LUAU_ASSERT(FFlag::LuauBit32Byteswap); + b_uint n = luaL_checkunsigned(L, 1); + n = ((n >> 24) & 0xff) | ((n << 8) & 0xff0000) | ((n >> 8) & 0xff00) | ((n << 24) & 0xff000000); + + lua_pushunsigned(L, n); + return 1; +} + static const luaL_Reg bitlib[] = { {"arshift", b_arshift}, {"band", b_and}, @@ -225,6 +237,7 @@ static const luaL_Reg bitlib[] = { {"rshift", b_rshift}, {"countlz", b_countlz}, {"countrz", b_countrz}, + {"byteswap", b_swap}, {NULL, NULL}, }; diff --git a/docs/_pages/library.md b/docs/_pages/library.md index d6d1bc7f..8633b332 100644 --- a/docs/_pages/library.md +++ b/docs/_pages/library.md @@ -728,6 +728,12 @@ function bit32.countrz(n: number): number Returns the number of consecutive zero bits in the 32-bit representation of `n` starting from the right-most (least significant) bit. Returns 32 if `n` is zero. +``` +function bit32.byteswap(n: number): number +``` + +Returns `n` with the order of the bytes swappped. + ## utf8 library Strings in Luau can contain arbitrary bytes; however, in many applications strings representing text contain UTF8 encoded data by convention, that can be inspected and manipulated using `utf8` library.