Skip to content

Commit

Permalink
Merge pull request #3 from metasim/feature/try-from
Browse files Browse the repository at this point in the history
Replaced `From<f64>` with `TryFrom<f64>`
  • Loading branch information
xpe authored Aug 13, 2024
2 parents 9fd4e8a + bfae1ae commit afe404e
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 14 deletions.
13 changes: 8 additions & 5 deletions src/gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,16 @@ fn generate_from_data(data: Data) -> syn::Result<TokenStream> {
}
}

impl From<#f64> for #name {
fn from(value: #f64) -> Self {
impl TryFrom<#f64> for #name {
type Error = Box<dyn std::error::Error + Send + Sync>;
fn try_from(value: #f64) -> std::result::Result<Self, Self::Error> {
if !(Self::MIN_FLOAT..=Self::MAX_FLOAT).contains(&value) {
panic!("{} is out of range for {}", value, Self::Q_NOTATION);
Err(format!("{} is out of range for {}", value, Self::Q_NOTATION).into())
}
else {
let n = (value * Self::CONVERSION_FACTOR) as #inner_type;
Ok(Self(n & Self::USED_MASK))
}
let n = (value * Self::CONVERSION_FACTOR) as #inner_type;
Self(n & Self::USED_MASK)
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@
//! ```
//! # use q_num::define_q_num;
//! define_q_num!(X, Q6.2);
//! let a = X::from(13.75);
//! let b = X::from(-2.25);
//! let c = X::from(11.5);
//! let a = X::try_from(13.75).unwrap();
//! let b = X::try_from(-2.25).unwrap();
//! let c = X::try_from(11.5).unwrap();
//! assert_eq!(a + b, c);
//! ```
//!
Expand Down
12 changes: 6 additions & 6 deletions tests/macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ fn test_q12p5_constants() {
#[test]
fn test_q12p5_add() {
define_q_num!(X, Q12.5);
let x1 = X::from(500.25);
let x2 = X::from(-744.75);
let x3 = X::from(-244.5);
let x1 = X::try_from(500.25).unwrap();
let x2 = X::try_from(-744.75).unwrap();
let x3 = X::try_from(-244.5).unwrap();
let b1 = x1.to_bits();
let b2 = x2.to_bits();
let b3 = x3.to_bits();
Expand Down Expand Up @@ -89,7 +89,7 @@ fn test_q5p3_inner_values() {
define_q_num!(Q, UQ5.3);
let mut value = 0.0;
for byte in 0..0b1111_1111 {
let q = Q::from(value);
let q = Q::try_from(value).unwrap();
assert_eq!(q.to_bits(), byte);
value += 0.125;
}
Expand All @@ -103,7 +103,7 @@ fn test_q4p2_inner_values() {
define_q_num!(Q, UQ4.2);
let mut value = 0.0;
for byte in (0..0b1111_1100).step_by(0b100) {
let q = Q::from(value);
let q = Q::try_from(value).unwrap();
assert_eq!(q.to_bits(), byte);
value += 0.25;
}
Expand All @@ -114,5 +114,5 @@ fn test_q4p2_inner_values() {
#[should_panic]
fn test_q4p2_out_of_range() {
define_q_num!(Q, Q4.2);
let _ = Q::from(16.00);
let _ = Q::try_from(16.00).unwrap();
}

0 comments on commit afe404e

Please sign in to comment.