/src/wasm-tools/crates/wasm-encoder/src/modules.rs
Line | Count | Source (jump to first uncovered line) |
1 | | use super::*; |
2 | | |
3 | | /// An encoder for the module section. |
4 | | /// |
5 | | /// Note that this is part of the [module linking proposal][proposal] and is |
6 | | /// not currently part of stable WebAssembly. |
7 | | /// |
8 | | /// [proposal]: https://github.com/webassembly/module-linking |
9 | | /// |
10 | | /// # Example |
11 | | /// |
12 | | /// ``` |
13 | | /// use wasm_encoder::{ModuleSection, Module}; |
14 | | /// |
15 | | /// let mut modules = ModuleSection::new(); |
16 | | /// modules.module(&Module::new()); |
17 | | /// modules.module(&Module::new()); |
18 | | /// |
19 | | /// let mut module = Module::new(); |
20 | | /// module.section(&modules); |
21 | | /// |
22 | | /// let wasm_bytes = module.finish(); |
23 | | /// ``` |
24 | 0 | #[derive(Clone, Debug)] |
25 | | pub struct ModuleSection { |
26 | | bytes: Vec<u8>, |
27 | | num_added: u32, |
28 | | } |
29 | | |
30 | | impl ModuleSection { |
31 | | /// Create a new code section encoder. |
32 | 67.8k | pub fn new() -> ModuleSection { |
33 | 67.8k | ModuleSection { |
34 | 67.8k | bytes: vec![], |
35 | 67.8k | num_added: 0, |
36 | 67.8k | } |
37 | 67.8k | } |
38 | | |
39 | | /// Writes a dmodule into this module code section. |
40 | 223k | pub fn module(&mut self, module: &Module) -> &mut Self { |
41 | 223k | self.bytes.extend( |
42 | 223k | encoders::u32(u32::try_from(module.bytes.len()).unwrap()) |
43 | 223k | .chain(module.bytes.iter().copied()), |
44 | 223k | ); |
45 | 223k | self.num_added += 1; |
46 | 223k | self |
47 | 223k | } |
48 | | } |
49 | | |
50 | | impl Section for ModuleSection { |
51 | 67.8k | fn id(&self) -> u8 { |
52 | 67.8k | SectionId::Module.into() |
53 | 67.8k | } |
54 | | |
55 | 67.8k | fn encode<S>(&self, sink: &mut S) |
56 | 67.8k | where |
57 | 67.8k | S: Extend<u8>, |
58 | 67.8k | { |
59 | 67.8k | let num_added = encoders::u32(self.num_added); |
60 | 67.8k | let n = num_added.len(); |
61 | 67.8k | sink.extend( |
62 | 67.8k | encoders::u32(u32::try_from(n + self.bytes.len()).unwrap()) |
63 | 67.8k | .chain(num_added) |
64 | 67.8k | .chain(self.bytes.iter().copied()), |
65 | 67.8k | ); |
66 | 67.8k | } |
67 | | } |