Skip to content

Commit

Permalink
First version
Browse files Browse the repository at this point in the history
  • Loading branch information
ColinTimBarndt committed Jan 8, 2021
0 parents commit d1c8149
Show file tree
Hide file tree
Showing 6 changed files with 237 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/target
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"liveServer.settings.port": 5501
}
170 changes: 170 additions & 0 deletions Cargo.lock

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

12 changes: 12 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "wasm-gzip"
version = "0.1.0"
authors = ["ColinTimBarndt <[email protected]>"]
edition = "2018"

[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "0.2.69"
libflate = "1.0"
3 changes: 3 additions & 0 deletions build.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
wasm-pack build --target web
cd .\pkg
wasm-snip --snip-rust-panicking-code --snip-rust-fmt-code -o .\wasm_gzip_bg.wasm .\wasm_gzip_bg.wasm
48 changes: 48 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use libflate::gzip::{Decoder, Encoder};
use std::io::{self, Read};
use wasm_bindgen::prelude::*;

/// Compresses binary data using GZip.
#[wasm_bindgen(js_name = "compressGzip")]
pub fn gzip_compress(mut data: &[u8]) -> Option<Vec<u8>> {
let mut encoder: Encoder<Vec<u8>> = Encoder::new(Vec::new()).unwrap();
io::copy(&mut data, &mut encoder).unwrap();
match encoder.finish().into_result() {
Ok(data) => Some(data),
Err(_e) => return None,
}
}

/// Decompresses GZip data and returns the binary result.
#[wasm_bindgen(js_name = "decompressGzip")]
pub fn gzip_decompress(data: &[u8]) -> Option<Vec<u8>> {
let mut decoder: Decoder<&[u8]> = match Decoder::new(data) {
Ok(v) => v,
Err(_e) => return None,
};
let mut decoded = Vec::new();
match decoder.read_to_end(&mut decoded) {
Ok(_len) => Some(decoded),
Err(_e) => None,
}
}

#[wasm_bindgen(js_name = "compressStringGzip")]
pub fn gzip_compress_string(string: &str) -> Option<Vec<u8>> {
gzip_compress(string.as_bytes())
}

#[wasm_bindgen(js_name = "decompressStringGzip")]
pub fn gzip_decompress_string(data: &[u8]) -> Option<String> {
gzip_decompress(data).map(|decoded| bytes_to_string(&decoded))
}

#[wasm_bindgen(js_name = "stringToUtf8")]
pub fn string_to_bytes(input: &str) -> Vec<u8> {
input.as_bytes().to_vec()
}

#[wasm_bindgen(js_name = "utf8ToString")]
pub fn bytes_to_string(input: &[u8]) -> String {
String::from_utf8_lossy(input).to_string()
}

0 comments on commit d1c8149

Please sign in to comment.