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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

//! This crate provides a data structure for byte size. With
//! [`x86_64`](https://github.com/rust-osdev/x86_64) crate, you can easily convert
//! the size of physical memory pages into bytes, and bytes into the number of physical memory
//! pages.
//!
//! Currently, this crate only supports Rust nightly version because of using
//! [`const_fn`](https://doc.rust-lang.org/beta/unstable-book/language-features/const-fn.html) feature.
//!
//! # Examples
//!
//! ```rust
//! use os_units::{Size, Bytes};
//! use x86_64::structures::paging::{PageSize, Size4KiB};
//!
//! let bytes_of_kernel = Size::<Bytes>::new(314159);
//! let pages_of_kernel = bytes_of_kernel.as_num_of_pages::<Size4KiB>();
//! assert_eq!(pages_of_kernel.as_usize(), 77);
//!
//! let bytes_of_pages = pages_of_kernel.as_bytes();
//! assert_eq!(bytes_of_pages.as_usize(), 315392);
//! ```
#![no_std]
#![feature(const_fn)]

use core::marker::PhantomData;
use core::ops::{Add, AddAssign, Sub, SubAssign};
use x86_64::structures::paging::PageSize;

/// A marker trait for representing units.
pub trait Unit: Copy + Clone + PartialEq + Eq + PartialOrd + Ord {}

/// A struct representing bytes.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Bytes;
impl Unit for Bytes {}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
/// A struct representing the number of physical pages.
pub struct NumOfPages<T: PageSize> {
    _marker: PhantomData<fn() -> T>,
}
impl<T: PageSize> Unit for NumOfPages<T> {}

#[repr(transparent)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
/// A struct containing the value with the unit specified by generic type.
pub struct Size<T: Unit> {
    val: usize,
    _marker: PhantomData<fn() -> T>,
}

impl<T: Unit> Size<T> {
    /// Creates a new instance with given value.
    pub const fn new(val: usize) -> Self {
        Self {
            val,
            _marker: PhantomData,
        }
    }

    /// Returns the value.
    pub const fn as_usize(self) -> usize {
        self.val
    }
}

impl Size<Bytes> {
    /// Converts bytes to the number of physical pages. Note that the number of physical pages will
    /// be calculated so that the specified bytes will be fit in pages.
    pub const fn as_num_of_pages<T: PageSize>(self) -> Size<NumOfPages<T>> {
        Size {
            val: (self.val + T::SIZE as usize - 1) / T::SIZE as usize,
            _marker: PhantomData,
        }
    }
}

impl<T: PageSize> Size<NumOfPages<T>> {
    /// Convert the number of physical pages to bytes.
    pub const fn as_bytes(self) -> Size<Bytes> {
        Size {
            val: self.val * T::SIZE as usize,
            _marker: PhantomData,
        }
    }
}

impl Add<Size<Bytes>> for Size<Bytes> {
    type Output = Size<Bytes>;

    fn add(self, rhs: Size<Bytes>) -> Self {
        Self::new(self.val + rhs.val)
    }
}

impl<T: PageSize> Add<Size<NumOfPages<T>>> for Size<NumOfPages<T>> {
    type Output = Size<NumOfPages<T>>;

    fn add(self, rhs: Size<NumOfPages<T>>) -> Self {
        Self::new(self.val + rhs.val)
    }
}

impl Sub<Size<Bytes>> for Size<Bytes> {
    type Output = Size<Bytes>;

    fn sub(self, rhs: Size<Bytes>) -> Self {
        Self::new(self.val - rhs.val)
    }
}

impl<T: PageSize> Sub<Size<NumOfPages<T>>> for Size<NumOfPages<T>> {
    type Output = Size<NumOfPages<T>>;

    fn sub(self, rhs: Size<NumOfPages<T>>) -> Self {
        Self::new(self.val - rhs.val)
    }
}

impl AddAssign for Size<Bytes> {
    fn add_assign(&mut self, rhs: Size<Bytes>) {
        *self = Self {
            val: self.val + rhs.val,
            ..*self
        }
    }
}

impl<T: PageSize> AddAssign for Size<NumOfPages<T>> {
    fn add_assign(&mut self, rhs: Size<NumOfPages<T>>) {
        *self = Self {
            val: self.val + rhs.val,
            ..*self
        }
    }
}

impl SubAssign for Size<Bytes> {
    fn sub_assign(&mut self, rhs: Size<Bytes>) {
        *self = Self {
            val: self.val - rhs.val,
            ..*self
        }
    }
}

impl<T: PageSize> SubAssign for Size<NumOfPages<T>> {
    fn sub_assign(&mut self, rhs: Size<NumOfPages<T>>) {
        *self = Self {
            val: self.val - rhs.val,
            ..*self
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use x86_64::structures::paging::{Size1GiB, Size2MiB, Size4KiB};

    #[test]
    fn get_value_from_bytes() {
        let bytes = Size::<Bytes>::new(334);
        assert_eq!(bytes.as_usize(), 334);
    }

    #[test]
    fn get_value_from_num_of_pages() {
        let pages = Size::<NumOfPages<Size4KiB>>::new(334);
        assert_eq!(pages.as_usize(), 334);
    }

    #[test]
    fn bytes_to_pages() {
        let bytes = Size::<Bytes>::new(0x40000000);
        assert_eq!(bytes.as_num_of_pages::<Size4KiB>().as_usize(), 0x40000);
        assert_eq!(bytes.as_num_of_pages::<Size2MiB>().as_usize(), 512);
        assert_eq!(bytes.as_num_of_pages::<Size1GiB>().as_usize(), 1);
    }

    #[test]
    fn pages_to_bytes_4k() {
        let num_of_pages = Size::<NumOfPages<Size4KiB>>::new(1);
        assert_eq!(num_of_pages.as_bytes().as_usize(), 0x1000);
    }

    #[test]
    fn pages_to_bytes_2m() {
        let num_of_pages = Size::<NumOfPages<Size2MiB>>::new(1);
        assert_eq!(num_of_pages.as_bytes().as_usize(), 0x200000);
    }

    #[test]
    fn pages_to_bytes_1g() {
        let num_of_pages = Size::<NumOfPages<Size1GiB>>::new(1);
        assert_eq!(num_of_pages.as_bytes().as_usize(), 0x40000000);
    }

    #[test]
    fn addition_bytes_to_bytes() {
        let b1 = Size::<Bytes>::new(3);
        let b2 = Size::<Bytes>::new(1);
        let sum = b1 + b2;

        assert_eq!(sum.as_usize(), 4);
    }

    #[test]
    fn addition_pages_to_pages() {
        let p1 = Size::<NumOfPages<Size4KiB>>::new(3);
        let p2 = Size::<NumOfPages<Size4KiB>>::new(1);
        let sum = p1 + p2;

        assert_eq!(sum.as_usize(), 4);
    }

    #[test]
    fn subtraction_bytes_from_bytes() {
        let b1 = Size::<Bytes>::new(3);
        let b2 = Size::<Bytes>::new(1);
        let diff = b1 - b2;

        assert_eq!(diff.as_usize(), 2);
    }

    #[test]
    fn subtraction_pages_from_pages() {
        let p1 = Size::<NumOfPages<Size4KiB>>::new(3);
        let p2 = Size::<NumOfPages<Size4KiB>>::new(1);
        let diff = p1 - p2;

        assert_eq!(diff.as_usize(), 2);
    }

    #[test]
    fn add_assign_bytes_to_bytes() {
        let mut b1 = Size::<Bytes>::new(3);
        b1 += Size::<Bytes>::new(1);

        assert_eq!(b1.as_usize(), 4);
    }

    #[test]
    fn add_assign_pages_to_pages() {
        let mut p1 = Size::<NumOfPages<Size4KiB>>::new(3);
        p1 += Size::<NumOfPages<Size4KiB>>::new(1);

        assert_eq!(p1.as_usize(), 4);
    }

    #[test]
    fn sub_assign_bytes_to_bytes() {
        let mut b1 = Size::<Bytes>::new(3);
        b1 -= Size::<Bytes>::new(1);

        assert_eq!(b1.as_usize(), 2);
    }

    #[test]
    fn sub_assign_pages_to_pages() {
        let mut p1 = Size::<NumOfPages<Size4KiB>>::new(3);
        p1 -= Size::<NumOfPages<Size4KiB>>::new(1);

        assert_eq!(p1.as_usize(), 2);
    }
}