wasm_encoder/core/
custom.rs1use crate::{encoding_size, Encode, Section, SectionId};
2use alloc::borrow::Cow;
3use alloc::vec::Vec;
4
5#[derive(Clone, Debug, PartialEq)]
7pub struct CustomSection<'a> {
8 pub name: Cow<'a, str>,
10 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#[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 9,
66 4,
68 b't', b'e', b's', b't',
70 11, 22, 33, 44,
72 ]);
73 }
74}