/rust/registry/src/index.crates.io-6f17d22bba15001f/wasm-encoder-0.4.1/src/custom.rs
Line | Count | Source (jump to first uncovered line) |
1 | | use super::*; |
2 | | |
3 | | /// A custom section holding arbitrary data. |
4 | | #[derive(Clone, Debug)] |
5 | | pub struct CustomSection<'a> { |
6 | | /// The name of this custom section. |
7 | | pub name: &'a str, |
8 | | /// This custom section's data. |
9 | | pub data: &'a [u8], |
10 | | } |
11 | | |
12 | | impl Section for CustomSection<'_> { |
13 | 0 | fn id(&self) -> u8 { |
14 | 0 | SectionId::Custom.into() |
15 | 0 | } |
16 | | |
17 | 0 | fn encode<S>(&self, sink: &mut S) |
18 | 0 | where |
19 | 0 | S: Extend<u8>, |
20 | 0 | { |
21 | 0 | let name_len = encoders::u32(u32::try_from(self.name.len()).unwrap()); |
22 | 0 | let n = name_len.len(); |
23 | 0 |
|
24 | 0 | sink.extend( |
25 | 0 | encoders::u32(u32::try_from(n + self.name.len() + self.data.len()).unwrap()) |
26 | 0 | .chain(name_len) |
27 | 0 | .chain(self.name.as_bytes().iter().copied()) |
28 | 0 | .chain(self.data.iter().copied()), |
29 | 0 | ); |
30 | 0 | } |
31 | | } |
32 | | |
33 | | #[cfg(test)] |
34 | | mod tests { |
35 | | use super::*; |
36 | | |
37 | | #[test] |
38 | | fn test_custom_section() { |
39 | | let custom = CustomSection { |
40 | | name: "test", |
41 | | data: &[11, 22, 33, 44], |
42 | | }; |
43 | | |
44 | | let mut encoded = vec![]; |
45 | | custom.encode(&mut encoded); |
46 | | |
47 | | #[rustfmt::skip] |
48 | | assert_eq!(encoded, vec![ |
49 | | // LEB128 length of section. |
50 | | 9, |
51 | | // LEB128 length of name. |
52 | | 4, |
53 | | // Name. |
54 | | b't', b'e', b's', b't', |
55 | | // Data. |
56 | | 11, 22, 33, 44, |
57 | | ]); |
58 | | } |
59 | | } |