diff --git a/doc/en/scripting.md b/doc/en/scripting.md index b00930f1..c94a26ab 100644 --- a/doc/en/scripting.md +++ b/doc/en/scripting.md @@ -9,9 +9,11 @@ Subsections: - [UI properties and methods](scripting/ui.md) - [Entities and components](scripting/ecs.md) - [Libraries](#) + - [app](scripting/builtins/libapp.md) - [base64](scripting/builtins/libbase64.md) - [bjson, json, toml](scripting/filesystem.md) - [block](scripting/builtins/libblock.md) + - [byteutil](scripting/builtins/libbyteutil.md) - [cameras](scripting/builtins/libcameras.md) - [entities](scripting/builtins/libentities.md) - [file](scripting/builtins/libfile.md) diff --git a/doc/en/scripting/builtins/libbyteutil.md b/doc/en/scripting/builtins/libbyteutil.md new file mode 100644 index 00000000..c0cf72d0 --- /dev/null +++ b/doc/en/scripting/builtins/libbyteutil.md @@ -0,0 +1,70 @@ +# *byteutil* library + +The library provides functions for working with byte arrays represented as tables or Bytearrays. + +```lua +byteutil.pack(format: str, ...) -> Bytearray +byteutil.tpack(format: str, ...) -> table +``` + +Returns a byte array containing the provided values packed according to the format string. The arguments must exactly match the values required by the format. + +The format string consists of special characters and value characters. + +Special characters specify the byte order for the subsequent values: + +| Character | Byte Order | +| --------- | ------------------- | +| `@` | System | +| `=` | System | +| `<` | Little-endian | +| `>` | Big-endian | +| `!` | Network (big-endian)| + + +Value characters describe the type and size. + +| Character | C++ Equivalent | Lua Type | Size | +| --------- | -------------- | -------- | ------- | +| `b` | int8_t | number | 1 byte | +| `B` | uint8_t | number | 1 byte | +| `?` | bool | boolean | 1 byte | +| `h` | int16_t | number | 2 bytes | +| `H` | uint16_t | number | 2 bytes | +| `i` | int32_t | number | 4 bytes | +| `I` | uint32_t | number | 4 bytes | +| `l` | int64_t | number | 8 bytes | +| `L` | uint64_t | number | 8 bytes | + +> [!WARNING] +> Due to the absence of an integer type in Lua for values `l` and `L`, only an output size of 8 bytes is guaranteed; the value may differ from what is expected. + +```lua +byteutil.unpack(format: str, bytes: table|Bytearray) -> ... +``` + +Extracts values ​​from a byte array based on a format string. + +Example: + +```lua +debug.print(byteutil.tpack('>iBH?', -8, 250, 2019, true)) +-- outputs: +-- debug.print( +-- { +-- 255, +-- 255, +-- 255, +-- 248, +-- 250, +-- 7, +-- 227, +-- 1 +-- } +-- ) + +local bytes = byteutil.pack('>iBH?', -8, 250, 2019, true) +print(byteutil.unpack('>iBH?', bytes)) +-- outputs: +-- -8 250 2019 true +``` diff --git a/doc/ru/scripting.md b/doc/ru/scripting.md index 63191ea8..0d880d78 100644 --- a/doc/ru/scripting.md +++ b/doc/ru/scripting.md @@ -9,9 +9,11 @@ - [Свойства и методы UI элементов](scripting/ui.md) - [Сущности и компоненты](scripting/ecs.md) - [Библиотеки](#) + - [app](scripting/builtins/libapp.md) - [base64](scripting/builtins/libbase64.md) - [bjson, json, toml](scripting/filesystem.md) - [block](scripting/builtins/libblock.md) + - [byteutil](scripting/builtins/libbyteutil.md) - [cameras](scripting/builtins/libcameras.md) - [entities](scripting/builtins/libentities.md) - [file](scripting/builtins/libfile.md) diff --git a/doc/ru/scripting/builtins/libbyteutil.md b/doc/ru/scripting/builtins/libbyteutil.md new file mode 100644 index 00000000..2c675594 --- /dev/null +++ b/doc/ru/scripting/builtins/libbyteutil.md @@ -0,0 +1,71 @@ +# Библиотека *byteutil* + +Библиотека предоставляет функции для работы с массивами байт, представленными в виде таблиц или Bytearray. + +```lua +byteutil.pack(format: str, ...) -> Bytearray +byteutil.tpack(format: str, ...) -> table +``` + +Возвращает массив байт, содержащий переданные значения, упакованные в соответствии со строкой формата. Аргументы должны точно соответствовать значениям, требуемым форматом. + +Строка формата состоит из специальных символов и символов значений. + +Специальные символы позволяют указать порядок байт для последующих значений: + +| Символ | Порядок байт | +| ------ | -------------------- | +| `@` | Системный | +| `=` | Системный | +| `<` | Little-endian | +| `>` | Big-endian | +| `!` | Сетевой (big-endian) | + + +Символы значений описывают тип и размер. + +| Символ | Аналог в С++ | Тип Lua | Размер | +| ------ | ------------ | -------- | ------- | +| `b` | int8_t | number | 1 байт | +| `B` | uint8_t | number | 1 байт | +| `?` | bool | boolean | 1 байт | +| `h` | int16_t | number | 2 байта | +| `H` | uint16_t | number | 2 байта | +| `i` | int32_t | number | 4 байта | +| `I` | uint32_t | number | 4 байта | +| `l` | int64_t | number | 8 байта | +| `L` | uint64_t | number | 8 байта | + +> [!WARNING] +> Из-за отсутствия в Lua целочисленного типа для значений `l` и `L` гарантируется +> только выходной размер в 8 байт, значение может отличаться от ожидаемого. + +```lua +byteutil.unpack(format: str, bytes: table|Bytearray) -> ... +``` + +Извлекает значения из массива байт, ориентируясь на строку формата. + +Пример: + +```lua +debug.print(byteutil.tpack('>iBH?', -8, 250, 2019, true)) +-- выводит: +-- debug.print( +-- { +-- 255, +-- 255, +-- 255, +-- 248, +-- 250, +-- 7, +-- 227, +-- 1 +-- } +-- ) + +local bytes = byteutil.pack('>iBH?', -8, 250, 2019, true) +debug.print(byteutil.unpack('>iBH?', bytes)) +-- выводит: +-- -8 250 2019 true +``` diff --git a/src/logic/scripting/lua/libs/libbyteutil.cpp b/src/logic/scripting/lua/libs/libbyteutil.cpp index e4b20d8c..a757712f 100644 --- a/src/logic/scripting/lua/libs/libbyteutil.cpp +++ b/src/logic/scripting/lua/libs/libbyteutil.cpp @@ -11,6 +11,7 @@ static size_t calc_size(const char* format) { switch (format[i]) { case 'b': case 'B': + case '?': outSize += 1; break; case 'h': @@ -43,8 +44,14 @@ static int pack(lua::State* L, const char* format, bool usetable) { for (int i = 0; format[i]; i++) { switch (format[i]) { case 'b': + builder.put(lua::tointeger(L, index)); + break; + case 'B': builder.put(lua::tointeger(L, index) & 0xFF); break; + case '?': + builder.put(lua::toboolean(L, index) ? 1 : 0); + break; case 'h': builder.putInt16(lua::tointeger(L, index), bigEndian); break; @@ -102,6 +109,7 @@ static int count_elements(const char* format) { switch (format[i]) { case 'b': case 'B': + case '?': case 'h': case 'H': case 'i': @@ -126,13 +134,17 @@ static int l_unpack(lua::State* L) { ByteReader reader(bytes); bool bigEndian = false; - int index = 1; - lua::createtable(L, count, 0); for (size_t i = 0; format[i]; i++) { switch (format[i]) { case 'b': lua::pushinteger(L, reader.get()); break; + case 'B': + lua::pushinteger(L, reader.get() & 0xFF); + break; + case '?': + lua::pushboolean(L, reader.get() != 0); + break; case 'h': lua::pushinteger(L, reader.getInt16(bigEndian)); break; @@ -171,9 +183,8 @@ static int l_unpack(lua::State* L) { default: continue; } - lua::rawseti(L, index++); } - return 1; + return count; } static int l_pack(lua::State* L) {