diff --git a/src/elements/module.rs b/src/elements/module.rs index 789c4e1..f85af7a 100644 --- a/src/elements/module.rs +++ b/src/elements/module.rs @@ -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)> { + 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); } diff --git a/src/elements/section.rs b/src/elements/section.rs index 539cfa2..f6c84e1 100644 --- a/src/elements/section.rs +++ b/src/elements/section.rs @@ -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(()) }