Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good way to include external resource data into Rust source code?

Tags:

resources

rust

Imagine the following example:

let SHADER: &'static str = "
#version 140

attribute vec2 v_coord;
uniform sampler2D fbo_texture;
varying vec2 f_texcoord;

void main(void) {
    gl_Position = vec4(v_coord, 0.0, 1.0);
    f_texcoord = (v_coord + 1.0) / 2.0;
}";

fn main() {
    // compile and use SHADER
}

Of course you can write the shader inline as shown above, but this gets really complicated when designing shaders using external software or when having multiple shaders. You can also load the data from external files, but sometimes you only want to provide a single small executable without the need to figure out where the resources are stored.

It would be great if the solution also works for binary files (e.g. icons, fonts).

I know that it is possible to write rustc plugins and as far as I understand it should be possible to provide such a feature, but writing my own plugin is rather complicated and I would like to know if there is already a good plugin/lib/standard way to include resource files. Another point is that it should work without exploiting the manual linker+pointer way.

like image 246
Marco Neumann Avatar asked Aug 26 '14 11:08

Marco Neumann


1 Answers

I believe you are looking for the include_str!() macro:

static SHADER: &'static str = include_str!("shader.glsl");

shader.glsl file should be located right beside the source file for this to work.

There's also include_bytes!() for non-UTF-8 data:

static SHADER: &'static [u8] = include_bytes!("main.rs");

Don't conflate these with include!, which imports a file as Rust code.

like image 180
Vladimir Matveev Avatar answered Oct 19 '22 14:10

Vladimir Matveev