wasm_encoder/core/
imports.rs1use crate::{
2 encode_section, Encode, GlobalType, MemoryType, Section, SectionId, TableType, TagType,
3 CORE_FUNCTION_SORT, CORE_GLOBAL_SORT, CORE_MEMORY_SORT, CORE_TABLE_SORT, CORE_TAG_SORT,
4};
5use alloc::vec::Vec;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum EntityType {
10 Function(u32),
14 Table(TableType),
16 Memory(MemoryType),
18 Global(GlobalType),
20 Tag(TagType),
24}
25
26impl Encode for EntityType {
27 fn encode(&self, sink: &mut Vec<u8>) {
28 match self {
29 Self::Function(i) => {
30 sink.push(CORE_FUNCTION_SORT);
31 i.encode(sink);
32 }
33 Self::Table(t) => {
34 sink.push(CORE_TABLE_SORT);
35 t.encode(sink);
36 }
37 Self::Memory(t) => {
38 sink.push(CORE_MEMORY_SORT);
39 t.encode(sink);
40 }
41 Self::Global(t) => {
42 sink.push(CORE_GLOBAL_SORT);
43 t.encode(sink);
44 }
45 Self::Tag(t) => {
46 sink.push(CORE_TAG_SORT);
47 t.encode(sink);
48 }
49 }
50 }
51}
52
53impl From<TableType> for EntityType {
54 fn from(t: TableType) -> Self {
55 Self::Table(t)
56 }
57}
58
59impl From<MemoryType> for EntityType {
60 fn from(t: MemoryType) -> Self {
61 Self::Memory(t)
62 }
63}
64
65impl From<GlobalType> for EntityType {
66 fn from(t: GlobalType) -> Self {
67 Self::Global(t)
68 }
69}
70
71impl From<TagType> for EntityType {
72 fn from(t: TagType) -> Self {
73 Self::Tag(t)
74 }
75}
76
77#[derive(Clone, Debug, Default)]
103pub struct ImportSection {
104 bytes: Vec<u8>,
105 num_added: u32,
106}
107
108impl ImportSection {
109 pub fn new() -> Self {
111 Self::default()
112 }
113
114 pub fn len(&self) -> u32 {
116 self.num_added
117 }
118
119 pub fn is_empty(&self) -> bool {
121 self.num_added == 0
122 }
123
124 pub fn import(&mut self, module: &str, field: &str, ty: impl Into<EntityType>) -> &mut Self {
126 module.encode(&mut self.bytes);
127 field.encode(&mut self.bytes);
128 ty.into().encode(&mut self.bytes);
129 self.num_added += 1;
130 self
131 }
132}
133
134impl Encode for ImportSection {
135 fn encode(&self, sink: &mut Vec<u8>) {
136 encode_section(sink, self.num_added, &self.bytes);
137 }
138}
139
140impl Section for ImportSection {
141 fn id(&self) -> u8 {
142 SectionId::Import.into()
143 }
144}