const-gen
This is a crate for generating compile-time constants in your build.rs
file. This crate supports converting types that are typically heap-allocated into fixed-size constants. It includes support for primitives, strings, vectors, maps, sets, and comes with a derive macro to allow implementation with structs and enums.
See this example:
// build.rs
use *;
use ;
// First, let's dummy up some structs. Enabling the "derive"
// feature allows us to do this simply, but implementing the
// CompileConst trait by hand is straightforward.
;
Now, in our main.rs
file we can do something like this:
// Include our constants
include!;
// And that's it, we can access all of the const values below.
// It plays quite well with rust-analyzer, etc
The actual generated output looks like (an unformatted version of) this:
;
const TEST_U8: u8 = 27u8;
const TEST_F32: f32 = 33.5f32;
const TEST_VEC: &'static =
&;
const TEST_STRING: &'static str = "I'm a string!";
const TEST_COW: &'static str = "Cow!";
const TEST_STRUCT: TestStruct = TestStruct
;
const TEST_TUP_STRUCT: TestTup = TestTup;
const TEST_ENUM: TestEnum = Variant1;
const TEST_ENUM_TUP: TestEnum = Variant2;
const TEST_ENUM_STRUCTLIKE: TestEnum = Variant3
;
Out-of-the-box Implementations
The following table shows what types have implementations of the CompileConst trait already defined
Type | Const Representation |
---|---|
<all numeric primitives> | no conversion |
String, &str, str | &'static str |
Vec<T>, &[T] | &'static [T] |
Box<T>, Cow<T>, Rc<T>, Arc<T> | T's CompileConst representation |
HashMap<K,V> | phf::Map<K, V>, with K and V's CompileConst representation |
HashSet<E> | phf::Set<E>, with E's CompileConst representation |
() | no conversion |
<tuples with 2-16 variants> | A tuple with the CompileConst representation of each variant |
Limitations
This crate will use the endianness, pointer widths, etc of the host machine rather than the target, unlike normal consts. It's still unclear if this caveat could be resolved with a reasonable amount of effort.
Features
At the current time, all features are default.
phf
The phf
feature implements the CompileConst trait for HashMaps and HashSets. It will generate a phf::Map
for HashMap types and a phf::Set
for HashSet types. Note that phf
does NOT need to be included in your build dependencies, but it ought to be included in your runtime dependencies in order to use the constants.
derive
The derive
feature adds #[derive(CompileConst)]
for structs and enums. The requirement is that all members implement CompileConst
as well.