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