Convi - convenient (but safe) conversion (From-like) traits for Rust

https://crates.io/crates/convi

I'm tired of so many usize::try_from(x).expect("I know it will not fail"); in my code, so I wrote this little crate as my solution.

First - if a code can't possibly work with smaller than X bit architectures, it will enable infalliable usize::cast_from and isize::cast_from conversions (among all existing from versions).

Second - when the code is relying on knowledge that certain value will fit certain conversion, it enables u32::checked_from(x); that will just panic on failure, to avoid both the .expect, and problems with using as.

And that's kind of it. Fairly small and unspectacular. If I missed a crate that does this already, please let me know. Any feedback welcome (especially naming).

1 Like

My feedback on naming is that having checked_... panic is surprising given that the standard library uses that prefix for functions that specifically avoid panicking.

4 Likes

Oh dear. That's true. What else then?

assert_from? asserted_from? ensure_from? expect_from?

BTW. I was wondering if cast_from shouldn't just be from, given that it's a super-set of From. This way one could just use convi::From and use usize::from(...) etc. . The shadowing can be a bit confusing sometimes, but a lot crates use Result and Error and it people learned to live with it.

I think I personally like this best, because that's kind of what it is. from + expect.

1 Like

Every (Sized) type implements From, so that will always be ambiguous and you'd have to spell it <usize as CastFrom<_>>::from(i) (or <usize as convi::From<_>>::from or whatever).

1 Like

Well, one thing less to wonder about. :slight_smile:

I agree with liking expect_from.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.