1use super::{
2 CORE_FUNCTION_SORT, CORE_GLOBAL_SORT, CORE_MEMORY_SORT, CORE_TABLE_SORT, CORE_TAG_SORT,
3};
4use crate::{encode_section, Encode, Section, SectionId};
5
6/// Represents the kind of an export from a WebAssembly module.
7#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
8#[repr(u8)]
9pub enum ExportKind {
10 /// The export is a function.
11 Func = CORE_FUNCTION_SORT,
12 /// The export is a table.
13 Table = CORE_TABLE_SORT,
14 /// The export is a memory.
15 Memory = CORE_MEMORY_SORT,
16 /// The export is a global.
17 Global = CORE_GLOBAL_SORT,
18 /// The export is a tag.
19 Tag = CORE_TAG_SORT,
20}
21
22impl Encode for ExportKind {
23 fn encode(&self, sink: &mut Vec<u8>) {
24 sink.push(*self as u8);
25 }
26}
27
28/// An encoder for the export section of WebAssembly module.
29///
30/// # Example
31///
32/// ```rust
33/// use wasm_encoder::{Module, ExportSection, ExportKind};
34///
35/// let mut exports = ExportSection::new();
36/// exports.export("foo", ExportKind::Func, 0);
37///
38/// let mut module = Module::new();
39/// module.section(&exports);
40///
41/// let bytes = module.finish();
42/// ```
43#[derive(Clone, Debug, Default)]
44pub struct ExportSection {
45 bytes: Vec<u8>,
46 num_added: u32,
47}
48
49impl ExportSection {
50 /// Create a new export section encoder.
51 pub fn new() -> Self {
52 Self::default()
53 }
54
55 /// The number of exports in the section.
56 pub fn len(&self) -> u32 {
57 self.num_added
58 }
59
60 /// Determines if the section is empty.
61 pub fn is_empty(&self) -> bool {
62 self.num_added == 0
63 }
64
65 /// Define an export in the export section.
66 pub fn export(&mut self, name: &str, kind: ExportKind, index: u32) -> &mut Self {
67 name.encode(&mut self.bytes);
68 kind.encode(&mut self.bytes);
69 index.encode(&mut self.bytes);
70 self.num_added += 1;
71 self
72 }
73}
74
75impl Encode for ExportSection {
76 fn encode(&self, sink: &mut Vec<u8>) {
77 encode_section(sink, self.num_added, &self.bytes);
78 }
79}
80
81impl Section for ExportSection {
82 fn id(&self) -> u8 {
83 SectionId::Export.into()
84 }
85}
86