Skip to content

Commit

Permalink
impl: remove unsafe code from read_uint and read_uint128 methods
Browse files Browse the repository at this point in the history
Rewrite read_uint and read_uint128 methods such that they no longer
use unsafe code.  Rather than casting pointers and doing unsafe
copies, declare output byte buffer for the read number and use
from_xx_bytes method to convert those read bytes to a number.

Closes #192
  • Loading branch information
mina86 authored and BurntSushi committed Oct 6, 2023
1 parent 1e2d8b0 commit c0b6678
Showing 1 changed file with 18 additions and 36 deletions.
54 changes: 18 additions & 36 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1955,32 +1955,20 @@ impl ByteOrder for BigEndian {

#[inline]
fn read_uint(buf: &[u8], nbytes: usize) -> u64 {
assert!(1 <= nbytes && nbytes <= 8 && nbytes <= buf.len());
let mut out = 0u64;
let ptr_out = &mut out as *mut u64 as *mut u8;
unsafe {
copy_nonoverlapping(
buf.as_ptr(),
ptr_out.offset((8 - nbytes) as isize),
nbytes,
);
}
out.to_be()
let mut out = [0; 8];
assert!(1 <= nbytes && nbytes <= out.len() && nbytes <= buf.len());
let start = out.len() - nbytes;
out[start..].copy_from_slice(&buf[..nbytes]);
u64::from_be_bytes(out)
}

#[inline]
fn read_uint128(buf: &[u8], nbytes: usize) -> u128 {
assert!(1 <= nbytes && nbytes <= 16 && nbytes <= buf.len());
let mut out: u128 = 0;
let ptr_out = &mut out as *mut u128 as *mut u8;
unsafe {
copy_nonoverlapping(
buf.as_ptr(),
ptr_out.offset((16 - nbytes) as isize),
nbytes,
);
}
out.to_be()
let mut out = [0; 16];
assert!(1 <= nbytes && nbytes <= out.len() && nbytes <= buf.len());
let start = out.len() - nbytes;
out[start..].copy_from_slice(&buf[..nbytes]);
u128::from_be_bytes(out)
}

#[inline]
Expand Down Expand Up @@ -2155,24 +2143,18 @@ impl ByteOrder for LittleEndian {

#[inline]
fn read_uint(buf: &[u8], nbytes: usize) -> u64 {
assert!(1 <= nbytes && nbytes <= 8 && nbytes <= buf.len());
let mut out = 0u64;
let ptr_out = &mut out as *mut u64 as *mut u8;
unsafe {
copy_nonoverlapping(buf.as_ptr(), ptr_out, nbytes);
}
out.to_le()
let mut out = [0; 8];
assert!(1 <= nbytes && nbytes <= out.len() && nbytes <= buf.len());
out[..nbytes].copy_from_slice(&buf[..nbytes]);
u64::from_le_bytes(out)
}

#[inline]
fn read_uint128(buf: &[u8], nbytes: usize) -> u128 {
assert!(1 <= nbytes && nbytes <= 16 && nbytes <= buf.len());
let mut out: u128 = 0;
let ptr_out = &mut out as *mut u128 as *mut u8;
unsafe {
copy_nonoverlapping(buf.as_ptr(), ptr_out, nbytes);
}
out.to_le()
let mut out = [0; 16];
assert!(1 <= nbytes && nbytes <= out.len() && nbytes <= buf.len());
out[..nbytes].copy_from_slice(&buf[..nbytes]);
u128::from_le_bytes(out)
}

#[inline]
Expand Down

0 comments on commit c0b6678

Please sign in to comment.