1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use crate::core::reader::span::Span;
use crate::core::reader::{WasmReadable, WasmReader};
use crate::execution::assert_validated::UnwrapValidatedExt;
use crate::{unreachable_validated, Error, Result};

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum SectionTy {
    Custom = 0,
    Type = 1,
    Import = 2,
    Function = 3,
    Table = 4,
    Memory = 5,
    Global = 6,
    Export = 7,
    Start = 8,
    Element = 9,
    Code = 10,
    Data = 11,
    DataCount = 12,
}

impl WasmReadable for SectionTy {
    fn read(wasm: &mut WasmReader) -> Result<Self> {
        use SectionTy::*;
        let ty = match wasm.read_u8()? {
            0 => Custom,
            1 => Type,
            2 => Import,
            3 => Function,
            4 => Table,
            5 => Memory,
            6 => Global,
            7 => Export,
            8 => Start,
            9 => Element,
            10 => Code,
            11 => Data,
            12 => DataCount,
            other => return Err(Error::InvalidSectionType(other)),
        };

        Ok(ty)
    }

    fn read_unvalidated(wasm: &mut WasmReader) -> Self {
        use SectionTy::*;
        match wasm.read_u8().unwrap_validated() {
            0 => Custom,
            1 => Type,
            2 => Import,
            3 => Function,
            4 => Table,
            5 => Memory,
            6 => Global,
            7 => Export,
            8 => Start,
            9 => Element,
            10 => Code,
            11 => Data,
            12 => DataCount,
            _ => unreachable_validated!(),
        }
    }
}

#[derive(Debug)]
pub(crate) struct SectionHeader {
    pub ty: SectionTy,
    pub contents: Span,
}

impl WasmReadable for SectionHeader {
    fn read(wasm: &mut WasmReader) -> Result<Self> {
        let ty = SectionTy::read(wasm)?;
        let size: u32 = wasm.read_var_u32()?;
        let contents_span = wasm.make_span(size as usize)?;

        Ok(SectionHeader {
            ty,
            contents: contents_span,
        })
    }

    fn read_unvalidated(wasm: &mut WasmReader) -> Self {
        let ty = SectionTy::read_unvalidated(wasm);
        let size: u32 = wasm.read_var_u32().unwrap_validated();
        let contents_span = wasm
            .make_span(size as usize)
            .expect("TODO remove this expect");

        SectionHeader {
            ty,
            contents: contents_span,
        }
    }
}