Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply sign extension when decoding int #732

Merged
merged 2 commits into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/buf/buf_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand Down
13 changes: 13 additions & 0 deletions tests/test_buf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,19 @@ fn test_get_u16() {
assert_eq!(0x5421, buf.get_u16_le());
}

#[test]
fn test_get_int() {
paolobarbolini marked this conversation as resolved.
Show resolved Hide resolved
let mut buf = &b"\xd6zomg"[..];
assert_eq!(-42, buf.get_int(1));
let mut buf = &b"\xd6zomg"[..];
assert_eq!(-42, buf.get_int_le(1));

let mut buf = &b"\xfe\x1d\xc0zomg"[..];
assert_eq!(0xffffffffffc01dfeu64 as i64, buf.get_int_le(3));
let mut buf = &b"\xfe\x1d\xc0zomg"[..];
assert_eq!(0xfffffffffffe1dc0u64 as i64, buf.get_int(3));
}

#[test]
#[should_panic]
fn test_get_u16_buffer_underflow() {
Expand Down