Skip to main content

wasm_encoder/core/
tags.rs

1use crate::{Encode, Section, SectionId, encode_section};
2use alloc::vec::Vec;
3
4/// An encoder for the tag section.
5///
6/// # Example
7///
8/// ```
9/// use wasm_encoder::{Module, TagSection, TagType, TagKind};
10///
11/// let mut tags = TagSection::new();
12/// tags.tag(TagType {
13///     kind: TagKind::Exception,
14///     func_type_idx: 0,
15/// });
16///
17/// let mut module = Module::new();
18/// module.section(&tags);
19///
20/// let wasm_bytes = module.finish();
21/// ```
22#[derive(Clone, Default, Debug)]
23pub struct TagSection {
24    bytes: Vec<u8>,
25    num_added: u32,
26}
27
28impl TagSection {
29    /// Create a new tag section encoder.
30    pub fn new() -> Self {
31        Self::default()
32    }
33
34    /// The number of tags in the section.
35    pub fn len(&self) -> u32 {
36        self.num_added
37    }
38
39    /// Determines if the section is empty.
40    pub fn is_empty(&self) -> bool {
41        self.num_added == 0
42    }
43
44    /// Define a tag.
45    pub fn tag(&mut self, tag_type: TagType) -> &mut Self {
46        tag_type.encode(&mut self.bytes);
47        self.num_added += 1;
48        self
49    }
50}
51
52impl Encode for TagSection {
53    fn encode(&self, sink: &mut Vec<u8>) {
54        encode_section(sink, self.num_added, &self.bytes);
55    }
56}
57
58impl Section for TagSection {
59    fn id(&self) -> u8 {
60        SectionId::Tag.into()
61    }
62}
63
64/// Represents a tag kind.
65#[repr(u8)]
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum TagKind {
68    /// The tag is an exception type.
69    Exception = 0x0,
70}
71
72/// A tag's type.
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub struct TagType {
75    /// The kind of tag
76    pub kind: TagKind,
77    /// The function type this tag uses
78    pub func_type_idx: u32,
79}
80
81impl Encode for TagType {
82    fn encode(&self, sink: &mut Vec<u8>) {
83        sink.push(self.kind as u8);
84        self.func_type_idx.encode(sink);
85    }
86}