parse names in custom section

This commit is contained in:
NikVolf 2018-01-18 19:26:30 +03:00
parent d3226952ec
commit fa87fff6d0
2 changed files with 44 additions and 1 deletions

View File

@ -6,6 +6,7 @@ use super::section::{
Section, CodeSection, TypeSection, ImportSection, ExportSection, FunctionSection,
GlobalSection, TableSection, ElementSection, DataSection, MemorySection
};
use super::name_section::NameSection;
const WASM_MAGIC_NUMBER: [u8; 4] = [0x00, 0x61, 0x73, 0x6d];
@ -142,6 +143,36 @@ impl Module {
}
None
}
pub fn parse_names(mut self) -> Result<Self, (Vec<(usize, Error)>, Self)> {
let mut parse_errors = Vec::new();
for i in 0..self.sections.len() {
if let Some(name_section) = {
let section = self.sections.get(i).expect("cannot fail because i in range 0..len; qed");
if let Section::Custom(ref custom) = *section {
if custom.name() == "name" {
let mut rdr = io::Cursor::new(custom.payload());
let name_section = match NameSection::deserialize(&self, &mut rdr) {
Ok(ns) => ns,
Err(e) => { parse_errors.push((i, e)); continue; }
};
Some(name_section)
} else {
None
}
} else { None }
} {
*self.sections.get_mut(i).expect("cannot fail because i in range 0..len; qed") = Section::Name(name_section);
}
}
if parse_errors.len() > 0 {
Err((parse_errors, self))
} else {
Ok(self)
}
}
}
impl Deserialize for Module {
@ -395,7 +426,7 @@ mod integration_tests {
fn module_default_round_trip() {
let module1 = Module::default();
let buf = serialize(module1).expect("Serialization should succeed");
let module2: Module = deserialize_buffer(&buf).expect("Deserialization should succeed");
assert_eq!(Module::default().magic, module2.magic);
}

View File

@ -19,9 +19,11 @@ use super::{
CountedWriter,
CountedListWriter,
External,
serialize,
};
use super::types::Type;
use super::name_section::NameSection;
/// Section in the WebAssembly module.
#[derive(Debug, Clone)]
@ -57,6 +59,8 @@ pub enum Section {
Code(CodeSection),
/// Data definition section
Data(DataSection),
/// Name section
Name(NameSection),
}
impl Deserialize for Section {
@ -175,6 +179,14 @@ impl Serialize for Section {
VarUint7::from(0x0b).serialize(writer)?;
data_section.serialize(writer)?;
},
Section::Name(name_section) => {
VarUint7::from(0x00).serialize(writer)?;
let custom = CustomSection {
name: "name".to_owned(),
payload: serialize(name_section)?,
};
custom.serialize(writer)?;
}
}
Ok(())
}