Skip to content

add infallible conversions between different bit sizes#23

Merged
jhpratt merged 5 commits intojhpratt:mainfrom
mcroomp:fromranged
Aug 18, 2025
Merged

add infallible conversions between different bit sizes#23
jhpratt merged 5 commits intojhpratt:mainfrom
mcroomp:fromranged

Conversation

@mcroomp
Copy link
Contributor

@mcroomp mcroomp commented Jul 6, 2025

This allows you to convert, for example, a RangedI8<-100, 100> to a RangedI32<-100, 100> without having to cast the value manually and avoiding unnecessary range checks.

The macro checks that the source ranged type's range fits within the destination ranged type's range, and it uses the larger of the two types for the comparison to ensure that the conversion is valid. It also asserts that the source and destination ranges are valid at compile time.

Updated MSRV to 1.79 (june 2024) to use const blocks for asserts that are much more readable instead of creating new assert trait.

This change doesn't try to convert between signed and unsigned types.

    // succeeds because range is the same, even if normally
    // this wouldn't be infallible because of the bitness
    let foo = RangedI16::<-5, 5>::new_static::<3>();
    let bar : RangedI8<-5, 5> = foo.into();

    // succeeds because range is larger
    let foo = RangedI16::<-5, 5>::new_static::<3>();
    let bar : RangedI8<-10, 10> = foo.into();

    // fails to compile because range is smaller
    let foo = RangedI16::<-5, 5>::new_static::<3>();
    let bar : RangedI8<-4, 4> = foo.into();

@jhpratt jhpratt self-requested a review July 22, 2025 08:54
@jhpratt
Copy link
Owner

jhpratt commented Aug 18, 2025

I'll certainly have some follow-up work, but in general this looks great. Ordinarily I would request that you not bump the MSRV, but I intended to do that soon anyways given that I have also bumped it for time.

While not technically a major change, I'll likely release this in part of 0.5 soon; I want to wrap up some other work before a release.

@jhpratt jhpratt merged commit d6910e1 into jhpratt:main Aug 18, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants