Skip to content

Commit 9844981

Browse files
committed
generic progress ratio fns
1 parent 1913076 commit 9844981

File tree

3 files changed

+19
-11
lines changed

3 files changed

+19
-11
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ esp-println = { version = "0.14.0", features = [
5454
] }
5555
log = "0.4.27"
5656
micromath = "2.1.0"
57+
num-traits = { version = "0.2.19", default-features = false }
5758
panic-rtt-target = { version = "0.2.0", features = ["defmt"] }
5859
postcard = { version = "1.1.1", features = ["use-defmt"] }
5960
rotary-encoder-hal = { version = "0.6.0", features = [

src/meeting_instruction.rs

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
#![allow(dead_code)]
22

33
use crate::meeting_duration::MeetingDuration;
4+
use core::ops::{Div, Mul};
45
use defmt::Format;
56
use embassy_time::Duration;
7+
use num_traits::{PrimInt, Unsigned};
68
use serde::{Deserialize, Serialize};
79

810
// fifo_full_threshold (RX)
@@ -47,21 +49,25 @@ impl From<MeetingDuration> for QuarterSeconds {
4749
#[serde(transparent)]
4850
pub struct ProgressRatio(pub u8);
4951
impl ProgressRatio {
50-
fn from_values(numerator: u8, denominator: u8) -> Option<Self> {
51-
if denominator == 0 {
52-
return None; // Avoid division by zero
53-
}
54-
if numerator > denominator {
55-
return None; // Avoid ratios greater than 1
52+
/// Create a ratio from `numerator / denominator`, scaled to 0..=255
53+
pub fn from_values<T>(numerator: T, denominator: T) -> Option<Self>
54+
where
55+
T: PrimInt + Unsigned,
56+
{
57+
if denominator.is_zero() {
58+
return None;
5659
}
5760

58-
let ratio = ((numerator as u16) * (u8::MAX as u16) / denominator as u16) as u8;
59-
Some(Self(ratio))
61+
let scaled = (numerator.to_u32()? * u8::MAX as u32) / denominator.to_u32()?;
62+
Some(Self(scaled.min(u8::MAX as u32) as u8))
6063
}
6164

62-
fn apply_to_value(&self, value: u16) -> u16 {
63-
// Apply the progress ratio to a value
64-
(value as u32 * self.0 as u32 / u8::MAX as u32) as u16
65+
/// Apply the ratio to a value of arbitrary unsigned integer type
66+
pub fn apply_to<T>(&self, value: T) -> T
67+
where
68+
T: Mul<u32, Output = T> + Div<u32, Output = T>,
69+
{
70+
value * self.0 as u32 / u8::MAX as u32
6571
}
6672
}
6773

0 commit comments

Comments
 (0)