Skip to content

Commit

Permalink
use start_position to handle little/big endians
Browse files Browse the repository at this point in the history
Signed-off-by: onur-ozkan <work@onurozkan.dev>
  • Loading branch information
onur-ozkan committed Mar 19, 2024
1 parent d5b98ff commit 539b009
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
5 changes: 3 additions & 2 deletions compiler/rustc_middle/src/mir/interpret/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -668,14 +668,15 @@ pub fn write_target_uint(
pub fn read_target_uint(endianness: Endian, mut source: &[u8]) -> Result<u128, io::Error> {
// This u128 holds an "any-size uint" (since smaller uints can fits in it)
let mut buf = [0u8; std::mem::size_of::<u128>()];
let start_position = 16 - source.len();
// So we do not read exactly 16 bytes into the u128, just the "payload".
let uint = match endianness {
Endian::Little => {
let _ = source.read(&mut buf)?;
source.read_exact(&mut buf[..start_position])?;
Ok(u128::from_le_bytes(buf))
}
Endian::Big => {
source.read_exact(&mut buf[16 - source.len()..])?;
source.read_exact(&mut buf[start_position..])?;
Ok(u128::from_be_bytes(buf))
}
};
Expand Down
10 changes: 6 additions & 4 deletions compiler/stable_mir/src/mir/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,14 @@ impl IndexedVal for AllocId {
/// Utility function used to read an allocation data into a unassigned integer.
pub(crate) fn read_target_uint(mut bytes: &[u8]) -> Result<u128, Error> {
let mut buf = [0u8; std::mem::size_of::<u128>()];
let start_position = 16 - bytes.len();
match MachineInfo::target_endianess() {
Endian::Little => {
let _ = bytes.read(&mut buf)?;
bytes.read_exact(&mut buf[..start_position])?;
Ok(u128::from_le_bytes(buf))
}
Endian::Big => {
bytes.read_exact(&mut buf[16 - bytes.len()..])?;
bytes.read_exact(&mut buf[start_position..])?;
Ok(u128::from_be_bytes(buf))
}
}
Expand All @@ -70,13 +71,14 @@ pub(crate) fn read_target_uint(mut bytes: &[u8]) -> Result<u128, Error> {
/// Utility function used to read an allocation data into an assigned integer.
pub(crate) fn read_target_int(mut bytes: &[u8]) -> Result<i128, Error> {
let mut buf = [0u8; std::mem::size_of::<i128>()];
let start_position = 16 - bytes.len();
match MachineInfo::target_endianess() {
Endian::Little => {
let _ = bytes.read(&mut buf)?;
bytes.read_exact(&mut buf[..start_position])?;
Ok(i128::from_le_bytes(buf))
}
Endian::Big => {
bytes.read_exact(&mut buf[16 - bytes.len()..])?;
bytes.read_exact(&mut buf[start_position..])?;
Ok(i128::from_be_bytes(buf))
}
}
Expand Down

0 comments on commit 539b009

Please sign in to comment.