Parchive / par2cmdline

Official repo for par2cmdline and libpar2
http://parchive.sourceforge.net
GNU General Public License v2.0
723 stars 75 forks source link

Avoid copying back memory in FileChecksummer when data is valid #179

Closed animetosho closed 1 year ago

animetosho commented 1 year ago

The current FileChecksummer almost always performs a memory copy once a read has occurred. This is because it fills the entire buffer, and every Jump call can, at most, consume half that buffer, leading to keep being greater than 0 in all cases except reaching the end-of-file.

This seemingly unnecessary copying around of memory seems rather wasteful.
A solution may be to turn the buffer into some sort of circular buffer, however implementing such is rather complex/fiddly.

With the goal of simplicity, I've implemented a much easier approach that yields most of the benefit - instead of filling the buffer completely, only fill it half way, most of the time. Since the buffer can only be consumed til the half-way point, this is safe.
Assuming all data is valid, this makes keep == 0 stay true throughout the process, avoiding the memory copy.

This leaves cases where data isn't valid, causing Step or Jump (with smaller distances) to be called. In such cases, it just reverts to existing behavior of filling the buffer completely, and moving the data to the beginning of the buffer (in Jumps case). If the data becomes valid again, it'll revert to filling the buffer halfway.

The assumption is that most data will be valid in typical usage scenarios, leading to a speedup most of the time.

Also the memmove in Step can be replaced with memcpy as the regions are guaranteed to be non-overlapping.