Skip to content

Commit 7e351b8

Browse files
committed
riscv: add result module
Adds the `result` module to contain types for fallible functions. For discussion, see: <#212 (comment)>
1 parent 9d3fb05 commit 7e351b8

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

riscv/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ pub(crate) mod bits;
4040
pub mod delay;
4141
pub mod interrupt;
4242
pub mod register;
43+
pub mod result;
4344

4445
#[macro_use]
4546
mod macros;

riscv/src/result.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
use core::fmt;
2+
3+
/// Convenience alias for the [Result](core::result::Result) type for the library.
4+
pub type Result<T> = core::result::Result<T, Error>;
5+
6+
/// Represents error variants for the library.
7+
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
8+
pub enum Error {
9+
/// Attempted out-of-bounds access.
10+
IndexOutOfBounds {
11+
index: usize,
12+
min: usize,
13+
max: usize,
14+
},
15+
/// Invalid field value.
16+
InvalidValue {
17+
field: &'static str,
18+
value: usize,
19+
bitmask: usize,
20+
},
21+
/// Invalid value of a register field that does not match any known variants.
22+
InvalidVariant { field: &'static str, value: usize },
23+
/// Unimplemented function or type.
24+
Unimplemented,
25+
}
26+
27+
impl fmt::Display for Error {
28+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29+
match self {
30+
Self::IndexOutOfBounds { index, min, max } => write!(
31+
f,
32+
"out-of-bounds access, index: {index}, min: {min}, max: {max}"
33+
),
34+
Self::InvalidValue {
35+
field,
36+
value,
37+
bitmask,
38+
} => write!(
39+
f,
40+
"invalid {field} field value: {value:#x}, valid bitmask: {bitmask:#x}",
41+
),
42+
Self::InvalidVariant { field, value } => {
43+
write!(f, "invalid {field} field variant: {value:#x}")
44+
}
45+
Self::Unimplemented => write!(f, "unimplemented"),
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)