diff --git a/tool/net/definitions.lua b/tool/net/definitions.lua index 988e3ba6f..f6fecffda 100644 --- a/tool/net/definitions.lua +++ b/tool/net/definitions.lua @@ -1977,6 +1977,10 @@ function VisualizeControlCodes(str) end ---@nodiscard function Underlong(str) end +--- Generate a uuid_v4 +--- @return string +function UuidV4() end + ---@param x integer ---@return integer # position of first bit set. --- Passing `0` will raise an error. Same as the Intel x86 instruction BSF. diff --git a/tool/net/lfuncs.c b/tool/net/lfuncs.c index 1949f1649..17f9565f2 100644 --- a/tool/net/lfuncs.c +++ b/tool/net/lfuncs.c @@ -72,6 +72,7 @@ #include "third_party/mbedtls/sha512.h" #include "third_party/musl/netdb.h" #include "third_party/zlib/zlib.h" +#include static int Rdpid(void) { #ifdef __x86_64__ @@ -829,6 +830,30 @@ int LuaVisualizeControlCodes(lua_State *L) { return LuaCoder(L, VisualizeControlCodes); } +int LuaUuidV4(lua_State *L) { + char *template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"; + char *uuid = (char *)malloc(strlen(template) + 1); + if (uuid == NULL) { + return NULL; // Memory allocation failed + } + + srand(time(NULL)); + + for (int i = 0; i < strlen(template); i++) { + char c = template[i]; + if (c == 'x') { + uuid[i] = (rand() % 16 < 10) ? (rand() % 10 + '0') : (rand() % 6 + 'a'); + } else if (c == 'y') { + uuid[i] = (rand() % 4 + '8'); + } else { + uuid[i] = c; + } + } + uuid[strlen(template)] = '\0'; + lua_pushfstring(L, uuid); + return 1; +} + static dontinline int LuaHasherImpl(lua_State *L, size_t k, int H(const void *, size_t, uint8_t *)) { size_t n; diff --git a/tool/net/lfuncs.h b/tool/net/lfuncs.h index c5fcf8796..ab82c4e95 100644 --- a/tool/net/lfuncs.h +++ b/tool/net/lfuncs.h @@ -90,6 +90,7 @@ int LuaSleep(lua_State *); int LuaSlurp(lua_State *); int LuaUncompress(lua_State *); int LuaUnderlong(lua_State *); +int LuaUuidV4(lua_State *); int LuaVisualizeControlCodes(lua_State *); void LuaPushUrlView(lua_State *, struct UrlView *); diff --git a/tool/net/redbean.c b/tool/net/redbean.c index e3c741b7a..144e0dcbd 100644 --- a/tool/net/redbean.c +++ b/tool/net/redbean.c @@ -5287,6 +5287,7 @@ static const luaL_Reg kLuaFuncs[] = { {"StoreAsset", LuaStoreAsset}, // {"Uncompress", LuaUncompress}, // {"Underlong", LuaUnderlong}, // + {"UuidV4", LuaUuidV4}, // {"VisualizeControlCodes", LuaVisualizeControlCodes}, // {"Write", LuaWrite}, // {"bin", LuaBin}, //