Skip to main content

libdqg/
util.rs

1use std::path::{Path, PathBuf};
2
3/// Resolves a resource path for the running binary.
4///
5/// Absolute paths are returned untouched. A relative path is first looked for next to
6/// the executable — where [`crate::copy_res_to_output_dir`] puts `res/` at build time —
7/// so a binary finds its assets no matter what the working directory is. If nothing is
8/// there, the path is returned unchanged and stays relative to the working directory,
9/// which is what `cargo run` from a package root relies on.
10pub fn resolve_resource_path(path: impl AsRef<Path>) -> PathBuf {
11    let path = path.as_ref();
12    if path.is_absolute() {
13        return path.to_path_buf();
14    }
15
16    if let Ok(exe) = std::env::current_exe()
17        && let Some(exe_dir) = exe.parent()
18    {
19        let candidate = exe_dir.join(path);
20        if candidate.exists() {
21            return candidate;
22        }
23    }
24
25    path.to_path_buf()
26}
27
28pub fn slice_to_bytes<T>(slice: &[T]) -> &[u8] {
29    let size = std::mem::size_of::<T>();
30    let len = slice.len() * size;
31    let ptr = slice.as_ptr() as *const u8;
32    unsafe { std::slice::from_raw_parts(ptr, len) }
33}