wasmi_core/
units.rs

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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/// An amount of linear memory pages.
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Pages(u32);

impl Pages {
    /// The maximum amount of pages on the `wasm32` target.
    ///
    /// # Note
    ///
    /// This is the maximum since WebAssembly is a 32-bit platform
    /// and a page is 2^16 bytes in size. Therefore there can be at
    /// most 2^16 pages of a single linear memory so that all bytes
    /// are still accessible.
    pub const fn max() -> Self {
        Self(65536) // 2^16
    }
}

impl From<u16> for Pages {
    /// Creates an `amount` of [`Pages`].
    ///
    /// # Note
    ///
    /// This is infallible since `u16` cannot represent invalid amounts
    /// of [`Pages`]. However, `u16` can also not represent [`Pages::max()`].
    ///
    /// [`Pages::max()`]: struct.Pages.html#method.max
    fn from(amount: u16) -> Self {
        Self(u32::from(amount))
    }
}

impl Pages {
    /// Creates a new amount of [`Pages`] if the amount is within bounds.
    ///
    /// Returns `None` if the given `amount` of [`Pages`] exceeds [`Pages::max()`].
    ///
    /// [`Pages::max()`]: struct.Pages.html#method.max
    pub fn new(amount: u32) -> Option<Self> {
        if amount > u32::from(Self::max()) {
            return None;
        }
        Some(Self(amount))
    }

    /// Adds the given amount of pages to `self`.
    ///
    /// Returns `Some` if the result is within bounds and `None` otherwise.
    pub fn checked_add<T>(self, rhs: T) -> Option<Self>
    where
        T: Into<u32>,
    {
        let lhs: u32 = self.into();
        let rhs: u32 = rhs.into();
        lhs.checked_add(rhs).and_then(Self::new)
    }

    /// Substracts the given amount of pages from `self`.
    ///
    /// Returns `None` if the subtraction underflows or the result is out of bounds.
    pub fn checked_sub<T>(self, rhs: T) -> Option<Self>
    where
        T: Into<u32>,
    {
        let lhs: u32 = self.into();
        let rhs: u32 = rhs.into();
        lhs.checked_sub(rhs).and_then(Self::new)
    }

    /// Returns the amount of bytes required for the amount of [`Pages`].
    ///
    /// Returns `None` if the amount of pages represented by `self` cannot
    /// be represented as bytes on the executing platform.
    pub fn to_bytes(self) -> Option<usize> {
        Bytes::new(self).map(Into::into)
    }
}

impl From<Pages> for u32 {
    fn from(pages: Pages) -> Self {
        pages.0
    }
}

/// An amount of bytes of a linear memory.
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Bytes(usize);

impl Bytes {
    /// A 16-bit platform cannot represent the size of a single Wasm page.
    const fn max16() -> u64 {
        i16::MAX as u64 + 1
    }

    /// A 32-bit platform can represent at most i32::MAX + 1 Wasm pages.
    const fn max32() -> u64 {
        i32::MAX as u64 + 1
    }

    /// A 64-bit platform can represent all possible u32::MAX + 1 Wasm pages.
    const fn max64() -> u64 {
        u32::MAX as u64 + 1
    }

    /// The bytes per WebAssembly linear memory page.
    ///
    /// # Note
    ///
    /// As mandated by the WebAssembly specification every linear memory page
    /// has exactly 2^16 (65536) bytes.
    const fn per_page() -> Self {
        Self(65536) // 2^16
    }

    /// Creates [`Bytes`] from the given amount of [`Pages`] if possible.
    ///
    /// Returns `None` if the amount of bytes is out of bounds. This may
    /// happen for example when trying to allocate bytes for more than
    /// `i16::MAX + 1` pages on a 32-bit platform since that amount would
    /// not be representable by a pointer sized `usize`.
    fn new(pages: Pages) -> Option<Bytes> {
        if cfg!(target_pointer_width = "16") {
            Self::new16(pages)
        } else if cfg!(target_pointer_width = "32") {
            Self::new32(pages)
        } else if cfg!(target_pointer_width = "64") {
            Self::new64(pages)
        } else {
            None
        }
    }

    /// Creates [`Bytes`] from the given amount of [`Pages`] as if
    /// on a 16-bit platform if possible.
    ///
    /// Returns `None` otherwise.
    ///
    /// # Note
    ///
    /// This API exists in isolation for cross-platform testing purposes.
    fn new16(pages: Pages) -> Option<Bytes> {
        Self::new_impl(pages, Bytes::max16())
    }

    /// Creates [`Bytes`] from the given amount of [`Pages`] as if
    /// on a 32-bit platform if possible.
    ///
    /// Returns `None` otherwise.
    ///
    /// # Note
    ///
    /// This API exists in isolation for cross-platform testing purposes.
    fn new32(pages: Pages) -> Option<Bytes> {
        Self::new_impl(pages, Bytes::max32())
    }

    /// Creates [`Bytes`] from the given amount of [`Pages`] as if
    /// on a 64-bit platform if possible.
    ///
    /// Returns `None` otherwise.
    ///
    /// # Note
    ///
    /// This API exists in isolation for cross-platform testing purposes.
    fn new64(pages: Pages) -> Option<Bytes> {
        Self::new_impl(pages, Bytes::max64())
    }

    /// Actual underlying implementation of [`Bytes::new`].
    fn new_impl(pages: Pages, max: u64) -> Option<Bytes> {
        let pages = u64::from(u32::from(pages));
        let bytes_per_page = usize::from(Self::per_page()) as u64;
        let bytes = pages
            .checked_mul(bytes_per_page)
            .filter(|&amount| amount <= max)?;
        Some(Self(bytes as usize))
    }
}

impl From<Bytes> for usize {
    #[inline]
    fn from(bytes: Bytes) -> Self {
        bytes.0
    }
}

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

    fn pages(amount: u32) -> Pages {
        Pages::new(amount).unwrap()
    }

    fn bytes(amount: usize) -> Bytes {
        Bytes(amount)
    }

    #[test]
    fn pages_max() {
        assert_eq!(Pages::max(), pages(u32::from(u16::MAX) + 1));
    }

    #[test]
    fn pages_new() {
        assert_eq!(Pages::new(0), Some(Pages(0)));
        assert_eq!(Pages::new(1), Some(Pages(1)));
        assert_eq!(Pages::new(1000), Some(Pages(1000)));
        assert_eq!(
            Pages::new(u32::from(u16::MAX)),
            Some(Pages(u32::from(u16::MAX)))
        );
        assert_eq!(Pages::new(u32::from(u16::MAX) + 1), Some(Pages::max()));
        assert_eq!(Pages::new(u32::from(u16::MAX) + 2), None);
        assert_eq!(Pages::new(u32::MAX), None);
    }

    #[test]
    fn pages_checked_add() {
        let max_pages = u32::from(Pages::max());

        assert_eq!(pages(0).checked_add(0u32), Some(pages(0)));
        assert_eq!(pages(0).checked_add(1u32), Some(pages(1)));
        assert_eq!(pages(1).checked_add(0u32), Some(pages(1)));

        assert_eq!(pages(0).checked_add(max_pages), Some(Pages::max()));
        assert_eq!(pages(0).checked_add(Pages::max()), Some(Pages::max()));
        assert_eq!(pages(1).checked_add(max_pages), None);
        assert_eq!(pages(1).checked_add(Pages::max()), None);

        assert_eq!(Pages::max().checked_add(0u32), Some(Pages::max()));
        assert_eq!(Pages::max().checked_add(1u32), None);
        assert_eq!(pages(0).checked_add(u32::MAX), None);

        for i in 0..100 {
            for j in 0..100 {
                assert_eq!(pages(i).checked_add(pages(j)), Some(pages(i + j)));
            }
        }
    }

    #[test]
    fn pages_checked_sub() {
        let max_pages = u32::from(Pages::max());

        assert_eq!(pages(0).checked_sub(0u32), Some(pages(0)));
        assert_eq!(pages(0).checked_sub(1u32), None);
        assert_eq!(pages(1).checked_sub(0u32), Some(pages(1)));
        assert_eq!(pages(1).checked_sub(1u32), Some(pages(0)));

        assert_eq!(Pages::max().checked_sub(Pages::max()), Some(pages(0)));
        assert_eq!(Pages::max().checked_sub(u32::MAX), None);
        assert_eq!(Pages::max().checked_sub(1u32), Some(pages(max_pages - 1)));

        for i in 0..100 {
            for j in 0..100 {
                assert_eq!(pages(i).checked_sub(pages(j)), i.checked_sub(j).map(pages));
            }
        }
    }

    #[test]
    fn pages_to_bytes() {
        assert_eq!(pages(0).to_bytes(), Some(0));
        if cfg!(target_pointer_width = "16") {
            assert_eq!(pages(1).to_bytes(), None);
        }
        if cfg!(target_pointer_width = "32") || cfg!(target_pointer_width = "64") {
            let bytes_per_page = usize::from(Bytes::per_page());
            for n in 1..10 {
                assert_eq!(pages(n as u32).to_bytes(), Some(n * bytes_per_page));
            }
        }
    }

    #[test]
    fn bytes_new16() {
        assert_eq!(Bytes::new16(pages(0)), Some(bytes(0)));
        assert_eq!(Bytes::new16(pages(1)), None);
        assert!(Bytes::new16(Pages::max()).is_none());
    }

    #[test]
    fn bytes_new32() {
        assert_eq!(Bytes::new32(pages(0)), Some(bytes(0)));
        assert_eq!(Bytes::new32(pages(1)), Some(Bytes::per_page()));
        let bytes_per_page = usize::from(Bytes::per_page());
        for n in 2..10 {
            assert_eq!(
                Bytes::new32(pages(n as u32)),
                Some(bytes(n * bytes_per_page))
            );
        }
        assert!(Bytes::new32(pages(i16::MAX as u32 + 1)).is_some());
        assert!(Bytes::new32(pages(i16::MAX as u32 + 2)).is_none());
        assert!(Bytes::new32(Pages::max()).is_none());
    }

    #[test]
    fn bytes_new64() {
        assert_eq!(Bytes::new64(pages(0)), Some(bytes(0)));
        assert_eq!(Bytes::new64(pages(1)), Some(Bytes::per_page()));
        let bytes_per_page = usize::from(Bytes::per_page());
        for n in 2..10 {
            assert_eq!(
                Bytes::new64(pages(n as u32)),
                Some(bytes(n * bytes_per_page))
            );
        }
        assert!(Bytes::new64(Pages(u32::from(u16::MAX) + 1)).is_some());
        assert!(Bytes::new64(Pages(u32::from(u16::MAX) + 2)).is_none());
        assert!(Bytes::new64(Pages::max()).is_some());
    }
}