Skip to content

Commit 030218a

Browse files
committed
Initial commit: Create a simple volatile wrapper type
0 parents  commit 030218a

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
target
2+
Cargo.lock

Cargo.toml

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[package]
2+
name = "volatile"
3+
version = "0.1.0"
4+
authors = ["Philipp Oppermann <[email protected]>"]
5+
license = "MIT OR Apache-2.0"
6+
keywords = ["volatile"]
7+
documentation = "https://docs.rs/volatile"
8+
repository = "https://github.com/phil-opp/volatile"
9+
10+
[dependencies]

src/lib.rs

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#![no_std]
2+
3+
use core::ptr;
4+
5+
#[derive(Debug)]
6+
pub struct Volatile<T: Copy>(T);
7+
8+
impl<T: Copy> Volatile<T> {
9+
pub fn read(&self) -> T {
10+
unsafe { ptr::read_volatile(&self.0) }
11+
}
12+
13+
pub fn write(&mut self, value: T) {
14+
unsafe { ptr::write_volatile(&mut self.0, value) };
15+
}
16+
17+
pub fn update<F>(&mut self, f: F)
18+
where F: FnOnce(&mut T)
19+
{
20+
let mut value = self.read();
21+
f(&mut value);
22+
self.write(value);
23+
}
24+
}
25+
26+
#[cfg(test)]
27+
mod tests {
28+
use super::Volatile;
29+
30+
#[test]
31+
fn test_read() {
32+
assert_eq!(Volatile(42).read(), 42);
33+
}
34+
35+
#[test]
36+
fn test_write() {
37+
let mut volatile = Volatile(42);
38+
volatile.write(50);
39+
assert_eq!(volatile.0, 50);
40+
}
41+
42+
#[test]
43+
fn test_update() {
44+
let mut volatile = Volatile(42);
45+
volatile.update(|v| *v += 1);
46+
assert_eq!(volatile.0, 43);
47+
}
48+
}

0 commit comments

Comments
 (0)