Add support for gzip compression
This commit is contained in:
1 parent
d886f585f8
commit
e72a271006
1 file changed
+27
-8
@@ -1,6 +1,6 @@
|
||||
use flate2::{
|
||||
Compression,
|
||||
read::{ZlibDecoder, ZlibEncoder},
|
||||
read::{GzDecoder, GzEncoder, ZlibDecoder, ZlibEncoder},
|
||||
};
|
||||
use mlua::{IntoLuaMulti, Lua, LuaString, MultiValue, Result as LuaResult, Value};
|
||||
use std::io::Read;
|
||||
@@ -13,15 +13,28 @@ pub fn inflate(l: &Lua, compressed: LuaString) -> LuaResult<MultiValue> {
|
||||
return (Value::Nil, "Input larger than 128 MiB").into_lua_multi(l);
|
||||
}
|
||||
|
||||
let mut decoder = ZlibDecoder::new(compressed_bytes);
|
||||
let mut decompressed = Vec::new();
|
||||
match decoder.read_to_end(&mut decompressed) {
|
||||
Ok(_) => l.create_string(&decompressed).unwrap().into_lua_multi(l),
|
||||
|
||||
let result = if is_gzip(compressed_bytes) {
|
||||
GzDecoder::new(compressed_bytes).read_to_end(&mut decompressed)
|
||||
} else {
|
||||
ZlibDecoder::new(compressed_bytes).read_to_end(&mut decompressed)
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(_) => l.create_string(&decompressed)?.into_lua_multi(l),
|
||||
Err(e) => (Value::Nil, e.to_string()).into_lua_multi(l),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deflate(l: &Lua, uncompressed: LuaString) -> LuaResult<MultiValue> {
|
||||
fn is_gzip(data: &[u8]) -> bool {
|
||||
data.len() >= 2 && data[0] == 0x1f && data[1] == 0x8b
|
||||
}
|
||||
|
||||
pub fn deflate(
|
||||
l: &Lua,
|
||||
(uncompressed, use_gzip): (LuaString, Option<bool>),
|
||||
) -> LuaResult<MultiValue> {
|
||||
let uncompressed_bytes = &uncompressed.as_bytes()[..];
|
||||
|
||||
// prevent compression of input larger than 128MiB
|
||||
@@ -29,10 +42,16 @@ pub fn deflate(l: &Lua, uncompressed: LuaString) -> LuaResult<MultiValue> {
|
||||
return (Value::Nil, "Input larger than 128 MiB").into_lua_multi(l);
|
||||
}
|
||||
|
||||
let mut encoder = ZlibEncoder::new(uncompressed_bytes, Compression::fast());
|
||||
let mut compressed = Vec::new();
|
||||
match encoder.read_to_end(&mut compressed) {
|
||||
Ok(_) => l.create_string(&compressed).unwrap().into_lua_multi(l),
|
||||
|
||||
let result = if use_gzip.unwrap_or(false) {
|
||||
GzEncoder::new(uncompressed_bytes, Compression::best()).read_to_end(&mut compressed)
|
||||
} else {
|
||||
ZlibEncoder::new(uncompressed_bytes, Compression::best()).read_to_end(&mut compressed)
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(_) => l.create_string(&compressed)?.into_lua_multi(l),
|
||||
Err(e) => (Value::Nil, e.to_string()).into_lua_multi(l),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user