ConstInit
Utilities to help you do constant initializations or build-time initializations of your custom types from a JSON configuration file. When compiled in release mode, usage of the instances that were constant initialized will be optimized. Especially branches where condition can be resolved at build time.
Kind of pattern we want to optimize:
let config = init_at_runtime;
if config.title == "foo" && config.syntax
Result:
const config: Config = const_init;
if config.title == "foo" && config.syntax
Use cases
This is meant for projects with a lot of configuration. Where code complexity increases a lot due to having a lot of potential settings.
I had this idea while working on Zed codebase which contains so many conditional branches depending on your settings. Ideally when I finish tweaking my settings I'd be able to compile my custom version of Zed that will be optimized. I'd also like to apply this to Tauri applications which are also highly configurable.
Features
const_init_buildcrate helps you generate a Rust file inbuild.rs. This Rust file contains constants variables obtained from a JSON configuration file.const_init_macrosprovides macros to do constant initializations with your custom struct.
Workflow
Cargo.toml:
[]
= "0.1"
[]
= "0.1"
settings.json:
build.rs:
generated rust file generated::settings.rs:
pub const FOO: bool = true;
pub const BAR: isize = 1;
usage in your code:
use *;
use ConstInit;
// Macro adds `const_init`, constant function for initialization
Limitations
File format
Currently only JSON is supported but there are no difficulties to support other formats such as TOML.
Json to Rust
Certain JSON types do not translate perfectly into Rust types.
- JSON
integersare all turned into Rustisize - JSON
arrayscontaining different types are not handled - JSON
nullis unsupported - JSON
Nanis unsupported
License
This project is licensed under the MIT License.