1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

crypto.sha256: add .free() and .reset() methods to reduce memory leaks with -autofree (#16991)

This commit is contained in:
MatejMagat305 2023-01-16 12:23:46 +01:00 committed by GitHub
parent e5fb457b19
commit 92fd12c18a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 1 deletions

View File

@ -48,9 +48,25 @@ mut:
is224 bool // mark if this digest is SHA-224 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.h = []u32{len: (8)}
d.x = []u8{len: sha256.chunk} d.x = []u8{len: sha256.chunk}
}
// reset the state of the Digest `d`
pub fn (mut d Digest) reset() {
if !d.is224 { if !d.is224 {
d.h[0] = u32(sha256.init0) d.h[0] = u32(sha256.init0)
d.h[1] = u32(sha256.init1) 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. // new returns a new Digest (implementing hash.Hash) computing the SHA256 checksum.
pub fn new() &Digest { pub fn new() &Digest {
mut d := &Digest{} mut d := &Digest{}
d.init()
d.reset() d.reset()
return d return d
} }
@ -85,6 +102,7 @@ pub fn new() &Digest {
pub fn new224() &Digest { pub fn new224() &Digest {
mut d := &Digest{} mut d := &Digest{}
d.is224 = true d.is224 = true
d.init()
d.reset() d.reset()
return d return d
} }

View File

@ -14,3 +14,15 @@ fn test_crypto_sha256_writer() {
sum := digest.sum([]) sum := digest.sum([])
assert sum.hex() == 'dc7163299659529eae29683eb1ffec50d6c8fc7275ecb10c145fde0e125b8727' 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'
}