use super::{
COMPONENT_SORT, CORE_MODULE_SORT, CORE_SORT, FUNCTION_SORT, INSTANCE_SORT, TYPE_SORT,
VALUE_SORT,
};
use crate::{ComponentSection, ComponentSectionId, ComponentTypeRef, Encode, encode_section};
use alloc::vec::Vec;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ComponentExportKind {
Module,
Func,
Value,
Type,
Instance,
Component,
}
impl Encode for ComponentExportKind {
fn encode(&self, sink: &mut Vec<u8>) {
match self {
Self::Module => {
sink.push(CORE_SORT);
sink.push(CORE_MODULE_SORT);
}
Self::Func => {
sink.push(FUNCTION_SORT);
}
Self::Value => {
sink.push(VALUE_SORT);
}
Self::Type => {
sink.push(TYPE_SORT);
}
Self::Instance => {
sink.push(INSTANCE_SORT);
}
Self::Component => {
sink.push(COMPONENT_SORT);
}
}
}
}
#[derive(Clone, Debug, Default)]
pub struct ComponentExportSection {
bytes: Vec<u8>,
num_added: u32,
}
impl ComponentExportSection {
pub fn new() -> Self {
Self::default()
}
pub fn len(&self) -> u32 {
self.num_added
}
pub fn is_empty(&self) -> bool {
self.num_added == 0
}
pub fn export(
&mut self,
name: &str,
kind: ComponentExportKind,
index: u32,
ty: Option<ComponentTypeRef>,
) -> &mut Self {
crate::encode_component_export_name(&mut self.bytes, name);
kind.encode(&mut self.bytes);
index.encode(&mut self.bytes);
match ty {
Some(ty) => {
self.bytes.push(0x01);
ty.encode(&mut self.bytes);
}
None => {
self.bytes.push(0x00);
}
}
self.num_added += 1;
self
}
}
impl Encode for ComponentExportSection {
fn encode(&self, sink: &mut Vec<u8>) {
encode_section(sink, self.num_added, &self.bytes);
}
}
impl ComponentSection for ComponentExportSection {
fn id(&self) -> u8 {
ComponentSectionId::Export.into()
}
}
pub(crate) fn encode_component_export_name(bytes: &mut Vec<u8>, name: &str) {
bytes.push(0x00);
name.encode(bytes);
}