Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include Buffer Support in the Standard Library #148

Merged
merged 21 commits into from
Apr 20, 2024
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
caecf9e
feat: buffer support for @lune/fs
CompeyDev Jan 20, 2024
a1b1134
feat(types + tests): updated types and tests for @lune/fs
CompeyDev Jan 21, 2024
746b1cc
feat(util + net): common buffer util & buffer support for @lune/net
CompeyDev Jan 21, 2024
185fb6a
feat(types): update @lune/net types to reflect buffer support
CompeyDev Jan 21, 2024
a97a7cf
Merge branch 'main' into feature/std-buffer
CompeyDev Mar 11, 2024
652e71b
merge: 'main' -> feature/std-buffer
CompeyDev Apr 11, 2024
8e38440
Merge branch 'main' into feature/std-buffer
CompeyDev Apr 11, 2024
a35c7fc
Merge branch 'main' into feature/std-buffer
CompeyDev Apr 19, 2024
716e8aa
refactor(net, fs): accept buffers and strings instead of just buffers
CompeyDev Apr 19, 2024
d3d1a4d
chore(tests, types): reflect changes in https://github.com/lune-org/l…
CompeyDev Apr 19, 2024
89d66a9
feat: accept and return buffers in @lune/net and @lune/serde
CompeyDev Apr 20, 2024
ef4fe6e
fix: handle buffers in compress_decompress too
CompeyDev Apr 20, 2024
8dbe532
feat: return buffers for fs too
CompeyDev Apr 20, 2024
39b8c89
fix: remove buffer returns, only accept buffers
CompeyDev Apr 20, 2024
d1d7cb7
fix(net, serde): fix serde not accepting non `BString` types
CompeyDev Apr 20, 2024
77edb89
fix(net, serde): update types to reflect buffer support
CompeyDev Apr 20, 2024
7a85117
fix(types): revert nullable body to a plain string
CompeyDev Apr 20, 2024
2f50d67
chore(tests): include unit tests with buffer arguments
CompeyDev Apr 20, 2024
3337e0e
chore(tests): include explicit type for `operationName`
CompeyDev Apr 20, 2024
2000cca
chore(types): revert inaccurate type
CompeyDev Apr 20, 2024
92ecb99
Merge branch 'main' into feature/std-buffer
filiptibell Apr 20, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ path-clean = "1.0"
pathdiff = "0.2"
pin-project = "1.0"
urlencoding = "2.1"
bstr = "1.9.1"

### RUNTIME

Expand All @@ -85,7 +86,7 @@ tokio = { version = "1.24", features = ["full", "tracing"] }
os_str_bytes = { version = "7.0", features = ["conversions"] }

mlua-luau-scheduler = { version = "0.0.2" }
mlua = { version = "0.9.6", features = [
mlua = { version = "0.9.7", features = [
"luau",
"luau-jit",
"async",
Expand Down
6 changes: 4 additions & 2 deletions src/lune/builtins/fs/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::io::ErrorKind as IoErrorKind;
use std::path::{PathBuf, MAIN_SEPARATOR};

use bstr::{BString, ByteSlice};
use mlua::prelude::*;
use tokio::fs;

Expand Down Expand Up @@ -32,6 +33,7 @@ pub fn create(lua: &Lua) -> LuaResult<LuaTable> {

async fn fs_read_file(lua: &Lua, path: String) -> LuaResult<LuaString> {
let bytes = fs::read(&path).await.into_lua_err()?;

lua.create_string(bytes)
}

Expand Down Expand Up @@ -64,8 +66,8 @@ async fn fs_read_dir(_: &Lua, path: String) -> LuaResult<Vec<String>> {
Ok(dir_strings_no_prefix)
}

async fn fs_write_file(_: &Lua, (path, contents): (String, LuaString<'_>)) -> LuaResult<()> {
fs::write(&path, &contents.as_bytes()).await.into_lua_err()
async fn fs_write_file(_: &Lua, (path, contents): (String, BString)) -> LuaResult<()> {
fs::write(&path, contents.as_bytes()).await.into_lua_err()
}

async fn fs_write_dir(_: &Lua, path: String) -> LuaResult<()> {
Expand Down
4 changes: 3 additions & 1 deletion src/lune/builtins/net/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::{
net::{IpAddr, Ipv4Addr},
};

use bstr::{BString, ByteSlice};
use mlua::prelude::*;

use reqwest::Method;
Expand Down Expand Up @@ -107,10 +108,11 @@ impl FromLua<'_> for RequestConfig {
Err(_) => HashMap::new(),
};
// Extract body
let body = match tab.get::<_, LuaString>("body") {
let body = match tab.get::<_, BString>("body") {
Ok(config_body) => Some(config_body.as_bytes().to_owned()),
Err(_) => None,
};

// Convert method string into proper enum
let method = method.trim().to_ascii_uppercase();
let method = match method.as_ref() {
Expand Down
3 changes: 2 additions & 1 deletion src/lune/builtins/net/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![allow(unused_variables)]

use bstr::BString;
use mlua::prelude::*;
use mlua_luau_scheduler::LuaSpawnExt;

Expand Down Expand Up @@ -45,7 +46,7 @@ fn net_json_encode<'lua>(
.serialize_to_string(lua, val)
}

fn net_json_decode<'lua>(lua: &'lua Lua, json: LuaString<'lua>) -> LuaResult<LuaValue<'lua>> {
fn net_json_decode<'lua>(lua: &'lua Lua, json: BString) -> LuaResult<LuaValue<'lua>> {
EncodeDecodeConfig::from(EncodeDecodeFormat::Json).deserialize_from_string(lua, json)
}

Expand Down
3 changes: 2 additions & 1 deletion src/lune/builtins/net/server/response.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::str::FromStr;

use bstr::{BString, ByteSlice};
use http_body_util::Full;
use hyper::{
body::Bytes,
Expand Down Expand Up @@ -56,7 +57,7 @@ impl FromLua<'_> for LuaResponse {
LuaValue::Table(t) => {
let status: Option<u16> = t.get("status")?;
let headers: Option<LuaTable> = t.get("headers")?;
let body: Option<LuaString> = t.get("body")?;
let body: Option<BString> = t.get("body")?;

let mut headers_map = HeaderMap::new();
if let Some(headers) = headers {
Expand Down
3 changes: 2 additions & 1 deletion src/lune/builtins/net/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::sync::{
Arc,
};

use bstr::{BString, ByteSlice};
use mlua::prelude::*;

use futures_util::{
Expand Down Expand Up @@ -160,7 +161,7 @@ where

methods.add_async_method(
"send",
|_, this, (string, as_binary): (LuaString, Option<bool>)| async move {
|_, this, (string, as_binary): (BString, Option<bool>)| async move {
this.send(if as_binary.unwrap_or_default() {
WsMessage::Binary(string.as_bytes().to_vec())
} else {
Expand Down
3 changes: 2 additions & 1 deletion src/lune/builtins/serde/encode_decode.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use bstr::{BString, ByteSlice};
use mlua::prelude::*;

use serde_json::Value as JsonValue;
Expand Down Expand Up @@ -89,7 +90,7 @@ impl EncodeDecodeConfig {
pub fn deserialize_from_string<'lua>(
self,
lua: &'lua Lua,
string: LuaString<'lua>,
string: BString,
) -> LuaResult<LuaValue<'lua>> {
let bytes = string.as_bytes();
match self.format {
Expand Down
7 changes: 4 additions & 3 deletions src/lune/builtins/serde/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use bstr::BString;
use mlua::prelude::*;

pub(super) mod compress_decompress;
Expand Down Expand Up @@ -27,23 +28,23 @@ fn serde_encode<'lua>(

fn serde_decode<'lua>(
lua: &'lua Lua,
(format, str): (EncodeDecodeFormat, LuaString<'lua>),
(format, str): (EncodeDecodeFormat, BString),
) -> LuaResult<LuaValue<'lua>> {
let config = EncodeDecodeConfig::from(format);
config.deserialize_from_string(lua, str)
}

async fn serde_compress<'lua>(
lua: &'lua Lua,
(format, str): (CompressDecompressFormat, LuaString<'lua>),
(format, str): (CompressDecompressFormat, BString),
) -> LuaResult<LuaString<'lua>> {
let bytes = compress(format, str).await?;
lua.create_string(bytes)
}

async fn serde_decompress<'lua>(
lua: &'lua Lua,
(format, str): (CompressDecompressFormat, LuaString<'lua>),
(format, str): (CompressDecompressFormat, BString),
) -> LuaResult<LuaString<'lua>> {
let bytes = decompress(format, str).await?;
lua.create_string(bytes)
Expand Down
6 changes: 3 additions & 3 deletions tests/fs/copy.luau
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,15 @@ assert(fs.isFile(TEMP_ROOT_PATH_2 .. "/foo/buzz"), "Missing copied file - root/f
-- Make sure the copied files are correct

assert(
fs.readFile(TEMP_ROOT_PATH_2 .. "/foo/bar/baz") == utils.binaryBlob,
fs.readFile(TEMP_ROOT_PATH_2 .. "/foo/bar/baz") == buffer.tostring(utils.binaryBlob),
"Invalid copied file - root/foo/bar/baz"
)
assert(
fs.readFile(TEMP_ROOT_PATH_2 .. "/foo/fizz") == utils.binaryBlob,
fs.readFile(TEMP_ROOT_PATH_2 .. "/foo/fizz") == buffer.tostring(utils.binaryBlob),
"Invalid copied file - root/foo/fizz"
)
assert(
fs.readFile(TEMP_ROOT_PATH_2 .. "/foo/buzz") == utils.binaryBlob,
fs.readFile(TEMP_ROOT_PATH_2 .. "/foo/buzz") == buffer.tostring(utils.binaryBlob),
"Invalid copied file - root/foo/buzz"
)

Expand Down
4 changes: 3 additions & 1 deletion tests/fs/files.luau
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@ fs.writeDir(TEMP_ROOT_PATH)

-- Write both of our files

-- binaryBlob is of type buffer to make sure fs.writeFile
-- works with both strings and buffers
fs.writeFile(TEMP_ROOT_PATH .. "/test_binary", utils.binaryBlob)
fs.writeFile(TEMP_ROOT_PATH .. "/test_json.json", utils.jsonBlob)

-- Make sure reading the file we just
-- wrote gets us back the original strings

assert(
fs.readFile(TEMP_ROOT_PATH .. "/test_binary") == utils.binaryBlob,
fs.readFile(TEMP_ROOT_PATH .. "/test_binary") == buffer.tostring(utils.binaryBlob),
"Binary file round-trip resulted in different strings"
)

Expand Down
2 changes: 1 addition & 1 deletion tests/fs/metadata.luau
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ assert(metaFile.kind == "file", "File metadata kind was invalid")

local metaBefore = fs.metadata(TEMP_FILE_PATH)
task.wait(1)
fs.writeFile(TEMP_FILE_PATH, utils.binaryBlob .. "\n")
fs.writeFile(TEMP_FILE_PATH, buffer.tostring(utils.binaryBlob) .. "\n")
local metaAfter = fs.metadata(TEMP_FILE_PATH)

assert(
Expand Down
2 changes: 1 addition & 1 deletion tests/fs/move.luau
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ fs.move("bin/move_test_json.json", "bin/moved_test_json.json")
-- wrote gets us back the original strings

assert(
fs.readFile("bin/moved_test_binary") == utils.binaryBlob,
fs.readFile("bin/moved_test_binary") == buffer.tostring(utils.binaryBlob),
"Binary file round-trip resulted in different strings"
)

Expand Down
2 changes: 1 addition & 1 deletion tests/fs/utils.luau
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ local jsonBlob = serde.encode("json", {
-- Return testing data and utils

return {
binaryBlob = binaryBlob,
binaryBlob = buffer.fromstring(binaryBlob),
jsonBlob = jsonBlob,
}
4 changes: 3 additions & 1 deletion tests/net/socket/wss_rw.luau
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ end)

task.wait(1)

socket.send('{"op":1,"d":null}')
local payload = '{"op":1,"d":null}'
socket.send(payload)
socket.send(buffer.fromstring(payload))
socket.close(1000)

task.cancel(delayedThread)
Expand Down
79 changes: 35 additions & 44 deletions tests/serde/compression/files.luau
Original file line number Diff line number Diff line change
Expand Up @@ -33,69 +33,60 @@ local TESTS: { Test } = {
}

local failed = false
for _, test in TESTS do
local source = fs.readFile(test.Source)
local target = fs.readFile(test.Target)

local success, compressed = pcall(serde.compress, test.Format, source)
local function testOperation(
operationName: "Compress" | "Decompress",
operation: (
format: serde.CompressDecompressFormat,
s: buffer | string
) -> string,
format: serde.CompressDecompressFormat,
source: string | buffer,
target: string
)
local success, res = pcall(operation, format, source)
if not success then
stdio.ewrite(
string.format(
"Compressing source using '%s' format threw an error!\n%s",
tostring(test.Format),
tostring(compressed)
"%sing source using '%s' format threw an error!\n%s",
operationName,
tostring(format),
tostring(res)
)
)
failed = true
continue
elseif compressed ~= target then
elseif res ~= target then
stdio.ewrite(
string.format(
"Compressing source using '%s' format did not produce target!\n",
tostring(test.Format)
"%sing source using '%s' format did not produce target!\n",
operationName,
tostring(format)
)
)
stdio.ewrite(
string.format(
"Compressed (%d chars long):\n%s\nTarget (%d chars long):\n%s\n\n",
#compressed,
tostring(compressed),
"%sed (%d chars long):\n%s\nTarget (%d chars long):\n%s\n\n",
operationName,
#res,
tostring(res),
#target,
tostring(target)
)
)
failed = true
continue
end
end

local success2, decompressed = pcall(serde.decompress, test.Format, target)
if not success2 then
stdio.ewrite(
string.format(
"Decompressing source using '%s' format threw an error!\n%s",
tostring(test.Format),
tostring(decompressed)
)
)
failed = true
continue
elseif decompressed ~= source then
stdio.ewrite(
string.format(
"Decompressing target using '%s' format did not produce source!\n",
tostring(test.Format)
)
)
stdio.ewrite(
string.format(
"Decompressed (%d chars long):\n%s\n\n",
#decompressed,
tostring(decompressed)
)
)
failed = true
continue
end
for _, test in TESTS do
local source = fs.readFile(test.Source)
local target = fs.readFile(test.Target)

-- Compression
testOperation("Compress", serde.compress, test.Format, source, target)
testOperation("Compress", serde.compress, test.Format, buffer.fromstring(source), target)

-- Decompression
testOperation("Decompress", serde.decompress, test.Format, target, source)
testOperation("Decompress", serde.decompress, test.Format, buffer.fromstring(target), source)
end

if failed then
Expand Down
2 changes: 1 addition & 1 deletion types/fs.luau
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ end
@param path The path of the file
@param contents The contents of the file
]=]
function fs.writeFile(path: string, contents: string) end
function fs.writeFile(path: string, contents: buffer | string) end

--[=[
@within FS
Expand Down
Loading
Loading