TryFrom for Range<U> to Range<V>?

Hi,

I have some functions which make more sense to return Range<u64> over Range<usize>, mostly because I'm parsing data which I know is going to be the u64 type, and returning usize means that 32-bit software can't parse 64-bit values correctly, which is... wrong, especially since u64 works on 32-bit platforms.

Currently, I'm using a function similar to:

pub fn as_range_usize<T: TryInto<usize>>(range: Range<T>) -> Result<Range<usize>, T::Error> {
    Ok(Range {
        start: range.start.try_into()?,
        end: range.end.try_into()?,
    })
}

However, it would be nice to be able to just do let range: Range<usize> = a_u64_range.try_into()?. Unfortunately, this isn't possible, due to orphan rules (I think).

I could implement a newtype wrapper of Range, but this is just annoying. Is there:
a) Something I'm missing to do this in a good way, or,
b) Any reason why the traits

impl<T> TryFrom<Range<T>> for Range<usize> where usize: TryFrom<T> { /* impl */ }
// or even the more general
impl<U, V> TryFrom<Range<U>> for Range<V> where V: TryFrom<U> { /* impl */ }

are not implemented on Range?

Overlapping implementations.

  1. There's a blanket T: From<T>
  2. That results in a T: Into<T> for any T
  3. That results in T: TryFrom<T> for any T
    a. (That results in T: TryInto<T> for any T)

Your suggested implementation in combination with 3 (with T = usize) means that you're trying to implement TryFrom<Range<usize>> for Range<usize> which conflicts with 3 (with T = Range<usize>).

The implementations could exist in std,[1] but they'd be on a laundry-list of specific types, like they are for NonZero<T>.

You could use a custom trait (or traits) instead, so you can use method call syntax.


  1. core technically ↩︎

Thanks, that's helpful. Defining a trait would probably be the way to go.

Ok. Slightly rephrasing my question, is there any reason why this wouldn't be the case? I looked at open issues and couldn't find anything about such a thing.

Not that I'm aware of. You could seek library team feedback via IRLO or ACP or Zulip.

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.