What's the best way to convert from RangeBounds to Range?

My goal is to store a list of ranges... the ranges represent indexes in some list. I guess I want to store this list of ranges as Vec<Range<usize>>.

I want the a public API that appends values to this list to be flexible... so I think that means it should accept appending RangeBounds<usize>. I think this means I need a way to convert from RangeBounds<usize> to Range<usize>... and I don't see this implemented in Rust?

Assuming it's not already implemented then can I do it any easier then this:

fn range_from_range_bounds<T: RangeBounds<usize>>(range: T, min: usize, max: usize) -> Range<usize> {
    let start = match range.start_bound() {
        Bound::Included(start) => *start,
        Bound::Excluded(start) => *start + 1,
        Bound::Unbounded => min,
    };
    let end = match range.end_bound() {
        Bound::Included(end) => *end + 1,
        Bound::Excluded(end) => *end,
        Bound::Unbounded => max,
    };
    start..end
}

Thanks!

It would be more flexible to store Vec<(Bound<usize>, Bound<usize>)>, so all semantics are preserved.

Ok thanks for the hint... I was only thinking of Range or Box<dyn RangeBounds> and I knew I didn't want to box. Thanks your solution works well.

Jesse

Still getting into long looking enums for what feels like simple stuff...is there better way to get from Bound<&usize> to Bound then:

let owned_start_bound: Bound<usize> = match range.start_bound() {
    Bound::Excluded(i) => Bound::Excluded(*i),
    Bound::Included(i) => Bound::Included(*i),
    Bound::Unbounded => Bound::Unbounded,
};

I see that in nightly I can use bound.cloned() to do this, but right now the above is needed?

Yeah, that annoyance is why cloned() has been added.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.