Playing with file reads / writes, so this loop will read from an input file and write to an output file:
loop do
buf = Slice(UInt8).new(4096)
n = infile.read(buf)
break if n == 0
outfile.write(buf[0...n])
end
All is fine, the output file hashes correctly.
If I place a reverse! in there:
loop do
buf = Slice(UInt8).new(4096)
n = infile.read(buf)
break if n == 0
buf.reverse!
outfile.write(buf[0...n])
end
.. and run it twice, first on an input file, and then on the file that the first run produced, I would have thought that I would be back to my starting point, but the final result (after running it twice) does not hash correctly, and the contents are jibberish.
If I then manually count the input file size and set the read_length accordingly:
loop do
read_length = do_length(fsize)
buf = Slice(UInt8).new(read_length)
n = infile.read(buf)
break if n == 0
buf.reverse!
outfile.write(buf[0...n])
fsize -= read_length
end
where do_length is:
if infile_size < 4096 # infile_size counts down in the above loop
read_length = infile_size
else
read_length = 4096
end
Now it will give me my expected result, i.e., if I run it twice, once on an input file and that on that output, I’m back to the same hash as the original input, which is interesting, as only the last slice read would not be 4096, furthermore, read_length must be an exponential growth of 8, i.e., 1024, 2048, 4096, as a random multiple of 8 will give trash results. As an example, 3072 does not work.
This snippet doesn’t actually do anything useful, just an interesting observation from a hobbyist, and I’m sure there’s an explanation.