| 1 | use crate::{encode_section, Encode, Section, SectionId}; |
| 2 | use alloc::vec::Vec; |
| 3 | |
| 4 | /// An encoder for the function section of WebAssembly modules. |
| 5 | /// |
| 6 | /// # Example |
| 7 | /// |
| 8 | /// ``` |
| 9 | /// use wasm_encoder::{Module, FunctionSection, ValType}; |
| 10 | /// |
| 11 | /// let mut functions = FunctionSection::new(); |
| 12 | /// let type_index = 0; |
| 13 | /// functions.function(type_index); |
| 14 | /// |
| 15 | /// let mut module = Module::new(); |
| 16 | /// module.section(&functions); |
| 17 | /// |
| 18 | /// // Note: this will generate an invalid module because we didn't generate a |
| 19 | /// // code section containing the function body. See the documentation for |
| 20 | /// // `CodeSection` for details. |
| 21 | /// |
| 22 | /// let bytes = module.finish(); |
| 23 | /// ``` |
| 24 | #[derive (Clone, Debug, Default)] |
| 25 | pub struct FunctionSection { |
| 26 | bytes: Vec<u8>, |
| 27 | num_added: u32, |
| 28 | } |
| 29 | |
| 30 | impl FunctionSection { |
| 31 | /// Construct a new module function section encoder. |
| 32 | pub fn new() -> Self { |
| 33 | Self::default() |
| 34 | } |
| 35 | |
| 36 | /// The number of functions in the section. |
| 37 | pub fn len(&self) -> u32 { |
| 38 | self.num_added |
| 39 | } |
| 40 | |
| 41 | /// Determines if the section is empty. |
| 42 | pub fn is_empty(&self) -> bool { |
| 43 | self.num_added == 0 |
| 44 | } |
| 45 | |
| 46 | /// Define a function in a module's function section. |
| 47 | pub fn function(&mut self, type_index: u32) -> &mut Self { |
| 48 | type_index.encode(&mut self.bytes); |
| 49 | self.num_added += 1; |
| 50 | self |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | impl Encode for FunctionSection { |
| 55 | fn encode(&self, sink: &mut Vec<u8>) { |
| 56 | encode_section(sink, self.num_added, &self.bytes); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | impl Section for FunctionSection { |
| 61 | fn id(&self) -> u8 { |
| 62 | SectionId::Function.into() |
| 63 | } |
| 64 | } |
| 65 | |