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

Return an error if a decoded slice length doesn't fit into usize #491

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/de/impls.rs
Expand Up @@ -172,10 +172,15 @@ impl Decode for usize {
IntEncoding::Fixed => {
let mut bytes = [0u8; 8];
decoder.reader().read(&mut bytes)?;
Ok(match D::C::ENDIAN {

let value = match D::C::ENDIAN {
Endian::Little => u64::from_le_bytes(bytes),
Endian::Big => u64::from_be_bytes(bytes),
} as usize)
};

value
.try_into()
.map_err(|_| DecodeError::OutsideUsizeRange(value))
}
}
}
Expand Down
7 changes: 5 additions & 2 deletions src/de/mod.rs
Expand Up @@ -149,7 +149,8 @@ pub trait Decoder: Sealed {
/// # }
/// impl<T: Decode> Decode for Container<T> {
/// fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, DecodeError> {
/// let len = u64::decode(decoder)? as usize;
/// let len = u64::decode(decoder)?;
/// let len: usize = len.try_into().map_err(|_| DecodeError::OutsideUsizeRange(len))?;
/// // Make sure we don't allocate too much memory
/// decoder.claim_bytes_read(len * core::mem::size_of::<T>());
///
Expand Down Expand Up @@ -236,5 +237,7 @@ pub(crate) fn decode_option_variant<D: Decoder>(
/// Decodes the length of any slice, container, etc from the decoder
#[inline]
pub(crate) fn decode_slice_len<D: Decoder>(decoder: &mut D) -> Result<usize, DecodeError> {
u64::decode(decoder).map(|v| v as usize)
let v = u64::decode(decoder)?;

v.try_into().map_err(|_| DecodeError::OutsideUsizeRange(v))
}
8 changes: 8 additions & 0 deletions src/error.rs
Expand Up @@ -116,6 +116,14 @@ pub enum DecodeError {
found: usize,
},

/// The encoded value is outside of the range of the target usize type.
///
/// This can happen if an usize was encoded on an architecture with a larger
/// usize type and then decoded on an architecture with a smaller one. For
/// example going from a 64 bit architecture to a 32 or 16 bit one may
/// cause this error.
OutsideUsizeRange(u64),

/// Tried to decode an enum with no variants
EmptyEnum {
/// The type that was being decoded
Expand Down