near / borsh-rs

Rust implementation of Binary Object Representation Serializer for Hashing
https://borsh.io/
Apache License 2.0
299 stars 65 forks source link

feat!: add `DiscriminantValue` to `Definition::Enum::variants` tuples #232

Closed dj8yfo closed 11 months ago

dj8yfo commented 11 months ago

resolves #230

dj8yfo commented 11 months ago

this commit was added to restrict possible values of discriminants to u8 range for BorshSchema to be congruent with what BorshSerialize, BorshDeserialize derives do.


with it:

    #[derive(BorshSchema)]
    #[borsh(use_discriminant = true)]
    enum XYa {
        A,
        B = discrim(),
        C,
        D,
        E = -100,
        F,
    }

    const fn discrim() -> isize {
        0x14
    }
//     |
// 277 |     #[derive(BorshSchema)]
//     |              ----------- expected due to this
// ...
// 281 |         B = discrim(),
//     |             ^^^^^^^^^ expected `u8`, found `isize`
//     |
// help: you can convert an `isize` to a `u8` and panic if the converted value doesn't fit
// 4  error[E0277]: the trait bound `u8: Neg` is not satisfied
//    --> borsh/tests/test_enum_discriminants.rs:284:13
//     |
// 284 |         E = -100,
//     |             ^^^^ the trait `Neg` is not implemented for `u8`
//     |
//     = help: the following other types implement trait `Neg`:

Without it:

    #[derive(BorshSchema)]
    #[borsh(use_discriminant = true)]
    enum XYa {
        A,
        B = discrim(),
        C,
        D,
        E = -100,
        F,
    }

    const fn discrim() -> isize {
        0x14
    }
//  1  error[E0308]: mismatched types
//     --> borsh/tests/test_enum_discriminants.rs:281:13
//      |
//  281 |         B = discrim(),
//      |             ^^^^^^^^^ expected `i64`, found `isize`
//      |
//  help: you can convert an `isize` to an `i64` and panic if the converted value doesn't fit

but

    #[derive(BorshSchema)]
    #[borsh(use_discriminant = true)]
    #[repr(i64)]
    enum XYa {
        A,
        B = discrim(),
        C,
        D,
        E = -100,
        F,
    }

    const fn discrim() -> i64 {
        0x14
    }
// OK