From 65bd5c222376eade21531b04d14ee9c9b8edae7e Mon Sep 17 00:00:00 2001 From: dAxpeDDa Date: Sat, 6 Aug 2022 20:25:23 +0200 Subject: [PATCH] Replace GZIP compression with Brotli --- Cargo.toml | 2 +- src/server.rs | 6 +++--- src/wasm_bindgen.rs | 16 +++++----------- 3 files changed, 9 insertions(+), 15 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 3e2a12f..4f52c44 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,5 +22,5 @@ tokio = { version = "1.11", default-features = false, features = ["rt-multi-thre tower-http = { version = "0.3", features = ["fs", "set-header", "trace"] } tower = "0.4" fastrand = "1.5" -flate2 = "1.0" +brotli = { version = "3", default-features = false, features = ["std"]} rcgen = { version = "0.9", default-features = false } diff --git a/src/server.rs b/src/server.rs index 8af4abe..9c3c999 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1,10 +1,10 @@ use std::net::SocketAddr; -use axum::headers::{ContentEncoding, HeaderName}; +use axum::headers::HeaderName; use axum::http::{HeaderValue, StatusCode}; use axum::response::{Html, IntoResponse, Response}; use axum::routing::{get, get_service}; -use axum::{Router, TypedHeader}; +use axum::Router; use axum_server::tls_rustls::RustlsConfig; use tower::ServiceBuilder; use tower_http::services::ServeDir; @@ -44,7 +44,7 @@ pub async fn run_server(options: Options, output: WasmBindgenOutput) -> Result<( let serve_dir = get_service(ServeDir::new(".")).handle_error(internal_server_error); let serve_wasm = || async move { - (TypedHeader(ContentEncoding::gzip()), WithContentType("application/wasm", compressed_wasm)) + ([("content-encoding", "br")], WithContentType("application/wasm", compressed_wasm)) }; let app = Router::new() diff --git a/src/wasm_bindgen.rs b/src/wasm_bindgen.rs index f5b30f0..49b9b15 100644 --- a/src/wasm_bindgen.rs +++ b/src/wasm_bindgen.rs @@ -3,8 +3,6 @@ use anyhow::Context; use std::path::Path; use tracing::debug; -const COMPRESSION_LEVEL: u32 = 2; - pub struct WasmBindgenOutput { pub js: String, pub compressed_wasm: Vec, @@ -34,15 +32,11 @@ pub fn generate(wasm_file: &Path) -> Result { Ok(WasmBindgenOutput { js, compressed_wasm }) } -fn compress(bytes: &[u8]) -> Result, std::io::Error> { - use flate2::write::GzEncoder; - use flate2::Compression; - use std::io::prelude::*; - - let mut encoder = GzEncoder::new(Vec::new(), Compression::new(COMPRESSION_LEVEL)); +fn compress(mut bytes: &[u8]) -> Result, std::io::Error> { + use brotli::enc::{self, BrotliEncoderParams}; - encoder.write_all(bytes)?; - let compressed = encoder.finish()?; + let mut output = Vec::new(); + enc::BrotliCompress(&mut bytes, &mut output, &BrotliEncoderParams::default())?; - Ok(compressed) + Ok(output) }