Skip to content

Add const generic support #52

@v1gnesh

Description

@v1gnesh

Hello @Licenser!

Thank you for sharing your excellent work.
I'm delighted to see that this crate shaves off about half the run time when parsing a huge binary file into structs, then into JSON.

As a novice programmer in general, I'm quite stuck by the below error.

When you have time, could you please help?

Code to reproduce:

use std::io::Cursor;
use binrw::BinRead;
use simd_json_derive::Serialize;

pub fn funk(bytes: &[u8]) -> String {
    String::from_utf8(Vec::from(bytes)).unwrap()
}

#[derive(Debug, PartialEq, BinRead, Serialize)]
pub struct EString<const N: usize>(
    #[br(map = |bytes: [u8; N]| funk(&bytes))]
    String
);

#[derive(Debug, PartialEq, BinRead, Serialize)]
#[br(big)]
pub struct Header {
    len: u16,
    _field: [u8; 12],
    // want: EString<4>,
    want: u32,
}

fn main() {

    let rec = vec![0x01, 0xB0, 0x00, 0x00, 0x1e, 0x0e, 0x00, 0x37, 0x93, 0xfa, 0x01, 0x21,
                   0x23, 0x0f, 0xe2, 0xf0, 0xe6, 0xf1];

    let value = Header::read(&mut Cursor::new(rec)).unwrap();
    // value.json_string().unwrap()
    println!("\n{}", value.json_string().unwrap());
}

Happy output:
When the EString struct is commented out, and when Header.want of u32 is used instead of EString<4>.

{"len":432,"_field":[0,0,30,14,0,55,147,250,1,33,35,15],"want":3807438577}

Sad output:

error: unexpected `const` parameter declaration
  --> src/main.rs:10:20
   |
10 | pub struct EString<const N: usize>(
   |                    ^^^^^^^^^^^^^^ expected a `const` expression, not a parameter declaration

error: proc-macro derive produced unparsable tokens
 --> src/main.rs:9:37
  |
9 | #[derive(Debug, PartialEq, BinRead, Serialize)]
  |                                     ^^^^^^^^^

error[E0207]: the const parameter `N` is not constrained by the impl trait, self type, or predicates
  --> src/main.rs:10:20
   |
10 | pub struct EString<const N: usize>(
   |                    ^^^^^^^^^^^^^^ unconstrained const parameter
   |
   = note: expressions using a const parameter must map each value to a distinct output value
   = note: proving the result of expressions other than the parameter are unique is not supported

error: aborting due to 3 previous errors

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions