Skip to content

Commit eb155da

Browse files
authored
Use standardized hash.CloneHash interface (#242)
1 parent 313c54f commit eb155da

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

hash.go

+18-5
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,19 @@ func isHashMarshallable(md C.GO_EVP_MD_PTR) bool {
236236
return marshallable
237237
}
238238

239+
// cloneHash is an interface that defines a Clone method.
240+
//
241+
// hahs.CloneHash will probably be added in Go 1.25, see https://golang.org/issue/69521,
242+
// but we need it now.
243+
type cloneHash interface {
244+
hash.Hash
245+
// Clone returns a separate Hash instance with the same state as h.
246+
Clone() hash.Hash
247+
}
248+
249+
var _ hash.Hash = (*evpHash)(nil)
250+
var _ cloneHash = (*evpHash)(nil)
251+
239252
// evpHash implements generic hash methods.
240253
type evpHash struct {
241254
alg *hashAlgorithm
@@ -349,26 +362,26 @@ func (h *evpHash) Sum(in []byte) []byte {
349362
// Clone returns a new evpHash object that is a deep clone of itself.
350363
// The duplicate object contains all state and data contained in the
351364
// original object at the point of duplication.
352-
func (h *evpHash) Clone() (hash.Hash, error) {
365+
func (h *evpHash) Clone() hash.Hash {
353366
h2 := &evpHash{alg: h.alg}
354367
if h.ctx != nil {
355368
h2.ctx = C.go_openssl_EVP_MD_CTX_new()
356369
if h2.ctx == nil {
357-
return nil, newOpenSSLError("EVP_MD_CTX_new")
370+
panic(newOpenSSLError("EVP_MD_CTX_new"))
358371
}
359372
if C.go_openssl_EVP_MD_CTX_copy_ex(h2.ctx, h.ctx) != 1 {
360373
C.go_openssl_EVP_MD_CTX_free(h2.ctx)
361-
return nil, newOpenSSLError("EVP_MD_CTX_copy")
374+
panic(newOpenSSLError("EVP_MD_CTX_copy"))
362375
}
363376
h2.ctx2 = C.go_openssl_EVP_MD_CTX_new()
364377
if h2.ctx2 == nil {
365378
C.go_openssl_EVP_MD_CTX_free(h2.ctx)
366-
return nil, newOpenSSLError("EVP_MD_CTX_new")
379+
panic(newOpenSSLError("EVP_MD_CTX_new"))
367380
}
368381
runtime.SetFinalizer(h2, (*evpHash).finalize)
369382
}
370383
runtime.KeepAlive(h)
371-
return h2, nil
384+
return h2
372385
}
373386

374387
// hashState returns a pointer to the internal hash structure.

hash_test.go

+1-4
Original file line numberDiff line numberDiff line change
@@ -216,10 +216,7 @@ func TestHash_Clone(t *testing.T) {
216216
}
217217
// We don't define an interface for the Clone method to avoid other
218218
// packages from depending on it. Use type assertion to call it.
219-
h2, err := h.(interface{ Clone() (hash.Hash, error) }).Clone()
220-
if err != nil {
221-
t.Fatal(err)
222-
}
219+
h2 := h.(interface{ Clone() hash.Hash }).Clone()
223220
h.Write(msg)
224221
h2.Write(msg)
225222
if actual, actual2 := h.Sum(nil), h2.Sum(nil); !bytes.Equal(actual, actual2) {

0 commit comments

Comments
 (0)