fix: apply sign extension when decoding int (#732)

Closes #730
This commit is contained in:
Paolo Barbolini
2024-08-30 08:20:29 -04:00
committed by GitHub
parent 291df5acc9
commit 79fb85323c
2 changed files with 21 additions and 2 deletions
+8 -2
View File
@@ -66,6 +66,12 @@ macro_rules! buf_get_impl {
}};
}
// https://en.wikipedia.org/wiki/Sign_extension
fn sign_extend(val: u64, nbytes: usize) -> i64 {
let shift = (8 - nbytes) * 8;
(val << shift) as i64 >> shift
}
/// Read bytes from a buffer.
///
/// A buffer stores bytes in memory such that read operations are infallible.
@@ -923,7 +929,7 @@ pub trait Buf {
/// This function panics if there is not enough remaining data in `self`, or
/// if `nbytes` is greater than 8.
fn get_int(&mut self, nbytes: usize) -> i64 {
buf_get_impl!(be => self, i64, nbytes);
sign_extend(self.get_uint(nbytes), nbytes)
}
/// Gets a signed n-byte integer from `self` in little-endian byte order.
@@ -944,7 +950,7 @@ pub trait Buf {
/// This function panics if there is not enough remaining data in `self`, or
/// if `nbytes` is greater than 8.
fn get_int_le(&mut self, nbytes: usize) -> i64 {
buf_get_impl!(le => self, i64, nbytes);
sign_extend(self.get_uint_le(nbytes), nbytes)
}
/// Gets a signed n-byte integer from `self` in native-endian byte order.