From 0e56d1c7a2be78d125a3a246ec2d15636a9eaddb Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Sun, 4 Aug 2024 06:12:45 +0000 Subject: [PATCH] add math::try_into util Signed-off-by: Jason Volk --- src/core/utils/math.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/core/utils/math.rs b/src/core/utils/math.rs index 96ac6dc2..f9d0de30 100644 --- a/src/core/utils/math.rs +++ b/src/core/utils/math.rs @@ -1,8 +1,8 @@ -use std::{cmp, time::Duration}; +use std::{cmp, convert::TryFrom, time::Duration}; pub use checked_ops::checked_ops; -use crate::{Err, Error, Result}; +use crate::{debug::type_name, err, Err, Error, Result}; /// Checked arithmetic expression. Returns a Result #[macro_export] @@ -86,3 +86,17 @@ pub fn ruma_from_usize(val: usize) -> ruma::UInt { #[must_use] #[allow(clippy::as_conversions, clippy::cast_possible_truncation)] pub fn usize_from_u64_truncated(val: u64) -> usize { val as usize } + +#[inline] +pub fn try_into, Src>(src: Src) -> Result { + Dst::try_from(src).map_err(try_into_err::) +} + +fn try_into_err, Src>(e: >::Error) -> Error { + drop(e); + err!(Arithmetic( + "failed to convert from {} to {}", + type_name::(), + type_name::() + )) +}