Skip to content

Suggest adding a BoundedInteger trait #27

@chrisbouchard

Description

@chrisbouchard

TL;DR: It would be nice if the types created by bounded_integer! implemented a BoundedInteger trait to allow some generic reflection on the bounds.


Hi there! Some background: I'm working on a crate for serializing and deserializing values as sequential integers. The idea is to serialize by recursively serializing the value's fields and then doing some math to combine them into a unique index. (And similarly by reversed for deserialization.)

This of course requires providing some core supported types. I've already handled integers and NonZero, and I figured I should add bounded integers as well. I started writing my own, but then I found this project which looks much nicer than anything I was going to throw together! 😄

My crate has a trait called Indexed that does most of the work. I could provide implementations for BoundedU8 and friends, but unfortunately as it stands today, I don't think my crate could implement Indexed for bounded_integer! types. They're independent newtypes, and I would need to know the min and max repr values for my math.

I was thinking that some sort of BoundedInteger trait would let my crate provide blanket implementations for supported reprs. Maybe something like:

pub unsafe trait BoundedInteger: Into<Self::Repr> + TryFrom<Self::Repr> {
    type Repr;

    const MIN_VALUE: Repr;
    const MAX_VALUE: Repr;
}

That should be sufficient for my crate's needs. (Though of course you might add other bits of the bounded_integer! interface as well.) I marked the trait as unsafe because the const values would need to be trustworthy to safely call, e.g., new_unchecked.

I did see that the num-traits02 feature implements num::Bounded, but unfortunately that wouldn't work for me. My crate would need to use the bounds in const contexts, and that trait only provides runtime methods. (And anyway, I'd rather not require downstream crates to pull in num for one trait!)

Thanks for reading all this. I hope it makes sense, and I hope it's agreeable. I'd be happy to help with the implementation! (I couldn't guarantee a timeline—my project is already a side project—but since I'm the one asking for the feature maybe that's ok. 😄)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions