wit_walrus/
exports.rs

1use crate::{FuncId, WasmInterfaceTypes, WitIdsToIndices, WitIndicesToIds};
2use anyhow::Result;
3use id_arena::{Arena, Id};
4
5#[derive(Debug, Default)]
6pub struct Exports {
7    arena: Arena<Export>,
8}
9
10#[derive(Debug)]
11pub struct Export {
12    id: ExportId,
13    pub name: String,
14    pub func: FuncId,
15}
16
17pub type ExportId = Id<Export>;
18
19impl WasmInterfaceTypes {
20    pub(crate) fn parse_exports(
21        &mut self,
22        exports: wit_parser::Exports,
23        wids: &mut WitIndicesToIds,
24    ) -> Result<()> {
25        for export in exports {
26            let export = export?;
27            let func = wids.func(export.func)?;
28            self.exports.add(export.name, func);
29        }
30        Ok(())
31    }
32
33    pub(crate) fn encode_exports(&self, writer: &mut wit_writer::Writer, wids: &WitIdsToIndices) {
34        let mut w = writer.exports(self.exports.arena.len() as u32);
35        for export in self.exports.iter() {
36            w.add(&export.name, wids.func(export.func));
37        }
38    }
39}
40
41impl Exports {
42    /// Gets a reference to an export given its id
43    pub fn get(&self, id: ExportId) -> &Export {
44        &self.arena[id]
45    }
46
47    /// Gets a reference to an export given its id
48    pub fn get_mut(&mut self, id: ExportId) -> &mut Export {
49        &mut self.arena[id]
50    }
51
52    // /// Removes an export from this module.
53    // ///
54    // /// It is up to you to ensure that any potential references to the deleted
55    // /// export are also removed, eg `get_global` expressions.
56    // pub fn delete(&mut self, id: ExportId) {
57    //     self.arena.delete(id);
58    // }
59
60    /// Get a shared reference to this section's exports.
61    pub fn iter(&self) -> impl Iterator<Item = &Export> {
62        self.arena.iter().map(|(_, f)| f)
63    }
64
65    /// Get mutable references to this section's exports.
66    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Export> {
67        self.arena.iter_mut().map(|(_, f)| f)
68    }
69
70    /// Adds a new export to this section
71    pub fn add(&mut self, name: &str, func: FuncId) -> ExportId {
72        self.arena.alloc_with_id(|id| Export {
73            id,
74            name: name.to_string(),
75            func,
76        })
77    }
78}
79
80impl Export {
81    /// Returns the identifier for this `Export`
82    pub fn id(&self) -> ExportId {
83        self.id
84    }
85}