Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Static memory mapped file in Rust
pub fn file_bytes(filename: &std::path::PathBuf) -> &'static [u8] {
let mut filename = String::from(filename.as_path().to_str().expect("Unexpected file name"));
filename.push('\0');
let file = unsafe {
CreateFileA(
filename.as_bytes().as_ptr(),
FILE_GENERIC_READ,
FILE_SHARE_READ,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0,
)
};
if file == -1 {
panic!("Failed to open file `{}`", filename);
}
let mut size = 0;
unsafe { GetFileSizeEx(file, &mut size) };
if size == 0 {
return &[];
}
unsafe {
let mapping =
CreateFileMappingW(file, 0, PAGE_READONLY, 0, 0, 0);
let data = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0) as _;
std::slice::from_raw_parts_mut(data, size as usize)
}
}
#[link(name = "KERNEL32")]
extern "system" {
fn CreateFileA(
lpfilename: *const u8,
dwdesiredaccess: u32,
dwsharemode: u32,
lpsecurityattributes : isize,
dwcreationdisposition: u32,
dwflagsandattributes: u32,
htemplatefile: isize,
) -> isize;
fn CreateFileMappingW(
hfile: isize,
lpfilemappingattributes : isize,
flprotect: u32,
dwmaximumsizehigh: u32,
dwmaximumsizelow: u32,
lpname: isize,
) -> isize;
fn GetFileSizeEx(
hfile: isize,
lpfilesize: *mut i64,
) -> i32;
fn MapViewOfFile(
hfilemappingobject: isize,
dwdesiredaccess: u32,
dwfileoffsethigh: u32,
dwfileoffsetlow: u32,
dwnumberofbytestomap: usize,
) -> *mut ::std::ffi::c_void;
}
const FILE_ATTRIBUTE_NORMAL: u32 = 128u32;
const FILE_GENERIC_READ: u32 = 1179785u32;
const FILE_SHARE_READ: u32 = 1u32;
const FILE_MAP_READ: u32 = 4u32;
const PAGE_READONLY: u32 = 2u32;
const OPEN_EXISTING: u32 = 3u32;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment