Skip to main content

sgxs/
util.rs

1/* Copyright (c) Fortanix, Inc.
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7/// Given a size in bytes, return the size in bytes of the total full pages
8/// required to cover the size.
9pub fn size_fit_page(size: u64) -> u64 {
10    match size & 0xfff {
11        0 => size,
12        remainder => size + (0x1000 - remainder),
13    }
14}
15
16/// Given a size in bytes, return the size in bytes of the naturally-aligned
17/// structure required to cover the size.
18///
19/// This is the smallest power of two that is equal to or higher than the input
20/// size.
21pub fn size_fit_natural(size: u64) -> u64 {
22    use std::num::Wrapping;
23    let mut v = Wrapping(size);
24    v -= Wrapping(1);
25    v |= v >> 1;
26    v |= v >> 2;
27    v |= v >> 4;
28    v |= v >> 8;
29    v |= v >> 16;
30    v |= v >> 32;
31    v += Wrapping(1);
32    v.0
33}
34
35#[test]
36fn test_size_fit_natural() {
37    let mut i = 0x1000;
38    loop {
39        assert_eq!(size_fit_natural(i - 1), i);
40        assert_eq!(size_fit_natural(i), i);
41        assert_eq!(size_fit_natural(i + 1), i << 1);
42        if i > 0x8000_0000_0000_0000 {
43            i <<= 1;
44        } else {
45            break;
46        }
47    }
48}