/build/source/src/execution/registry.rs
Line | Count | Source |
1 | | use crate::{Error, ModuleInst}; |
2 | | |
3 | | use alloc::borrow::Cow; |
4 | | use alloc::collections::BTreeMap; |
5 | | |
6 | | use crate::ExternVal; |
7 | | |
8 | | #[derive(Debug, PartialEq, PartialOrd, Eq, Ord)] |
9 | | struct ImportKey { |
10 | | module_name: Cow<'static, str>, |
11 | | name: Cow<'static, str>, |
12 | | } |
13 | | #[derive(Default, Debug)] |
14 | | pub struct Registry(BTreeMap<ImportKey, ExternVal>); |
15 | | |
16 | | impl Registry { |
17 | 4.91k | pub fn register( |
18 | 4.91k | &mut self, |
19 | 4.91k | module_name: Cow<'static, str>, |
20 | 4.91k | name: Cow<'static, str>, |
21 | 4.91k | extern_val: ExternVal, |
22 | 4.91k | ) -> Result<(), Error> { |
23 | 4.91k | if self |
24 | 4.91k | .0 |
25 | 4.91k | .insert(ImportKey { module_name, name }, extern_val) |
26 | 4.91k | .is_some() |
27 | | { |
28 | 0 | return Err(Error::InvalidImportType); |
29 | 4.91k | } |
30 | 4.91k | |
31 | 4.91k | Ok(()) |
32 | 4.91k | } |
33 | | |
34 | 645 | pub fn lookup( |
35 | 645 | &self, |
36 | 645 | module_name: Cow<'static, str>, |
37 | 645 | name: Cow<'static, str>, |
38 | 645 | ) -> Result<&ExternVal, Error> { |
39 | 645 | // Note: We cannot do a `&str` lookup on a [`String`] map key. |
40 | 645 | // Thus we have to use `Cow<'static, str>` as a key |
41 | 645 | // (at least this prevents allocations with static names). |
42 | 645 | self.0 |
43 | 645 | .get(&ImportKey { module_name, name }) |
44 | 645 | .ok_or(Error::UnknownImport) |
45 | 645 | } |
46 | | |
47 | 1.55k | pub fn register_module( |
48 | 1.55k | &mut self, |
49 | 1.55k | module_name: Cow<'static, str>, |
50 | 1.55k | module_inst: &ModuleInst, |
51 | 1.55k | ) -> Result<(), Error> { |
52 | 6.46k | for (entity_name, extern_val4.90k ) in &module_inst.exports { |
53 | | // FIXME this clones module_name. Maybe prevent by using `Cow<'static, Arc<str>>`. |
54 | 4.90k | self.register( |
55 | 4.90k | module_name.clone(), |
56 | 4.90k | Cow::Owned(entity_name.clone()), |
57 | 4.90k | *extern_val, |
58 | 4.90k | )?0 ; |
59 | | } |
60 | 1.55k | Ok(()) |
61 | 1.55k | } |
62 | | } |