From 87a7e94f5c2eb8023724813e2f8178dc3d781b48 Mon Sep 17 00:00:00 2001 From: matejcik Date: Fri, 28 Jan 2022 11:22:33 +0100 Subject: [PATCH] feat(core/rust): add saturating multiplication by f32 to Duration --- core/embed/rust/src/time.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/core/embed/rust/src/time.rs b/core/embed/rust/src/time.rs index e2ea3d922..d96477977 100644 --- a/core/embed/rust/src/time.rs +++ b/core/embed/rust/src/time.rs @@ -1,4 +1,7 @@ -use core::{cmp::Ordering, ops::Div}; +use core::{ + cmp::Ordering, + ops::{Div, Mul}, +}; use crate::micropython::time; @@ -35,7 +38,19 @@ impl Duration { } } +impl Mul for Duration { + // Multiplication by float is saturating -- in particular, casting from a float to + // an int is saturating, value larger than INT_MAX casts to INT_MAX. So this + // operation does not need to be checked. + type Output = Self; + + fn mul(self, rhs: f32) -> Self::Output { + Self::from_millis((self.millis as f32 * rhs) as u32) + } +} + impl Div for Duration { + // Division by integer cannot overflow so it does not need to be checked. type Output = Self; fn div(self, rhs: u32) -> Self::Output { @@ -44,6 +59,7 @@ impl Div for Duration { } impl Div for Duration { + // Division by float results in float so it does not need to be checked. type Output = f32; fn div(self, rhs: Self) -> Self::Output {