Serialize to Rust?

I want initialise struct in const context without usage of lazy_static and similar stuff.
Just plain constant.
But current stable rustc can no evaluate code that I need in const context (the main problem are math functions, like sin, sqrt and so on).

So the part of calculation is simple, I use build script and calculate what I need.
But how I save result back to Rust?

Is any serde like crates, where I can do something like this:

#[derive(Serialize)]
struct Foo {
  a: f64,
  b: f64,
}

serde_rust::to_code(&Foo { .. })

where serde_rust::to_code generates Rust code as string?

Heya, you could:

  1. Generate code in build.rs like you mention, and
  2. Use the include! macro to include the generated code as part of the source code.

I've done something like that in this build.rs which writes to "${OUT_DIR}/fn_metadata_impl.rs", and included it in fn_metadata.rs.

peace :v:

I can calculate the resulting value of Foo.
The problem exactly in code generation.
I use Foo in build.rs as type. In other words,
I use module where Foo defined from my build.rs.

You could do something as simple as this.

#[derive(Default, Debug)]
struct Foo {
  a: f64,
  b: f64,
}

fn static_foo(name: &str, foo: &Foo) -> String {
    format!("static {name}: Foo = {foo:?};")
}

fn main() {
    // `Debug` format is not guaranteed
    // (Roll your own `Display` if preferred)
    assert_eq!(
        "static FOO: Foo = Foo { a: 0.0, b: 0.0 };",
        static_foo("FOO", &Foo::default())
    );
    
    // ... build.rs stuff ...
}
1 Like

Yeah, this is almost what I want. The problem is that default Debug implementation uses unknown precision of float points. But I suppose I can implement my own Debug implementation of Foo, that replace print of all float values with hex float.

I can't find a reference document to cite (best I could quickly find is things like this PR where it was done), but Rust's floating-point printing will not lose precision — it will print enough digits to reproduce the number, unless you ask for a specific number of digits.

4 Likes

There is databake - Rust. Check out also Rust Zürisee, Dec 2022: Supercharging Zero-Copy Deserialization - YouTube

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.