sophon_wasm/elements/
types.rs

1use std::{io, fmt};
2use super::{
3    Deserialize, Serialize, Error, VarUint7, VarInt7, VarUint1, CountedList,
4    CountedListWriter
5};
6
7/// Type definition in types section. Currently can be only of the function type.
8#[derive(Debug, PartialEq, Clone)]
9pub enum Type {
10    /// Function type.
11    Function(FunctionType),
12}
13
14impl Deserialize for Type {
15    type Error = Error;
16
17    fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
18        Ok(Type::Function(FunctionType::deserialize(reader)?))
19    }
20}
21
22impl Serialize for Type {
23    type Error = Error;
24
25    fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
26        match self {
27            Type::Function(fn_type) => fn_type.serialize(writer)
28        }
29    }
30}
31
32/// Value type.
33#[derive(Clone, Copy, PartialEq, Debug)]
34pub enum ValueType {
35    /// 32-bit signed integer
36    I32,
37    /// 64-bit signed integer
38    I64,
39    /// 32-bit float
40    F32,
41    /// 64-bit float
42    F64,
43}
44
45impl Deserialize for ValueType {
46    type Error = Error;
47
48    fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
49        let val = VarInt7::deserialize(reader)?;
50
51        match val.into() {
52            -0x01 => Ok(ValueType::I32),
53            -0x02 => Ok(ValueType::I64),
54            -0x03 => Ok(ValueType::F32),
55            -0x04 => Ok(ValueType::F64),
56            _ => Err(Error::UnknownValueType(val.into())),
57        }
58    }
59}
60
61impl Serialize for ValueType {
62    type Error = Error;
63
64    fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
65        let val: VarInt7 = match self {
66            ValueType::I32 => -0x01,
67            ValueType::I64 => -0x02,
68            ValueType::F32 => -0x03,
69            ValueType::F64 => -0x04,
70        }.into();
71        val.serialize(writer)?;
72        Ok(())
73    }
74}
75
76impl fmt::Display for ValueType {
77    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78        match *self {
79            ValueType::I32 => write!(f, "i32"),
80            ValueType::I64 => write!(f, "i64"),
81            ValueType::F32 => write!(f, "f32"),
82            ValueType::F64 => write!(f, "f64"),
83        }
84    }
85}
86
87/// Block type which is basically `ValueType` + NoResult (to define blocks that have no return type)
88#[derive(Clone, Copy, PartialEq, Debug)]
89pub enum BlockType {
90    /// Value-type specified block type
91    Value(ValueType),
92    /// No specified block type
93    NoResult,
94}
95
96impl Deserialize for BlockType {
97    type Error = Error;
98
99    fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
100        let val = VarInt7::deserialize(reader)?;
101
102        match val.into() {
103            -0x01 => Ok(BlockType::Value(ValueType::I32)),
104            -0x02 => Ok(BlockType::Value(ValueType::I64)),
105            -0x03 => Ok(BlockType::Value(ValueType::F32)),
106            -0x04 => Ok(BlockType::Value(ValueType::F64)),
107            -0x40 => Ok(BlockType::NoResult),
108            _ => Err(Error::UnknownValueType(val.into())),
109        }
110    }
111}
112
113impl Serialize for BlockType {
114    type Error = Error;
115
116    fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
117        let val: VarInt7 = match self {
118            BlockType::NoResult => -0x40i8,
119            BlockType::Value(ValueType::I32) => -0x01,
120            BlockType::Value(ValueType::I64) => -0x02,
121            BlockType::Value(ValueType::F32) => -0x03,
122            BlockType::Value(ValueType::F64) => -0x04,
123        }.into();
124        val.serialize(writer)?;
125        Ok(())
126    }
127}
128
129/// Function signature type.
130#[derive(Debug, Clone, PartialEq)]
131pub struct FunctionType {
132    form: u8,
133    params: Vec<ValueType>,
134    return_type: Option<ValueType>,
135}
136
137impl Default for FunctionType {
138    fn default() -> Self {
139        FunctionType {
140            form: 0x60,
141            params: Vec::new(),
142            return_type: None,
143        }
144    }
145}
146
147impl FunctionType {
148    /// New function type given the signature in-params(`params`) and return type (`return_type`)
149    pub fn new(params: Vec<ValueType>, return_type: Option<ValueType>) -> Self {
150        FunctionType {
151            params: params,
152            return_type: return_type,
153            ..Default::default()
154        }
155    }
156    /// Function form (currently only valid value is `0x60`)
157    pub fn form(&self) -> u8 { self.form }
158    /// Parameters in the function signature.
159    pub fn params(&self) -> &[ValueType] { &self.params }
160    /// Mutable parameters in the function signature.
161    pub fn params_mut(&mut self) -> &mut Vec<ValueType> { &mut self.params }
162    /// Return type in the function signature, if any.
163    pub fn return_type(&self) -> Option<ValueType> { self.return_type }
164    /// Mutable type in the function signature, if any.
165    pub fn return_type_mut(&mut self) -> &mut Option<ValueType> { &mut self.return_type }
166}
167
168impl Deserialize for FunctionType {
169    type Error = Error;
170
171    fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
172        let form: u8 = VarUint7::deserialize(reader)?.into();
173
174        let params: Vec<ValueType> = CountedList::deserialize(reader)?.into_inner();
175
176        let has_return_type = VarUint1::deserialize(reader)?;
177        let return_type = if has_return_type.into() {
178            Some(ValueType::deserialize(reader)?)
179        } else {
180            None
181        };
182
183        Ok(FunctionType {
184            form: form,
185            params: params,
186            return_type: return_type,
187        })
188    }
189}
190
191impl Serialize for FunctionType {
192    type Error = Error;
193
194    fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
195        VarUint7::from(self.form).serialize(writer)?;
196
197        let data = self.params;
198        let counted_list = CountedListWriter::<ValueType, _>(
199            data.len(),
200            data.into_iter().map(Into::into),
201        );
202        counted_list.serialize(writer)?;
203
204        if let Some(return_type) = self.return_type {
205            VarUint1::from(true).serialize(writer)?;
206            return_type.serialize(writer)?;
207        } else {
208            VarUint1::from(false).serialize(writer)?;
209        }
210
211        Ok(())
212    }
213}
214
215/// Table element type.
216#[derive(Clone, Copy, PartialEq, Debug)]
217pub enum TableElementType {
218    /// A reference to a function with any signature.
219    AnyFunc,
220}
221
222impl Deserialize for TableElementType {
223    type Error = Error;
224
225    fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
226        let val = VarInt7::deserialize(reader)?;
227
228        match val.into() {
229            -0x10 => Ok(TableElementType::AnyFunc),
230            _ => Err(Error::UnknownTableElementType(val.into())),
231        }
232    }
233}
234
235impl Serialize for TableElementType {
236    type Error = Error;
237
238    fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
239        let val: VarInt7 = match self {
240            TableElementType::AnyFunc => 0x70,
241        }.into();
242        val.serialize(writer)?;
243        Ok(())
244    }
245}