Am I getting the target pointer width correctly? I'm not familiar with using raw pointer types and not sure if *const ()
is correct here.
/// The target pointer width in bits.
pub const POINTER_WIDTH: usize = std::mem::size_of::<*const ()>() * 8;
fn main() {
// This outputs 64 on my machine, which looks correct to me,
// but I can't be sure.
println!("{POINTER_WIDTH}");
}
By the way, the reason I want to do this is because I want to compare u64
and usize
as follows, is there an easier way to compare them in the standard library?
use std::{io, path::Path};
/// My data files must start with this byte sequence.
pub const HEADER: &[u8] = b"HEADER_OF_MY_FILE_FORMAT";
pub fn validate(path: &Path) -> io::Result<()> {
let meta: std::fs::Metadata =
todo!("Check if path is a regular file, then get its metadata.");
// HERE: meta.len() returns u64, and HEADER.len() returns usize.
// Since u64 and usize cannot be directly compared,
// the smaller type must be converted to the bigger.
// In addition to that, I want to see unnecessary code removed by the compiler.
// This is why I want the POINTER_WIDTH constant.
let too_small = if POINTER_WIDTH >= 64 {
(meta.len() as usize) < HEADER.len()
} else {
meta.len() < (HEADER.len() as u64)
};
if too_small {
return Err(io::Error::new(io::ErrorKind::InvalidData, "missing header"));
}
todo!("do other validation");
}