I am working on some code where a buffer is backed by a statically sized array. Since Rust and the build tools provided by it offer the possibilities to compile conditionally, I can do something like this:
struct Buffer {
// default case, if none is set
#[cfg(not(buffersize))]
buffer: [f32; 16],
#[cfg(buffersize = "32")]
buffer: [f32; 32],
#[cfg(buffersize = "64")]
buffer: [f32; 64],
}
impl Buffer {
fn new() -> Buffer {
Buffer {
#[cfg(not(buffersize))]
buffer: [0.0; 16],
#[cfg(buffersize = "32")]
buffer: [0.0; 32],
#[cfg(buffersize = "64")]
buffer: [0.0; 64],
}
}
}
There is another question that uses features to compile the code conditionally. Using features alone, I would have to combine buffersize
and the actual value e.g. buffersize16
. Is it possible to provide the cfg
flags to Cargo, or would I need to provide them directly to rustc
?
Buffer
is just a wrapper for a statically sized array. I could have used a type alias eg.type Buffer = [f32; 256]
and implement the necessary methods on it. TheBuffer
will eventually be used in some concurrent context / will be processed in multiple threads. Working with correct lifetimes seems to be more cumbersome here, but I get your point, that the provided example is not very elegant. – Sartorial