Fix hashing context example

Example now works for any file size instead of just multiples of CHUNK_SIZE
Example also uses correct method for looping over file data
This commit is contained in:
David Peck 2024-05-14 19:12:38 +12:00 committed by David Peck
parent 557f63d037
commit d6715b4cde
1 changed files with 6 additions and 4 deletions

View File

@ -20,8 +20,9 @@
# Open the file to hash. # Open the file to hash.
var file = FileAccess.open(path, FileAccess.READ) var file = FileAccess.open(path, FileAccess.READ)
# Update the context after reading each chunk. # Update the context after reading each chunk.
while not file.eof_reached(): while file.get_position() < file.get_length():
ctx.update(file.get_buffer(CHUNK_SIZE)) var remaining = file.get_length() - file.get_position()
ctx.update(file.get_buffer(min(remaining, CHUNK_SIZE)))
# Get the computed hash. # Get the computed hash.
var res = ctx.finish() var res = ctx.finish()
# Print the result as hex string and array. # Print the result as hex string and array.
@ -43,9 +44,10 @@
// Open the file to hash. // Open the file to hash.
using var file = FileAccess.Open(path, FileAccess.ModeFlags.Read); using var file = FileAccess.Open(path, FileAccess.ModeFlags.Read);
// Update the context after reading each chunk. // Update the context after reading each chunk.
while (!file.EofReached()) while (file.GetPosition() < file.GetLength())
{ {
ctx.Update(file.GetBuffer(ChunkSize)); int remaining = (int)(file.GetLength() - file.GetPosition());
ctx.Update(file.GetBuffer(Mathf.Min(remaining, ChunkSize)));
} }
// Get the computed hash. // Get the computed hash.
byte[] res = ctx.Finish(); byte[] res = ctx.Finish();