From 92fd12c18a2a38fe3ac5205e21c81a04aca7e563 Mon Sep 17 00:00:00 2001 From: MatejMagat305 <61238240+MatejMagat305@users.noreply.github.com> Date: Mon, 16 Jan 2023 12:23:46 +0100 Subject: [PATCH] crypto.sha256: add .free() and .reset() methods to reduce memory leaks with `-autofree` (#16991) --- vlib/crypto/sha256/sha256.v | 20 +++++++++++++++++++- vlib/crypto/sha256/sha256_test.v | 12 ++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/vlib/crypto/sha256/sha256.v b/vlib/crypto/sha256/sha256.v index 0fc6280971..89638bce4c 100644 --- a/vlib/crypto/sha256/sha256.v +++ b/vlib/crypto/sha256/sha256.v @@ -48,9 +48,25 @@ mut: is224 bool // mark if this digest is SHA-224 } -fn (mut d Digest) reset() { +// free the resources taken by the Digest `d` +[unsafe] +pub fn (mut d Digest) free() { + $if prealloc { + return + } + unsafe { + d.x.free() + d.h.free() + } +} + +fn (mut d Digest) init() { d.h = []u32{len: (8)} d.x = []u8{len: sha256.chunk} +} + +// reset the state of the Digest `d` +pub fn (mut d Digest) reset() { if !d.is224 { d.h[0] = u32(sha256.init0) d.h[1] = u32(sha256.init1) @@ -77,6 +93,7 @@ fn (mut d Digest) reset() { // new returns a new Digest (implementing hash.Hash) computing the SHA256 checksum. pub fn new() &Digest { mut d := &Digest{} + d.init() d.reset() return d } @@ -85,6 +102,7 @@ pub fn new() &Digest { pub fn new224() &Digest { mut d := &Digest{} d.is224 = true + d.init() d.reset() return d } diff --git a/vlib/crypto/sha256/sha256_test.v b/vlib/crypto/sha256/sha256_test.v index c477af5bc6..7749974353 100644 --- a/vlib/crypto/sha256/sha256_test.v +++ b/vlib/crypto/sha256/sha256_test.v @@ -14,3 +14,15 @@ fn test_crypto_sha256_writer() { sum := digest.sum([]) assert sum.hex() == 'dc7163299659529eae29683eb1ffec50d6c8fc7275ecb10c145fde0e125b8727' } + +fn test_crypto_sha256_writer_reset() { + mut digest := sha256.new() + digest.write('This is a'.bytes()) or { assert false } + digest.write(' sha256 checksum.'.bytes()) or { assert false } + _ = digest.sum([]) + digest.reset() + digest.write('This is a'.bytes()) or { assert false } + digest.write(' sha256 checksum.'.bytes()) or { assert false } + sum := digest.sum([]) + assert sum.hex() == 'dc7163299659529eae29683eb1ffec50d6c8fc7275ecb10c145fde0e125b8727' +}