noritada / grib-rs

GRIB format parser for Rust
Apache License 2.0
57 stars 9 forks source link

Subtract with Overflow Error in FixedValueIterator #75

Closed shastro closed 5 months ago

shastro commented 5 months ago

Simple Description on the Bug

If the length is zero inside the next() method in FixedValueIterator we get a subtract with overflow.

Steps to Reproduce

This happened to me when processing grib data from the GFS

Expected Behavior

Not crashing on valid grib data.

Actual Behavior

Crashing on valid grib data.

Additional Context

The bug can be fixed by changing the next method in decoder/stream.rs to not subtract the length unless there is some value.

Going from this:

impl<T> Iterator for FixedValueIterator<T>
where
    T: Copy,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        let val = if self.length > 0 { 
            Some(self.val)
        } else {
            None
        };
        self.length -= 1; // <--- Crash here
        val
    }

    // -- snip -- //
}

To this:

impl<T> Iterator for FixedValueIterator<T>
where
    T: Copy,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        let val = if self.length > 0 {
            self.length -= 1;
            Some(self.val)
        } else {
            None
        };
        val
    }

    // -- snip -- //
}

I'll be sending in a PR for this shortly.