use super::{COMPONENT_SORT, CORE_MODULE_SORT, CORE_SORT, CORE_TYPE_SORT, TYPE_SORT};
use crate::{
ComponentExportKind, ComponentSection, ComponentSectionId, Encode, ExportKind, encode_section,
};
use alloc::vec::Vec;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ComponentOuterAliasKind {
CoreModule,
CoreType,
Type,
Component,
}
impl Encode for ComponentOuterAliasKind {
fn encode(&self, sink: &mut Vec<u8>) {
match self {
Self::CoreModule => {
sink.push(CORE_SORT);
sink.push(CORE_MODULE_SORT);
}
Self::CoreType => {
sink.push(CORE_SORT);
sink.push(CORE_TYPE_SORT);
}
Self::Type => sink.push(TYPE_SORT),
Self::Component => sink.push(COMPONENT_SORT),
}
}
}
#[derive(Clone, Debug, Default)]
pub struct ComponentAliasSection {
bytes: Vec<u8>,
num_added: u32,
}
#[derive(Copy, Clone, Debug)]
pub enum Alias<'a> {
InstanceExport {
instance: u32,
kind: ComponentExportKind,
name: &'a str,
},
#[allow(missing_docs)]
CoreInstanceExport {
instance: u32,
kind: ExportKind,
name: &'a str,
},
Outer {
kind: ComponentOuterAliasKind,
count: u32,
index: u32,
},
}
impl ComponentAliasSection {
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 alias(&mut self, alias: Alias<'_>) -> &mut Self {
alias.encode(&mut self.bytes);
self.num_added += 1;
self
}
}
impl Encode for ComponentAliasSection {
fn encode(&self, sink: &mut Vec<u8>) {
encode_section(sink, self.num_added, &self.bytes);
}
}
impl ComponentSection for ComponentAliasSection {
fn id(&self) -> u8 {
ComponentSectionId::Alias.into()
}
}
impl Encode for Alias<'_> {
fn encode(&self, sink: &mut Vec<u8>) {
match self {
Alias::InstanceExport {
instance,
kind,
name,
} => {
kind.encode(sink);
sink.push(0x00);
instance.encode(sink);
name.encode(sink);
}
Alias::CoreInstanceExport {
instance,
kind,
name,
} => {
sink.push(CORE_SORT);
kind.encode(sink);
sink.push(0x01);
instance.encode(sink);
name.encode(sink);
}
Alias::Outer { kind, count, index } => {
kind.encode(sink);
sink.push(0x02);
count.encode(sink);
index.encode(sink);
}
}
}
}