Skip to content

Commit 33f55ec

Browse files
committed
Added helper types for delayed or exactly once initialisation
Signed-off-by: SlyMarbo <[email protected]>
1 parent e93db68 commit 33f55ec

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed

kernel/src/structures/lazy.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//! lazy implements a simple wrapper type, which can be left
2+
//! uninitialised until it is written to for the first time.
3+
4+
use core::ops::{Deref, DerefMut};
5+
6+
/// Lazy is a wrapper type that can be left uninitialized until
7+
/// the first time it is overwritten.
8+
///
9+
pub struct Lazy<T> {
10+
value: Option<T>,
11+
}
12+
13+
impl<T> Lazy<T> {
14+
pub const fn new() -> Lazy<T> {
15+
Lazy { value: None }
16+
}
17+
18+
pub fn get(&self) -> &T {
19+
self.value.as_ref().expect("Lazy not yet initialised")
20+
}
21+
22+
pub fn get_mut(&mut self) -> &mut T {
23+
self.value.as_mut().expect("Lazy not yet initialised")
24+
}
25+
26+
pub fn set(&mut self, value: T) {
27+
self.value = Some(value);
28+
}
29+
}
30+
31+
impl<T> Deref for Lazy<T> {
32+
type Target = T;
33+
34+
fn deref(&self) -> &T {
35+
self.get()
36+
}
37+
}
38+
39+
impl<T> DerefMut for Lazy<T> {
40+
fn deref_mut(&mut self) -> &mut T {
41+
self.get_mut()
42+
}
43+
}

kernel/src/structures/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
//! structures implements various data structures used elsewhere in the kernel.
22
33
pub mod bitmap;
4+
pub mod lazy;
5+
pub mod once;

kernel/src/structures/once.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//! once implements a simple wrapper type, which is initialised
2+
//! exactly once.
3+
4+
use core::ops::{Deref, DerefMut};
5+
6+
/// Once is a wrapper, which is initialised
7+
/// extacly once.
8+
///
9+
pub struct Once<T> {
10+
inner: spin::Once<T>,
11+
}
12+
13+
impl<T> Once<T> {
14+
pub const fn new() -> Once<T> {
15+
Once {
16+
inner: spin::Once::new(),
17+
}
18+
}
19+
20+
pub fn init<F: FnOnce() -> T>(&self, f: F) {
21+
assert!(!self.inner.is_completed());
22+
self.inner.call_once(f);
23+
}
24+
}
25+
26+
impl<T> Deref for Once<T> {
27+
type Target = T;
28+
29+
fn deref(&self) -> &T {
30+
self.inner.get().expect("Once not yet initialised")
31+
}
32+
}
33+
34+
impl<T> DerefMut for Once<T> {
35+
fn deref_mut(&mut self) -> &mut T {
36+
self.inner.get_mut().expect("Once not yet initialised")
37+
}
38+
}

0 commit comments

Comments
 (0)