diff --git a/src/pob/api/compression.rs b/src/pob/api/compression.rs index 6e2badc..d4ed633 100644 --- a/src/pob/api/compression.rs +++ b/src/pob/api/compression.rs @@ -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 { 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 { +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), +) -> LuaResult { 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 { 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), } }