Skip to content

Commit

Permalink
Make Rust rotate code smaller (GoogleChromeLabs#462)
Browse files Browse the repository at this point in the history
* Make Rust rotate code smaller

* Back on the rust happy path
  • Loading branch information
surma authored and jakearchibald committed Feb 15, 2019
1 parent adbc99c commit a3a272f
Show file tree
Hide file tree
Showing 6 changed files with 100 additions and 38 deletions.
2 changes: 2 additions & 0 deletions codecs/rotate/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
target
Cargo.lock
14 changes: 14 additions & 0 deletions codecs/rotate/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "rotate"
version = "0.1.0"
authors = ["Surma <surma@google.com>"]
edition = "2018"

[lib]
name = "rotate"
path = "rotate.rs"
crate-type = ["cdylib", "rlib"]

[profile.release]
lto = true
opt-level = "s"
11 changes: 5 additions & 6 deletions codecs/rotate/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@ echo "Compiling wasm"
echo "============================================="
(
rustup run nightly \
rustc \
--target=wasm32-unknown-unknown \
-C opt-level=3 \
-o rotate.wasm \
rotate.rs
wasm-strip rotate.wasm
cargo build \
--target wasm32-unknown-unknown \
--release
cp target/wasm32-unknown-unknown/release/rotate.wasm .
wasm-strip rotate.wasm
)
echo "============================================="
echo "Compiling wasm done"
Expand Down
29 changes: 19 additions & 10 deletions codecs/rotate/rotate.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
#![no_std]
#![no_main]
use std::slice::from_raw_parts_mut;

use core::panic::PanicInfo;
use core::slice::from_raw_parts_mut;
// This function is taken from
// https://rustwasm.github.io/book/reference/code-size.html
#[cfg(not(debug_assertions))]
#[inline]
pub fn unwrap_abort<T>(o: Option<T>) -> T {
use std::process;
match o {
Some(t) => t,
None => process::abort(),
}
}

// Normal panic-y behavior for debug builds
#[cfg(debug_assertions)]
unsafe fn unchecked_unwrap<T>(o: Option<T>) -> T {
o.unwrap()
}

#[no_mangle]
fn rotate(input_width: isize, input_height: isize, rotate: isize) {
Expand Down Expand Up @@ -69,13 +83,8 @@ fn rotate(input_width: isize, input_height: isize, rotate: isize) {
for d2 in 0..d2_limit {
for d1 in 0..d1_limit {
let in_idx = (d1_start + d1 * d1_advance) * d1_multiplier + (d2_start + d2 * d2_advance) * d2_multiplier;
out_b[i as usize] = in_b[in_idx as usize];
*unwrap_abort(out_b.get_mut(i as usize)) = *unwrap_abort(in_b.get(in_idx as usize));
i += 1;
}
}
}

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {}
}
Binary file modified codecs/rotate/rotate.wasm
Binary file not shown.
Loading

0 comments on commit a3a272f

Please sign in to comment.