Skip to content

Commit 6cc68f8

Browse files
authored
Merge pull request #19 from rust-osdev/restrict-access
Add methods to restrict access
2 parents c32508b + aca085f commit 6cc68f8

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

Changelog.md

+2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# Unreleased
22

3+
- Add methods to restrict access ([#19](https://github.com/rust-osdev/volatile/pull/19))
4+
35
# 0.4.2 – 2020-10-31
46

57
- Change `slice::check_range` to `RangeBounds::assert_len` ([#16](https://github.com/rust-osdev/volatile/pull/16))

src/lib.rs

+49
Original file line numberDiff line numberDiff line change
@@ -746,6 +746,55 @@ where
746746
}
747747
}
748748

749+
/// Methods for restricting access.
750+
impl<R> Volatile<R> {
751+
/// Restricts access permissions to read-only.
752+
///
753+
/// ## Example
754+
///
755+
/// ```
756+
/// use volatile::Volatile;
757+
///
758+
/// let mut value: i16 = -4;
759+
/// let mut volatile = Volatile::new(&mut value);
760+
///
761+
/// let read_only = volatile.read_only();
762+
/// assert_eq!(read_only.read(), -4);
763+
/// // read_only.write(10); // compile-time error
764+
/// ```
765+
pub fn read_only(self) -> Volatile<R, ReadOnly> {
766+
Volatile {
767+
reference: self.reference,
768+
access: PhantomData,
769+
}
770+
}
771+
772+
/// Restricts access permissions to write-only.
773+
///
774+
/// ## Example
775+
///
776+
/// Creating a write-only reference to a struct field:
777+
///
778+
/// ```
779+
/// use volatile::Volatile;
780+
///
781+
/// struct Example { field_1: u32, field_2: u8, }
782+
/// let mut value = Example { field_1: 15, field_2: 255 };
783+
/// let mut volatile = Volatile::new(&mut value);
784+
///
785+
/// // construct a volatile write-only reference to `field_2`
786+
/// let mut field_2 = volatile.map_mut(|example| &mut example.field_2).write_only();
787+
/// field_2.write(14);
788+
/// // field_2.read(); // compile-time error
789+
/// ```
790+
pub fn write_only(self) -> Volatile<R, WriteOnly> {
791+
Volatile {
792+
reference: self.reference,
793+
access: PhantomData,
794+
}
795+
}
796+
}
797+
749798
impl<R, T, A> fmt::Debug for Volatile<R, A>
750799
where
751800
R: Deref<Target = T>,

0 commit comments

Comments
 (0)