RON: Are there crates to serialize Rust types as correctly formated Rust code?

Are there any creates that help serialize Rust types as correctly formatted Rust code? It'd help enormously when defining tables used in cryptography or other arithmetic computations.

It should produce const/static declarations of course, so it'd require a translation from non-'static types to 'static types, and should fail when this fails.

As a type level example, if T could be converted to 'static then Cow<'a,T> should be replaced by Cow<'static,T>. At the value level, both Cow::Owned(Box<[T]>) and Cow::Borrowed(&'a [T]) should be replaced by Cow::Borrowed(&'static [T]).

There exist more complex forms in which you translate names so that Vec<T> and Box<[T]> simple become &static [T] directly, but this plays less well than Cow with the same code being used both at runtime and at pre-compile time.

In principle, you could serialize types containing allocations like Box<T> into code that first creates the Box<T>, but doing so appears largely useless since other serializations operate more efficiently once you require decoding anyways.

uneval is a serde serializer that outputs Rust expressions, which can be include!ed where you need. Its output isn’t well formatted, but you can run rustfmt on it to fix that, I’m sure. I’ve had small successes with it in a build.rs experiment I did on generating prepared HTML from data at build time.

5 Likes

I've a stupid question: Could one make uneval or even serde handle Cows or any Deref type explicitly?

It appears serde fully dereferences types before serializing them or something, meaning Cow breaks uneval.

I suspect one needs some new RustConst formatter trait, similar to Debug and Display, maybe post-processing the output of uneval turns out easier, but doing so makes serde a dependency and not actually that trivial.

I don't think so. Serde serializers can't distinguish between owned and borrowed strings; Serializer::serialize_str() always takes a borrowed &str and there's no counterpart to this method.

1 Like