Skip to content

Commit 92fd12c

Browse files
crypto.sha256: add .free() and .reset() methods to reduce memory leaks with -autofree (#16991)
1 parent e5fb457 commit 92fd12c

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

vlib/crypto/sha256/sha256.v

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,25 @@ mut:
4848
is224 bool // mark if this digest is SHA-224
4949
}
5050

51-
fn (mut d Digest) reset() {
51+
// free the resources taken by the Digest `d`
52+
[unsafe]
53+
pub fn (mut d Digest) free() {
54+
$if prealloc {
55+
return
56+
}
57+
unsafe {
58+
d.x.free()
59+
d.h.free()
60+
}
61+
}
62+
63+
fn (mut d Digest) init() {
5264
d.h = []u32{len: (8)}
5365
d.x = []u8{len: sha256.chunk}
66+
}
67+
68+
// reset the state of the Digest `d`
69+
pub fn (mut d Digest) reset() {
5470
if !d.is224 {
5571
d.h[0] = u32(sha256.init0)
5672
d.h[1] = u32(sha256.init1)
@@ -77,6 +93,7 @@ fn (mut d Digest) reset() {
7793
// new returns a new Digest (implementing hash.Hash) computing the SHA256 checksum.
7894
pub fn new() &Digest {
7995
mut d := &Digest{}
96+
d.init()
8097
d.reset()
8198
return d
8299
}
@@ -85,6 +102,7 @@ pub fn new() &Digest {
85102
pub fn new224() &Digest {
86103
mut d := &Digest{}
87104
d.is224 = true
105+
d.init()
88106
d.reset()
89107
return d
90108
}

vlib/crypto/sha256/sha256_test.v

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,15 @@ fn test_crypto_sha256_writer() {
1414
sum := digest.sum([])
1515
assert sum.hex() == 'dc7163299659529eae29683eb1ffec50d6c8fc7275ecb10c145fde0e125b8727'
1616
}
17+
18+
fn test_crypto_sha256_writer_reset() {
19+
mut digest := sha256.new()
20+
digest.write('This is a'.bytes()) or { assert false }
21+
digest.write(' sha256 checksum.'.bytes()) or { assert false }
22+
_ = digest.sum([])
23+
digest.reset()
24+
digest.write('This is a'.bytes()) or { assert false }
25+
digest.write(' sha256 checksum.'.bytes()) or { assert false }
26+
sum := digest.sum([])
27+
assert sum.hex() == 'dc7163299659529eae29683eb1ffec50d6c8fc7275ecb10c145fde0e125b8727'
28+
}

0 commit comments

Comments
 (0)