wasmparser_nostd/readers/core/
custom.rs

1use crate::{BinaryReader, Result};
2use ::core::ops::Range;
3
4/// A reader for custom sections of a WebAssembly module.
5#[derive(Clone)]
6pub struct CustomSectionReader<'a> {
7    // NB: these fields are public to the crate to make testing easier.
8    pub(crate) name: &'a str,
9    pub(crate) data_offset: usize,
10    pub(crate) data: &'a [u8],
11    pub(crate) range: Range<usize>,
12}
13
14impl<'a> CustomSectionReader<'a> {
15    /// Constructs a new `CustomSectionReader` for the given data and offset.
16    pub fn new(data: &'a [u8], offset: usize) -> Result<CustomSectionReader<'a>> {
17        let mut reader = BinaryReader::new_with_offset(data, offset);
18        let name = reader.read_string()?;
19        let data_offset = reader.original_position();
20        let data = reader.remaining_buffer();
21        let range = reader.range();
22        Ok(CustomSectionReader {
23            name,
24            data_offset,
25            data,
26            range,
27        })
28    }
29
30    /// The name of the custom section.
31    pub fn name(&self) -> &'a str {
32        self.name
33    }
34
35    /// The offset, relative to the start of the original module or component,
36    /// that the `data` payload for this custom section starts at.
37    pub fn data_offset(&self) -> usize {
38        self.data_offset
39    }
40
41    /// The actual contents of the custom section.
42    pub fn data(&self) -> &'a [u8] {
43        self.data
44    }
45
46    /// The range of bytes that specify this whole custom section (including
47    /// both the name of this custom section and its data) specified in
48    /// offsets relative to the start of the byte stream.
49    pub fn range(&self) -> Range<usize> {
50        self.range.clone()
51    }
52}
53
54impl<'a> ::core::fmt::Debug for CustomSectionReader<'a> {
55    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
56        f.debug_struct("CustomSectionReader")
57            .field("name", &self.name)
58            .field("data_offset", &self.data_offset)
59            .field("data", &"...")
60            .field("range", &self.range)
61            .finish()
62    }
63}