BurntSushi / byteorder

Rust library for reading/writing numbers in big-endian and little-endian.
The Unlicense
984 stars 144 forks source link

Implement `read_usize` #185

Closed AsafFisher closed 2 years ago

AsafFisher commented 2 years ago

Iv'e notice there is no read_usize.... Wondered why...

let mut buf = [0; core::mem::size_of::<usize>()];
connection.read_exact(&mut buf).unwrap();
usize::from_ne_bytes(buf);

Iv'e got a project where a pointer changes its size from 64 to 32 bit... It will be useful when compiling for different target and not wanting to make an config conditions...

BurntSushi commented 2 years ago

There is no read_usize precisely because its size is platform dependent. There is a read_uint method that lets you specify the size precisely, and it seems like something you could use here. Since you didn't mention it, it's not clear why read_uint is insufficient for your use case.

AsafFisher commented 2 years ago

But I might want my code to read the platform specific size, say if I pass a pointer from one process to the other... I want my code to pass the pointer correctly on both x64 and x32 arch...

let ptr = unix_socket.read_usize() as * _;

without read_usize the code will look like this (psudo code):

if conf!(arch == "x64"){
unix_socket.read_u64() // or read_uint with size of 8
}else{
unix_socket.read_u32() // or read_uint with size of 4
}
BurntSushi commented 2 years ago

Why not just do unix_socked.read_uint(core::mem::size_of::<usize>())?

AsafFisher commented 2 years ago

Well why not just support all rusts type ahead of time? I dont think usize is going to be deprecated anytime soon... Its just seem to me like a fundamental type like u64 Like I get what you are saying, but with your logic I could just say "Hey lets get rid of read_u64 we can just do unix_socked.read_uint(core::mem::size_of::<u64>())"

BurntSushi commented 2 years ago

I already explained why. Because usize has a platform dependent size. u64 does not. It's a possible footgun to use it accidentally if you're not thinking about platform dependent size. The read_uint API makes it explicit.

I'm going to close this because I don't see this changing personally.