wasmer_types/
module.rs

1// This file contains code from external sources.
2// Attributions: https://github.com/wasmerio/wasmer/blob/main/docs/ATTRIBUTIONS.md
3
4//! Data structure for representing WebAssembly modules in a
5//! `wasmer::Module`.
6
7use crate::entity::{EntityRef, PrimaryMap};
8use crate::{
9    CustomSectionIndex, DataIndex, ElemIndex, ExportIndex, ExportType, ExternType, FunctionIndex,
10    FunctionType, GlobalIndex, GlobalInit, GlobalType, ImportIndex, ImportType, LocalFunctionIndex,
11    LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, LocalTagIndex, MemoryIndex, MemoryType,
12    ModuleHash, SignatureIndex, TableIndex, TableInitializer, TableType, TagIndex, TagType,
13};
14
15use indexmap::IndexMap;
16use rkyv::rancor::{Fallible, Source, Trace};
17use rkyv::{Archive, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize};
18#[cfg(feature = "enable-serde")]
19use serde::{Deserialize, Serialize};
20use std::collections::BTreeMap;
21use std::collections::HashMap;
22use std::fmt;
23use std::iter::ExactSizeIterator;
24use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
25
26#[derive(Debug, Clone, RkyvSerialize, RkyvDeserialize, Archive)]
27#[cfg_attr(feature = "artifact-size", derive(loupe::MemoryUsage))]
28#[rkyv(derive(Debug))]
29pub struct ModuleId {
30    id: usize,
31}
32
33impl ModuleId {
34    pub fn id(&self) -> String {
35        format!("{}", &self.id)
36    }
37}
38
39impl Default for ModuleId {
40    fn default() -> Self {
41        static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
42        Self {
43            id: NEXT_ID.fetch_add(1, SeqCst),
44        }
45    }
46}
47
48/// Hash key of an import
49#[derive(Debug, Hash, Eq, PartialEq, Clone, Default, RkyvSerialize, RkyvDeserialize, Archive)]
50#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
51#[rkyv(derive(PartialOrd, Ord, PartialEq, Eq, Hash, Debug))]
52pub struct ImportKey {
53    /// Module name
54    pub module: String,
55    /// Field name
56    pub field: String,
57    /// Import index
58    pub import_idx: u32,
59}
60
61impl From<(String, String, u32)> for ImportKey {
62    fn from((module, field, import_idx): (String, String, u32)) -> Self {
63        Self {
64            module,
65            field,
66            import_idx,
67        }
68    }
69}
70
71#[cfg(feature = "enable-serde")]
72mod serde_imports {
73
74    use crate::ImportIndex;
75    use crate::ImportKey;
76    use indexmap::IndexMap;
77    use serde::{Deserialize, Deserializer, Serialize, Serializer};
78
79    type InitialType = IndexMap<ImportKey, ImportIndex>;
80    type SerializedType = Vec<(ImportKey, ImportIndex)>;
81    // IndexMap<ImportKey, ImportIndex>
82    // Vec<
83    pub fn serialize<S: Serializer>(s: &InitialType, serializer: S) -> Result<S::Ok, S::Error> {
84        let vec: SerializedType = s
85            .iter()
86            .map(|(a, b)| (a.clone(), b.clone()))
87            .collect::<Vec<_>>();
88        vec.serialize(serializer)
89    }
90
91    pub fn deserialize<'de, D: Deserializer<'de>>(
92        deserializer: D,
93    ) -> Result<InitialType, D::Error> {
94        let serialized = <SerializedType as Deserialize>::deserialize(deserializer)?;
95        Ok(serialized.into_iter().collect())
96    }
97}
98
99/// A translated WebAssembly module, excluding the function bodies and
100/// memory initializers.
101///
102/// IMPORTANT: since this struct will be serialized as part of the compiled module artifact,
103/// if you change this struct, do not forget to update [`MetadataHeader::version`](crate::serialize::MetadataHeader)
104/// to make sure we don't break compatibility between versions.
105#[derive(Debug, Clone, Default)]
106#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
107#[cfg_attr(feature = "artifact-size", derive(loupe::MemoryUsage))]
108pub struct ModuleInfo {
109    /// A unique identifier (within this process) for this module.
110    ///
111    /// We skip serialization/deserialization of this field, as it
112    /// should be computed by the process.
113    /// It's not skipped in rkyv, but that is okay, because even though it's skipped in bincode/serde
114    /// it's still deserialized back as a garbage number, and later override from computed by the process
115    #[cfg_attr(feature = "enable-serde", serde(skip_serializing, skip_deserializing))]
116    pub id: ModuleId,
117
118    /// hash of the module
119    pub hash: Option<ModuleHash>,
120
121    /// The name of this wasm module, often found in the wasm file.
122    pub name: Option<String>,
123
124    /// Imported entities with the (module, field, index_of_the_import)
125    ///
126    /// Keeping the `index_of_the_import` is important, as there can be
127    /// two same references to the same import, and we don't want to confuse
128    /// them.
129    #[cfg_attr(feature = "enable-serde", serde(with = "serde_imports"))]
130    pub imports: IndexMap<ImportKey, ImportIndex>,
131
132    /// Exported entities.
133    pub exports: IndexMap<String, ExportIndex>,
134
135    /// The module "start" function, if present.
136    pub start_function: Option<FunctionIndex>,
137
138    /// WebAssembly table initializers.
139    pub table_initializers: Vec<TableInitializer>,
140
141    /// WebAssembly passive elements.
142    pub passive_elements: HashMap<ElemIndex, Box<[FunctionIndex]>>,
143
144    /// WebAssembly passive data segments.
145    pub passive_data: HashMap<DataIndex, Box<[u8]>>,
146
147    /// WebAssembly global initializers.
148    pub global_initializers: PrimaryMap<LocalGlobalIndex, GlobalInit>,
149
150    /// WebAssembly function names.
151    pub function_names: HashMap<FunctionIndex, String>,
152
153    /// WebAssembly function signatures.
154    pub signatures: PrimaryMap<SignatureIndex, FunctionType>,
155
156    /// WebAssembly functions (imported and local).
157    pub functions: PrimaryMap<FunctionIndex, SignatureIndex>,
158
159    /// WebAssembly tables (imported and local).
160    pub tables: PrimaryMap<TableIndex, TableType>,
161
162    /// WebAssembly linear memories (imported and local).
163    pub memories: PrimaryMap<MemoryIndex, MemoryType>,
164
165    /// WebAssembly global variables (imported and local).
166    pub globals: PrimaryMap<GlobalIndex, GlobalType>,
167
168    /// WebAssembly tag variables (imported and local).
169    pub tags: PrimaryMap<TagIndex, SignatureIndex>,
170
171    /// Custom sections in the module.
172    pub custom_sections: IndexMap<String, CustomSectionIndex>,
173
174    /// The data for each CustomSection in the module.
175    pub custom_sections_data: PrimaryMap<CustomSectionIndex, Box<[u8]>>,
176
177    /// Number of imported functions in the module.
178    pub num_imported_functions: usize,
179
180    /// Number of imported tables in the module.
181    pub num_imported_tables: usize,
182
183    /// Number of imported memories in the module.
184    pub num_imported_memories: usize,
185
186    /// Number of imported tags in the module.
187    pub num_imported_tags: usize,
188
189    /// Number of imported globals in the module.
190    pub num_imported_globals: usize,
191}
192
193/// Mirror version of ModuleInfo that can derive rkyv traits
194#[derive(Debug, RkyvSerialize, RkyvDeserialize, Archive)]
195#[rkyv(derive(Debug))]
196pub struct ArchivableModuleInfo {
197    name: Option<String>,
198    hash: Option<ModuleHash>,
199    imports: IndexMap<ImportKey, ImportIndex>,
200    exports: IndexMap<String, ExportIndex>,
201    start_function: Option<FunctionIndex>,
202    table_initializers: Vec<TableInitializer>,
203    passive_elements: BTreeMap<ElemIndex, Box<[FunctionIndex]>>,
204    passive_data: BTreeMap<DataIndex, Box<[u8]>>,
205    global_initializers: PrimaryMap<LocalGlobalIndex, GlobalInit>,
206    function_names: BTreeMap<FunctionIndex, String>,
207    signatures: PrimaryMap<SignatureIndex, FunctionType>,
208    functions: PrimaryMap<FunctionIndex, SignatureIndex>,
209    tables: PrimaryMap<TableIndex, TableType>,
210    memories: PrimaryMap<MemoryIndex, MemoryType>,
211    globals: PrimaryMap<GlobalIndex, GlobalType>,
212    tags: PrimaryMap<TagIndex, SignatureIndex>,
213    custom_sections: IndexMap<String, CustomSectionIndex>,
214    custom_sections_data: PrimaryMap<CustomSectionIndex, Box<[u8]>>,
215    num_imported_functions: usize,
216    num_imported_tables: usize,
217    num_imported_tags: usize,
218    num_imported_memories: usize,
219    num_imported_globals: usize,
220}
221
222impl From<ModuleInfo> for ArchivableModuleInfo {
223    fn from(it: ModuleInfo) -> Self {
224        Self {
225            name: it.name,
226            hash: it.hash,
227            imports: it.imports,
228            exports: it.exports,
229            start_function: it.start_function,
230            table_initializers: it.table_initializers,
231            passive_elements: it.passive_elements.into_iter().collect(),
232            passive_data: it.passive_data.into_iter().collect(),
233            global_initializers: it.global_initializers,
234            function_names: it.function_names.into_iter().collect(),
235            signatures: it.signatures,
236            functions: it.functions,
237            tables: it.tables,
238            memories: it.memories,
239            globals: it.globals,
240            tags: it.tags,
241            custom_sections: it.custom_sections,
242            custom_sections_data: it.custom_sections_data,
243            num_imported_functions: it.num_imported_functions,
244            num_imported_tables: it.num_imported_tables,
245            num_imported_tags: it.num_imported_tags,
246            num_imported_memories: it.num_imported_memories,
247            num_imported_globals: it.num_imported_globals,
248        }
249    }
250}
251
252impl From<ArchivableModuleInfo> for ModuleInfo {
253    fn from(it: ArchivableModuleInfo) -> Self {
254        Self {
255            id: Default::default(),
256            name: it.name,
257            hash: it.hash,
258            imports: it.imports,
259            exports: it.exports,
260            start_function: it.start_function,
261            table_initializers: it.table_initializers,
262            passive_elements: it.passive_elements.into_iter().collect(),
263            passive_data: it.passive_data.into_iter().collect(),
264            global_initializers: it.global_initializers,
265            function_names: it.function_names.into_iter().collect(),
266            signatures: it.signatures,
267            functions: it.functions,
268            tables: it.tables,
269            memories: it.memories,
270            globals: it.globals,
271            tags: it.tags,
272            custom_sections: it.custom_sections,
273            custom_sections_data: it.custom_sections_data,
274            num_imported_functions: it.num_imported_functions,
275            num_imported_tables: it.num_imported_tables,
276            num_imported_tags: it.num_imported_tags,
277            num_imported_memories: it.num_imported_memories,
278            num_imported_globals: it.num_imported_globals,
279        }
280    }
281}
282
283impl From<&ModuleInfo> for ArchivableModuleInfo {
284    fn from(it: &ModuleInfo) -> Self {
285        Self::from(it.clone())
286    }
287}
288
289impl Archive for ModuleInfo {
290    type Archived = <ArchivableModuleInfo as Archive>::Archived;
291    type Resolver = <ArchivableModuleInfo as Archive>::Resolver;
292
293    fn resolve(&self, resolver: Self::Resolver, out: rkyv::Place<Self::Archived>) {
294        ArchivableModuleInfo::from(self).resolve(resolver, out)
295    }
296}
297
298impl<S: rkyv::ser::Allocator + rkyv::ser::Writer + Fallible + ?Sized> RkyvSerialize<S>
299    for ModuleInfo
300where
301    <S as Fallible>::Error: rkyv::rancor::Source + rkyv::rancor::Trace,
302{
303    fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
304        ArchivableModuleInfo::from(self).serialize(serializer)
305    }
306}
307
308impl<D: Fallible + ?Sized> RkyvDeserialize<ModuleInfo, D> for ArchivedArchivableModuleInfo
309where
310    D::Error: Source + Trace,
311{
312    fn deserialize(&self, deserializer: &mut D) -> Result<ModuleInfo, D::Error> {
313        let archived = RkyvDeserialize::<ArchivableModuleInfo, D>::deserialize(self, deserializer)?;
314        Ok(ModuleInfo::from(archived))
315    }
316}
317
318// For test serialization correctness, everything except module id should be same
319impl PartialEq for ModuleInfo {
320    fn eq(&self, other: &Self) -> bool {
321        self.name == other.name
322            && self.imports == other.imports
323            && self.exports == other.exports
324            && self.start_function == other.start_function
325            && self.table_initializers == other.table_initializers
326            && self.passive_elements == other.passive_elements
327            && self.passive_data == other.passive_data
328            && self.global_initializers == other.global_initializers
329            && self.function_names == other.function_names
330            && self.signatures == other.signatures
331            && self.functions == other.functions
332            && self.tables == other.tables
333            && self.memories == other.memories
334            && self.globals == other.globals
335            && self.tags == other.tags
336            && self.custom_sections == other.custom_sections
337            && self.custom_sections_data == other.custom_sections_data
338            && self.num_imported_functions == other.num_imported_functions
339            && self.num_imported_tables == other.num_imported_tables
340            && self.num_imported_tags == other.num_imported_tags
341            && self.num_imported_memories == other.num_imported_memories
342            && self.num_imported_globals == other.num_imported_globals
343    }
344}
345
346impl Eq for ModuleInfo {}
347
348impl ModuleInfo {
349    /// Allocates the module data structures.
350    pub fn new() -> Self {
351        Default::default()
352    }
353
354    /// Returns the module hash if available
355    pub fn hash(&self) -> Option<ModuleHash> {
356        self.hash
357    }
358
359    /// Returns the module hash as String if available
360    pub fn hash_string(&self) -> Option<String> {
361        self.hash.map(|m| m.to_string())
362    }
363
364    /// Get the given passive element, if it exists.
365    pub fn get_passive_element(&self, index: ElemIndex) -> Option<&[FunctionIndex]> {
366        self.passive_elements.get(&index).map(|es| &**es)
367    }
368
369    /// Get the exported signatures of the module
370    pub fn exported_signatures(&self) -> Vec<FunctionType> {
371        self.exports
372            .iter()
373            .filter_map(|(_name, export_index)| match export_index {
374                ExportIndex::Function(i) => {
375                    let signature = self.functions.get(*i).unwrap();
376                    let func_type = self.signatures.get(*signature).unwrap();
377                    Some(func_type.clone())
378                }
379                _ => None,
380            })
381            .collect::<Vec<FunctionType>>()
382    }
383
384    /// Get the export types of the module
385    pub fn exports(&'_ self) -> ExportsIterator<Box<dyn Iterator<Item = ExportType> + '_>> {
386        let iter = self.exports.iter().map(move |(name, export_index)| {
387            let extern_type = match export_index {
388                ExportIndex::Function(i) => {
389                    let signature = self.functions.get(*i).unwrap();
390                    let func_type = self.signatures.get(*signature).unwrap();
391                    ExternType::Function(func_type.clone())
392                }
393                ExportIndex::Table(i) => {
394                    let table_type = self.tables.get(*i).unwrap();
395                    ExternType::Table(*table_type)
396                }
397                ExportIndex::Memory(i) => {
398                    let memory_type = self.memories.get(*i).unwrap();
399                    ExternType::Memory(*memory_type)
400                }
401                ExportIndex::Global(i) => {
402                    let global_type = self.globals.get(*i).unwrap();
403                    ExternType::Global(*global_type)
404                }
405                ExportIndex::Tag(i) => {
406                    let signature = self.tags.get(*i).unwrap();
407                    let tag_type = self.signatures.get(*signature).unwrap();
408
409                    ExternType::Tag(TagType {
410                        kind: crate::types::TagKind::Exception,
411                        params: tag_type.params().into(),
412                    })
413                }
414            };
415            ExportType::new(name, extern_type)
416        });
417        ExportsIterator::new(Box::new(iter), self.exports.len())
418    }
419
420    /// Get the import types of the module
421    pub fn imports(&'_ self) -> ImportsIterator<Box<dyn Iterator<Item = ImportType> + '_>> {
422        let iter =
423            self.imports
424                .iter()
425                .map(move |(ImportKey { module, field, .. }, import_index)| {
426                    let extern_type = match import_index {
427                        ImportIndex::Function(i) => {
428                            let signature = self.functions.get(*i).unwrap();
429                            let func_type = self.signatures.get(*signature).unwrap();
430                            ExternType::Function(func_type.clone())
431                        }
432                        ImportIndex::Table(i) => {
433                            let table_type = self.tables.get(*i).unwrap();
434                            ExternType::Table(*table_type)
435                        }
436                        ImportIndex::Memory(i) => {
437                            let memory_type = self.memories.get(*i).unwrap();
438                            ExternType::Memory(*memory_type)
439                        }
440                        ImportIndex::Global(i) => {
441                            let global_type = self.globals.get(*i).unwrap();
442                            ExternType::Global(*global_type)
443                        }
444                        ImportIndex::Tag(i) => {
445                            let tag_type = self.tags.get(*i).unwrap();
446                            let func_type = self.signatures.get(*tag_type).unwrap();
447                            ExternType::Tag(TagType::from_fn_type(
448                                crate::TagKind::Exception,
449                                func_type.clone(),
450                            ))
451                        }
452                    };
453                    ImportType::new(module, field, extern_type)
454                });
455        ImportsIterator::new(Box::new(iter), self.imports.len())
456    }
457
458    /// Get the custom sections of the module given a `name`.
459    pub fn custom_sections<'a>(
460        &'a self,
461        name: &'a str,
462    ) -> Box<impl Iterator<Item = Box<[u8]>> + 'a> {
463        Box::new(
464            self.custom_sections
465                .iter()
466                .filter_map(move |(section_name, section_index)| {
467                    if name != section_name {
468                        return None;
469                    }
470                    Some(self.custom_sections_data[*section_index].clone())
471                }),
472        )
473    }
474
475    /// Convert a `LocalFunctionIndex` into a `FunctionIndex`.
476    pub fn func_index(&self, local_func: LocalFunctionIndex) -> FunctionIndex {
477        FunctionIndex::new(self.num_imported_functions + local_func.index())
478    }
479
480    /// Convert a `FunctionIndex` into a `LocalFunctionIndex`. Returns None if the
481    /// index is an imported function.
482    pub fn local_func_index(&self, func: FunctionIndex) -> Option<LocalFunctionIndex> {
483        func.index()
484            .checked_sub(self.num_imported_functions)
485            .map(LocalFunctionIndex::new)
486    }
487
488    /// Test whether the given function index is for an imported function.
489    pub fn is_imported_function(&self, index: FunctionIndex) -> bool {
490        index.index() < self.num_imported_functions
491    }
492
493    /// Convert a `LocalTableIndex` into a `TableIndex`.
494    pub fn table_index(&self, local_table: LocalTableIndex) -> TableIndex {
495        TableIndex::new(self.num_imported_tables + local_table.index())
496    }
497
498    /// Convert a `TableIndex` into a `LocalTableIndex`. Returns None if the
499    /// index is an imported table.
500    pub fn local_table_index(&self, table: TableIndex) -> Option<LocalTableIndex> {
501        table
502            .index()
503            .checked_sub(self.num_imported_tables)
504            .map(LocalTableIndex::new)
505    }
506
507    /// Test whether the given table index is for an imported table.
508    pub fn is_imported_table(&self, index: TableIndex) -> bool {
509        index.index() < self.num_imported_tables
510    }
511
512    /// Convert a `LocalMemoryIndex` into a `MemoryIndex`.
513    pub fn memory_index(&self, local_memory: LocalMemoryIndex) -> MemoryIndex {
514        MemoryIndex::new(self.num_imported_memories + local_memory.index())
515    }
516
517    /// Convert a `MemoryIndex` into a `LocalMemoryIndex`. Returns None if the
518    /// index is an imported memory.
519    pub fn local_memory_index(&self, memory: MemoryIndex) -> Option<LocalMemoryIndex> {
520        memory
521            .index()
522            .checked_sub(self.num_imported_memories)
523            .map(LocalMemoryIndex::new)
524    }
525
526    /// Test whether the given memory index is for an imported memory.
527    pub fn is_imported_memory(&self, index: MemoryIndex) -> bool {
528        index.index() < self.num_imported_memories
529    }
530
531    /// Convert a `LocalGlobalIndex` into a `GlobalIndex`.
532    pub fn global_index(&self, local_global: LocalGlobalIndex) -> GlobalIndex {
533        GlobalIndex::new(self.num_imported_globals + local_global.index())
534    }
535
536    /// Convert a `GlobalIndex` into a `LocalGlobalIndex`. Returns None if the
537    /// index is an imported global.
538    pub fn local_global_index(&self, global: GlobalIndex) -> Option<LocalGlobalIndex> {
539        global
540            .index()
541            .checked_sub(self.num_imported_globals)
542            .map(LocalGlobalIndex::new)
543    }
544
545    /// Test whether the given global index is for an imported global.
546    pub fn is_imported_global(&self, index: GlobalIndex) -> bool {
547        index.index() < self.num_imported_globals
548    }
549
550    /// Convert a `LocalTagIndex` into a `TagIndex`.
551    pub fn tag_index(&self, local_tag: LocalTagIndex) -> TagIndex {
552        TagIndex::new(self.num_imported_tags + local_tag.index())
553    }
554
555    /// Convert a `TagIndex` into a `LocalTagIndex`. Returns None if the
556    /// index is an imported tag.
557    pub fn local_tag_index(&self, tag: TagIndex) -> Option<LocalTagIndex> {
558        tag.index()
559            .checked_sub(self.num_imported_tags)
560            .map(LocalTagIndex::new)
561    }
562
563    /// Test whether the given tag index is for an imported tag.
564    pub fn is_imported_tag(&self, index: TagIndex) -> bool {
565        index.index() < self.num_imported_tags
566    }
567
568    /// Get the Module name
569    pub fn name(&self) -> String {
570        match self.name {
571            Some(ref name) => name.to_string(),
572            None => "<module>".to_string(),
573        }
574    }
575
576    /// Get the imported function types of the module.
577    pub fn imported_function_types(&'_ self) -> impl Iterator<Item = FunctionType> + '_ {
578        self.functions
579            .values()
580            .take(self.num_imported_functions)
581            .map(move |sig_index| self.signatures[*sig_index].clone())
582    }
583
584    /// Get the name of a function by its index.
585    pub fn get_function_name(&self, func_index: FunctionIndex) -> String {
586        self.function_names
587            .get(&func_index)
588            .cloned()
589            .unwrap_or_else(|| format!("function_{}", func_index.as_u32()))
590    }
591}
592
593impl fmt::Display for ModuleInfo {
594    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
595        write!(f, "{}", self.name())
596    }
597}
598
599// Code inspired from
600// https://www.reddit.com/r/rust/comments/9vspv4/extending_iterators_ergonomically/
601
602/// This iterator allows us to iterate over the exports
603/// and offer nice API ergonomics over it.
604pub struct ExportsIterator<I: Iterator<Item = ExportType> + Sized> {
605    iter: I,
606    size: usize,
607}
608
609impl<I: Iterator<Item = ExportType> + Sized> ExportsIterator<I> {
610    /// Create a new `ExportsIterator` for a given iterator and size
611    pub fn new(iter: I, size: usize) -> Self {
612        Self { iter, size }
613    }
614}
615
616impl<I: Iterator<Item = ExportType> + Sized> ExactSizeIterator for ExportsIterator<I> {
617    // We can easily calculate the remaining number of iterations.
618    fn len(&self) -> usize {
619        self.size
620    }
621}
622
623impl<I: Iterator<Item = ExportType> + Sized> ExportsIterator<I> {
624    /// Get only the functions
625    pub fn functions(self) -> impl Iterator<Item = ExportType<FunctionType>> + Sized {
626        self.iter.filter_map(|extern_| match extern_.ty() {
627            ExternType::Function(ty) => Some(ExportType::new(extern_.name(), ty.clone())),
628            _ => None,
629        })
630    }
631    /// Get only the memories
632    pub fn memories(self) -> impl Iterator<Item = ExportType<MemoryType>> + Sized {
633        self.iter.filter_map(|extern_| match extern_.ty() {
634            ExternType::Memory(ty) => Some(ExportType::new(extern_.name(), *ty)),
635            _ => None,
636        })
637    }
638    /// Get only the tables
639    pub fn tables(self) -> impl Iterator<Item = ExportType<TableType>> + Sized {
640        self.iter.filter_map(|extern_| match extern_.ty() {
641            ExternType::Table(ty) => Some(ExportType::new(extern_.name(), *ty)),
642            _ => None,
643        })
644    }
645    /// Get only the globals
646    pub fn globals(self) -> impl Iterator<Item = ExportType<GlobalType>> + Sized {
647        self.iter.filter_map(|extern_| match extern_.ty() {
648            ExternType::Global(ty) => Some(ExportType::new(extern_.name(), *ty)),
649            _ => None,
650        })
651    }
652}
653
654impl<I: Iterator<Item = ExportType> + Sized> Iterator for ExportsIterator<I> {
655    type Item = ExportType;
656    fn next(&mut self) -> Option<Self::Item> {
657        self.iter.next()
658    }
659}
660
661/// This iterator allows us to iterate over the imports
662/// and offer nice API ergonomics over it.
663pub struct ImportsIterator<I: Iterator<Item = ImportType> + Sized> {
664    iter: I,
665    size: usize,
666}
667
668impl<I: Iterator<Item = ImportType> + Sized> ImportsIterator<I> {
669    /// Create a new `ImportsIterator` for a given iterator and size
670    pub fn new(iter: I, size: usize) -> Self {
671        Self { iter, size }
672    }
673}
674
675impl<I: Iterator<Item = ImportType> + Sized> ExactSizeIterator for ImportsIterator<I> {
676    // We can easily calculate the remaining number of iterations.
677    fn len(&self) -> usize {
678        self.size
679    }
680}
681
682impl<I: Iterator<Item = ImportType> + Sized> ImportsIterator<I> {
683    /// Get only the functions
684    pub fn functions(self) -> impl Iterator<Item = ImportType<FunctionType>> + Sized {
685        self.iter.filter_map(|extern_| match extern_.ty() {
686            ExternType::Function(ty) => Some(ImportType::new(
687                extern_.module(),
688                extern_.name(),
689                ty.clone(),
690            )),
691            _ => None,
692        })
693    }
694    /// Get only the memories
695    pub fn memories(self) -> impl Iterator<Item = ImportType<MemoryType>> + Sized {
696        self.iter.filter_map(|extern_| match extern_.ty() {
697            ExternType::Memory(ty) => Some(ImportType::new(extern_.module(), extern_.name(), *ty)),
698            _ => None,
699        })
700    }
701    /// Get only the tables
702    pub fn tables(self) -> impl Iterator<Item = ImportType<TableType>> + Sized {
703        self.iter.filter_map(|extern_| match extern_.ty() {
704            ExternType::Table(ty) => Some(ImportType::new(extern_.module(), extern_.name(), *ty)),
705            _ => None,
706        })
707    }
708    /// Get only the globals
709    pub fn globals(self) -> impl Iterator<Item = ImportType<GlobalType>> + Sized {
710        self.iter.filter_map(|extern_| match extern_.ty() {
711            ExternType::Global(ty) => Some(ImportType::new(extern_.module(), extern_.name(), *ty)),
712            _ => None,
713        })
714    }
715}
716
717impl<I: Iterator<Item = ImportType> + Sized> Iterator for ImportsIterator<I> {
718    type Item = ImportType;
719    fn next(&mut self) -> Option<Self::Item> {
720        self.iter.next()
721    }
722}