Add ExpectInto numerological conversion trait. (#357)

Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
Jason Volk
2026-03-08 10:14:23 +00:00
parent 3fcfcafdd2
commit cf7a4dc88d
3 changed files with 24 additions and 6 deletions

View File

@@ -1,3 +1,4 @@
mod expect_into;
mod expected;
mod tried;
@@ -5,7 +6,7 @@ use std::convert::TryFrom;
pub use checked_ops::checked_ops;
pub use self::{expected::Expected, tried::Tried};
pub use self::{expect_into::ExpectInto, expected::Expected, tried::Tried};
use crate::{Err, Error, Result, debug::type_name, err};
/// Checked arithmetic expression. Returns a Result<R, Error::Arithmetic>
@@ -100,6 +101,11 @@ pub fn ruma_from_usize(val: usize) -> ruma::UInt {
#[expect(clippy::as_conversions, clippy::cast_possible_truncation)]
pub fn usize_from_u64_truncated(val: u64) -> usize { val as usize }
#[inline]
pub fn expect_into<Dst: TryFrom<Src>, Src>(src: Src) -> Dst {
try_into(src).expect("failed conversion from Src to Dst")
}
#[inline]
pub fn try_into<Dst: TryFrom<Src>, Src>(src: Src) -> Result<Dst> {
Dst::try_from(src).map_err(|_| {

View File

@@ -0,0 +1,12 @@
pub trait ExpectInto {
#[inline]
#[must_use]
fn expect_into<Dst: TryFrom<Self>>(self) -> Dst
where
Self: Sized,
{
super::expect_into::<Dst, Self>(self)
}
}
impl<T> ExpectInto for T {}

View File

@@ -2,7 +2,7 @@
use nix::sys::resource::{Resource, getrlimit};
use nix::unistd::{SysconfVar, sysconf};
use crate::{Result, apply, debug, utils::math::usize_from_u64_truncated};
use crate::{Result, apply, debug, utils::math::ExpectInto};
#[cfg(unix)]
/// This is needed for opening lots of file descriptors, which tends to
@@ -55,7 +55,7 @@ pub fn maximize_thread_limit() -> Result { Ok(()) }
#[inline]
pub fn max_file_descriptors() -> Result<(usize, usize)> {
getrlimit(Resource::RLIMIT_NOFILE)
.map(apply!(2, usize_from_u64_truncated))
.map(apply!(2, ExpectInto::expect_into))
.map_err(Into::into)
}
@@ -67,7 +67,7 @@ pub fn max_file_descriptors() -> Result<(usize, usize)> { Ok((usize::MAX, usize:
#[inline]
pub fn max_stack_size() -> Result<(usize, usize)> {
getrlimit(Resource::RLIMIT_STACK)
.map(apply!(2, usize_from_u64_truncated))
.map(apply!(2, ExpectInto::expect_into))
.map_err(Into::into)
}
@@ -79,7 +79,7 @@ pub fn max_stack_size() -> Result<(usize, usize)> { Ok((usize::MAX, usize::MAX))
#[inline]
pub fn max_memory_locked() -> Result<(usize, usize)> {
getrlimit(Resource::RLIMIT_MEMLOCK)
.map(apply!(2, usize_from_u64_truncated))
.map(apply!(2, ExpectInto::expect_into))
.map_err(Into::into)
}
@@ -96,7 +96,7 @@ pub fn max_memory_locked() -> Result<(usize, usize)> { Ok((usize::MIN, usize::MI
#[inline]
pub fn max_threads() -> Result<(usize, usize)> {
getrlimit(Resource::RLIMIT_NPROC)
.map(apply!(2, usize_from_u64_truncated))
.map(apply!(2, ExpectInto::expect_into))
.map_err(Into::into)
}