Debian Codegraph @

third_party/rust/wasm-encoder/README.md

raw
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, Instruction,
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.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.instruction(&Instruction::LocalGet(0));
58 f.instruction(&Instruction::LocalGet(1));
59 f.instruction(&Instruction::I32Add);
60 f.instruction(&Instruction::End);
61 codes.function(&f);
62 module.section(&codes);
63
64 // Extract the encoded Wasm bytes for this module.
65 let wasm_bytes = module.finish();
66
67 // We generated a valid Wasm module!
68 assert!(wasmparser::validate(&wasm_bytes).is_ok());
69 ```
70
71 # License
72
73 This project is licensed under the Apache 2.0 license with the LLVM exception.
74 See [LICENSE](LICENSE) for more details.
75
76 ### Contribution
77
78 Unless you explicitly state otherwise, any contribution intentionally submitted
79 for inclusion in this project by you, as defined in the Apache-2.0 license,
80 shall be licensed as above, without any additional terms or conditions.