| 1 |
<div align="center"> |
| 2 |
<h1><code>wasm-encoder</code></h1> |
| 3 |
|
| 4 |
<strong>A <a href="https://bytecodealliance.org/">Bytecode Alliance</a> project</strong> |
| 5 |
|
| 6 |
<p> |
| 7 |
<strong>A WebAssembly encoder for Rust.</strong> |
| 8 |
</p> |
| 9 |
|
| 10 |
<p> |
| 11 |
<a href="https://crates.io/crates/wasm-encoder"><img src="https://img.shields.io/crates/v/wasm-encoder.svg?style=flat-square" alt="Crates.io version" /></a> |
| 12 |
<a href="https://crates.io/crates/wasm-encoder"><img src="https://img.shields.io/crates/d/wasm-encoder.svg?style=flat-square" alt="Download" /></a> |
| 13 |
<a href="https://docs.rs/wasm-encoder/"><img src="https://img.shields.io/static/v1?label=docs&message=wasm-encoder&color=blue&style=flat-square" alt="docs.rs docs" /></a> |
| 14 |
</p> |
| 15 |
</div> |
| 16 |
|
| 17 |
## Usage |
| 18 |
|
| 19 |
Add `wasm-encoder` to your `Cargo.toml` |
| 20 |
|
| 21 |
```sh |
| 22 |
$ cargo add wasm-encoder |
| 23 |
``` |
| 24 |
|
| 25 |
And then you can encode WebAssembly binaries via: |
| 26 |
|
| 27 |
```rust |
| 28 |
use wasm_encoder::{ |
| 29 |
CodeSection, ExportKind, ExportSection, Function, FunctionSection, |
| 30 |
Module, TypeSection, ValType, |
| 31 |
}; |
| 32 |
|
| 33 |
let mut module = Module::new(); |
| 34 |
|
| 35 |
// Encode the type section. |
| 36 |
let mut types = TypeSection::new(); |
| 37 |
let params = vec![ValType::I32, ValType::I32]; |
| 38 |
let results = vec![ValType::I32]; |
| 39 |
types.ty().function(params, results); |
| 40 |
module.section(&types); |
| 41 |
|
| 42 |
// Encode the function section. |
| 43 |
let mut functions = FunctionSection::new(); |
| 44 |
let type_index = 0; |
| 45 |
functions.function(type_index); |
| 46 |
module.section(&functions); |
| 47 |
|
| 48 |
// Encode the export section. |
| 49 |
let mut exports = ExportSection::new(); |
| 50 |
exports.export("f", ExportKind::Func, 0); |
| 51 |
module.section(&exports); |
| 52 |
|
| 53 |
// Encode the code section. |
| 54 |
let mut codes = CodeSection::new(); |
| 55 |
let locals = vec![]; |
| 56 |
let mut f = Function::new(locals); |
| 57 |
f.instructions() |
| 58 |
.local_get(0) |
| 59 |
.local_get(1) |
| 60 |
.i32_add() |
| 61 |
.end(); |
| 62 |
codes.function(&f); |
| 63 |
module.section(&codes); |
| 64 |
|
| 65 |
// Extract the encoded Wasm bytes for this module. |
| 66 |
let wasm_bytes = module.finish(); |
| 67 |
|
| 68 |
// We generated a valid Wasm module! |
| 69 |
assert!(wasmparser::validate(&wasm_bytes).is_ok()); |
| 70 |
``` |
| 71 |
|
| 72 |
# License |
| 73 |
|
| 74 |
This project is licensed under the Apache 2.0 license with the LLVM exception. |
| 75 |
See [LICENSE](LICENSE) for more details. |
| 76 |
|
| 77 |
### Contribution |
| 78 |
|
| 79 |
Unless you explicitly state otherwise, any contribution intentionally submitted |
| 80 |
for inclusion in this project by you, as defined in the Apache-2.0 license, |
| 81 |
shall be licensed as above, without any additional terms or conditions. |