bounded-integer icon indicating copy to clipboard operation
bounded-integer copied to clipboard

Support custom reprs, and constants in range bounds

Open Stargateur opened this issue 4 years ago • 3 comments

My use case of this crate is as follow:

bounded_integer! {
    #[repr(libc::c_int)]
    pub struct TimeOut { -1..=libc::c_int::MAX }
}

bounded_integer! {
    #[repr(usize)]
    pub struct MaxEvents{ 1..=libc::c_int::MAX as usize }
}

Unfortunately, this can't be parsed by the macro.

For the first one we could have an alternate:

bounded_integer! {
    #[repr(libc::c_int)]
    pub struct TimeOut { -1.. }
}

This one is possible, I guess.

And the second one I could do:

const TMP : usize = libc::c_int::MAX as usize;

bounded_integer! {
    #[repr(usize)]
    pub struct MaxEvents{ 1..=TMP }
}

But I guess it will be hard.

There is also that #[repr(libc::c_int)] is not possible but #[repr(transparent)] should allow that without problem not need to use #[repr(libc::c_int)]directly for structure. I don't think it's possible for enum https://github.com/rust-lang/rust/pull/68122.

This is just a feedback of my personal use case, I totally agree with closing this.

Stargateur avatar Mar 20 '21 19:03 Stargateur

The trouble with allowing custom type reprs is that bounded-integer doesn't know their signedness and size. Signedness is used to determine whether abs, checked_abs, Neg and checked_neg should be generated, and size is used to generate the From<{bounded type}> for {larger types}.

I think the best option is to special-case c_* types for bounded integers, and support arbitrary const expressions inside bound ranges for structs instead of requiring a value evaluatable by the macro.

Kestrer avatar Mar 20 '21 19:03 Kestrer

I think the best option is to special-case c_* types for bounded integers

I don't think it's a good idea, do a specialization just for the libc add a lot of work for this crate.

I think this need a general solution or just don't do it. After all I don't think there will be ever a OS where c_int is not a i32 :p.

I'm fine with:

bounded_integer! {
    #[repr(i32)]
    pub struct TimeOut { -1..=i32::MAX }
}

static_assertions::assert_type_eq_all!(libc::c_int, i32);

Stargateur avatar Mar 20 '21 19:03 Stargateur

And I just encountered another problem - automatic repr detection does not work if the macro doesn't know the value of each range bound when it runs (this is the case if we allow constants in range bounds).

I will leave this issue open because someone might potentially come along with a better solution in the future, but for now I don't think I can solve this.

Kestrer avatar Mar 20 '21 19:03 Kestrer