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