Some of the internal state is cached in local variables at the start of
the function, and is updated only at the end of the function. But the
contents of the packet buffer is never cached. As a result, the two can
go out of sync when an error occurs and the function returns early.
Trying to restore the original state is pointless if the corresponding
data in the packet buffer is no longer available.
Fixed by removing the local variables and always updating the internal
state in-place to reflect the current state.
The ringbuffer boundary addresses (begin/end) should be ordered
correctly, and the packet size should be smaller than the ringbuffer
size, otherwise the code won't work as expected.
Reading a ringbuffer backwards in order to process the most recent data
first, is a very common operation. Nearly every dive computer backend
has its own implementation. Thus with a common implementation, the
amount of code duplication and complexity in the dive computer backends
can be greatly reduced.
The common algorithm is implemented as a simple ringbuffer stream, which
takes care of all the technical details like the ringbuffer boundaries,
alignment to the page size, using the optimal packet size and caching
the remaining data.