1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
use core::slice;
use std::{str, vec::Vec};

/// Wasm custom sections.
#[derive(Default, Debug)]
pub struct CustomSections {
    inner: CustomSectionsInner,
}

impl CustomSections {
    /// Returns an iterator over the [`CustomSection`]s stored in `self`.
    #[inline]
    pub fn iter(&self) -> CustomSectionsIter {
        self.inner.iter()
    }
}

/// A builder for [`CustomSections`].
#[derive(Default, Debug)]
pub struct CustomSectionsBuilder {
    inner: CustomSectionsInner,
}

impl CustomSectionsBuilder {
    /// Pushes a new custom section segment to the [`CustomSectionsBuilder`].
    #[inline]
    pub fn push(&mut self, name: &str, data: &[u8]) {
        self.inner.push(name, data);
    }

    /// Finalize construction of the [`CustomSections`].
    #[inline]
    pub fn finish(self) -> CustomSections {
        CustomSections { inner: self.inner }
    }
}

/// Internal representation of [`CustomSections`].
#[derive(Debug, Default)]
pub struct CustomSectionsInner {
    /// The name and data lengths of each Wasm custom section.
    items: Vec<CustomSectionInner>,
    /// The combined name and data of all Wasm custom sections.
    names_and_data: Vec<u8>,
}

/// Internal representation of a Wasm [`CustomSection`].
#[derive(Debug, Copy, Clone)]
pub struct CustomSectionInner {
    /// The length in bytes of the Wasm custom section name.
    len_name: usize,
    /// The length in bytes of the Wasm custom section data.
    len_data: usize,
}

impl CustomSectionsInner {
    /// Pushes a new custom section segment to the [`CustomSectionsBuilder`].
    #[inline]
    pub fn push(&mut self, name: &str, data: &[u8]) {
        let name_bytes = name.as_bytes();
        self.names_and_data.extend_from_slice(name_bytes);
        self.names_and_data.extend_from_slice(data);
        self.items.push(CustomSectionInner {
            len_name: name_bytes.len(),
            len_data: data.len(),
        })
    }

    /// Returns an iterator over the [`CustomSection`]s stored in `self`.
    #[inline]
    pub fn iter(&self) -> CustomSectionsIter {
        CustomSectionsIter {
            items: self.items.iter(),
            names_and_data: &self.names_and_data[..],
        }
    }
}

/// A Wasm custom section.
#[derive(Debug)]
pub struct CustomSection<'a> {
    /// The name of the custom section.
    name: &'a str,
    /// The undecoded data of the custom section.
    data: &'a [u8],
}

impl<'a> CustomSection<'a> {
    /// Returns the name or identifier of the [`CustomSection`].
    #[inline]
    pub fn name(&self) -> &'a str {
        self.name
    }

    /// Returns a shared reference to the data of the [`CustomSection`].
    #[inline]
    pub fn data(&self) -> &'a [u8] {
        self.data
    }
}

/// An iterator over the custom sections of a Wasm module.
#[derive(Debug)]
pub struct CustomSectionsIter<'a> {
    items: slice::Iter<'a, CustomSectionInner>,
    names_and_data: &'a [u8],
}

impl<'a> Iterator for CustomSectionsIter<'a> {
    type Item = CustomSection<'a>;

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.items.size_hint()
    }

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let item = self.items.next()?;
        let names_and_data = self.names_and_data;
        let (name, names_and_data) = names_and_data.split_at(item.len_name);
        let (data, names_and_data) = names_and_data.split_at(item.len_data);
        self.names_and_data = names_and_data;
        // Safety: We encoded this part of the data buffer from the bytes of a string previously.
        let name = unsafe { str::from_utf8_unchecked(name) };
        Some(CustomSection { name, data })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let mut builder = CustomSectionsBuilder::default();
        builder.push("A", b"first");
        builder.push("B", b"second");
        builder.push("C", b"third");
        builder.push("", b"fourth"); // empty name
        builder.push("E", &[]); // empty data
        let custom_sections = builder.finish();
        let mut iter = custom_sections.iter();
        assert_eq!(
            iter.next().map(|s| (s.name(), s.data())),
            Some(("A", &b"first"[..]))
        );
        assert_eq!(
            iter.next().map(|s| (s.name(), s.data())),
            Some(("B", &b"second"[..]))
        );
        assert_eq!(
            iter.next().map(|s| (s.name(), s.data())),
            Some(("C", &b"third"[..]))
        );
        assert_eq!(
            iter.next().map(|s| (s.name(), s.data())),
            Some(("", &b"fourth"[..]))
        );
        assert_eq!(
            iter.next().map(|s| (s.name(), s.data())),
            Some(("E", &b""[..]))
        );
        assert_eq!(iter.next().map(|s| (s.name(), s.data())), None);
    }
}