wasm_encoder/core/
custom.rs

1use crate::{encoding_size, Encode, Section, SectionId};
2use alloc::borrow::Cow;
3use alloc::vec::Vec;
4
5/// A custom section holding arbitrary data.
6#[derive(Clone, Debug, PartialEq)]
7pub struct CustomSection<'a> {
8    /// The name of this custom section.
9    pub name: Cow<'a, str>,
10    /// This custom section's data.
11    pub data: Cow<'a, [u8]>,
12}
13
14impl Encode for CustomSection<'_> {
15    fn encode(&self, sink: &mut Vec<u8>) {
16        let encoded_name_len = encoding_size(u32::try_from(self.name.len()).unwrap());
17        (encoded_name_len + self.name.len() + self.data.len()).encode(sink);
18        self.name.encode(sink);
19        sink.extend(&*self.data);
20    }
21}
22
23impl Section for CustomSection<'_> {
24    fn id(&self) -> u8 {
25        SectionId::Custom.into()
26    }
27}
28
29/// A raw custom section where the bytes specified contain the leb-encoded
30/// length of the custom section, the custom section's name, and the custom
31/// section's data.
32#[derive(Clone, Debug)]
33pub struct RawCustomSection<'a>(pub &'a [u8]);
34
35impl Encode for RawCustomSection<'_> {
36    fn encode(&self, sink: &mut Vec<u8>) {
37        sink.extend(self.0);
38    }
39}
40
41impl Section for RawCustomSection<'_> {
42    fn id(&self) -> u8 {
43        SectionId::Custom.into()
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50    use alloc::vec;
51
52    #[test]
53    fn test_custom_section() {
54        let custom = CustomSection {
55            name: "test".into(),
56            data: Cow::Borrowed(&[11, 22, 33, 44]),
57        };
58
59        let mut encoded = vec![];
60        custom.encode(&mut encoded);
61
62        #[rustfmt::skip]
63        assert_eq!(encoded, vec![
64            // LEB128 length of section.
65            9,
66            // LEB128 length of name.
67            4,
68            // Name.
69            b't', b'e', b's', b't',
70            // Data.
71            11, 22, 33, 44,
72        ]);
73    }
74}