Skip to content
This repository was archived by the owner on Apr 28, 2025. It is now read-only.

Commit 5dea7fc

Browse files
committed
Split cast into cast and cast_lossy
There is a difference in intent between wishing to cast and truncate the value, and expecting the input to be within range. To make this clear, add separate `cast_lossy` and `cast_from_lossy` to indicate what that truncation is intended, leaving `cast` and `cast_from` to only be casts that expected not to truncate. Actually enforcing this at runtime is likely to have a cost, so just `debug_assert!` that `cast` doesn't truncate.
1 parent edc5958 commit 5dea7fc

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/math/support/int_traits.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,18 +343,30 @@ impl_h_int!(
343343
/// Trait to express (possibly lossy) casting of integers
344344
#[allow(unused)]
345345
pub trait CastInto<T: Copy>: Copy {
346+
/// By default, casts should be exact.
346347
fn cast(self) -> T;
348+
349+
/// Call for casts that are expected to truncate.
350+
fn cast_lossy(self) -> T;
347351
}
348352

349353
#[allow(unused)]
350354
pub trait CastFrom<T: Copy>: Copy {
355+
/// By default, casts should be exact.
351356
fn cast_from(value: T) -> Self;
357+
358+
/// Call for casts that are expected to truncate.
359+
fn cast_from_lossy(value: T) -> Self;
352360
}
353361

354362
impl<T: Copy, U: CastInto<T> + Copy> CastFrom<U> for T {
355363
fn cast_from(value: U) -> Self {
356364
value.cast()
357365
}
366+
367+
fn cast_from_lossy(value: U) -> Self {
368+
value.cast_lossy()
369+
}
358370
}
359371

360372
macro_rules! cast_into {
@@ -364,6 +376,13 @@ macro_rules! cast_into {
364376
($ty:ty; $($into:ty),*) => {$(
365377
impl CastInto<$into> for $ty {
366378
fn cast(self) -> $into {
379+
// All we can really do to enforce casting rules is check the rules when in
380+
// debug mode.
381+
debug_assert!(<$into>::try_from(self).is_ok(), "failed cast from {self}");
382+
self as $into
383+
}
384+
385+
fn cast_lossy(self) -> $into {
367386
self as $into
368387
}
369388
}

0 commit comments

Comments
 (0)