@@ -232,21 +232,42 @@ func TestHash_Clone(t *testing.T) {
232
232
if ! openssl .SupportsHash (ch ) {
233
233
t .Skip ("not supported" )
234
234
}
235
- h := cryptoToHash (ch )()
236
- if _ , ok := h .(encoding.BinaryMarshaler ); ! ok {
237
- t .Skip ("not supported" )
238
- }
235
+ h := cryptoToHash (ch )().(openssl.HashCloner )
239
236
_ , err := h .Write (msg )
240
237
if err != nil {
241
238
t .Fatal (err )
242
239
}
243
- // We don't define an interface for the Clone method to avoid other
244
- // packages from depending on it. Use type assertion to call it.
245
- h2 := h .(interface { Clone () hash.Hash }).Clone ()
246
- h .Write (msg )
247
- h2 .Write (msg )
248
- if actual , actual2 := h .Sum (nil ), h2 .Sum (nil ); ! bytes .Equal (actual , actual2 ) {
249
- t .Errorf ("%s(%q) = 0x%x != cloned 0x%x" , ch .String (), msg , actual , actual2 )
240
+
241
+ h3 , err := h .Clone ()
242
+ if err != nil {
243
+ t .Fatalf ("Clone failed: %v" , err )
244
+ }
245
+ prefix := []byte ("tmp" )
246
+ writeToHash (t , h , prefix )
247
+ h2 , err := h .Clone ()
248
+ if err != nil {
249
+ t .Fatalf ("Clone failed: %v" , err )
250
+ }
251
+ prefixSum := h .Sum (nil )
252
+ if ! bytes .Equal (prefixSum , h2 .Sum (nil )) {
253
+ t .Fatalf ("%T Clone results are inconsistent" , h )
254
+ }
255
+ suffix := []byte ("tmp2" )
256
+ writeToHash (t , h , suffix )
257
+ writeToHash (t , h3 , append (prefix , suffix ... ))
258
+ compositeSum := h3 .Sum (nil )
259
+ if ! bytes .Equal (h .Sum (nil ), compositeSum ) {
260
+ t .Fatalf ("%T Clone results are inconsistent" , h )
261
+ }
262
+ if ! bytes .Equal (h2 .Sum (nil ), prefixSum ) {
263
+ t .Fatalf ("%T Clone results are inconsistent" , h )
264
+ }
265
+ writeToHash (t , h2 , suffix )
266
+ if ! bytes .Equal (h .Sum (nil ), compositeSum ) {
267
+ t .Fatalf ("%T Clone results are inconsistent" , h )
268
+ }
269
+ if ! bytes .Equal (h2 .Sum (nil ), compositeSum ) {
270
+ t .Fatalf ("%T Clone results are inconsistent" , h )
250
271
}
251
272
})
252
273
}
@@ -519,3 +540,20 @@ func (h *stubHash) Sum(in []byte) []byte { return in }
519
540
func (h * stubHash ) Reset () {}
520
541
func (h * stubHash ) Size () int { return 0 }
521
542
func (h * stubHash ) BlockSize () int { return 0 }
543
+
544
+ // Helper function for writing. Verifies that Write does not error.
545
+ func writeToHash (t * testing.T , h hash.Hash , p []byte ) {
546
+ t .Helper ()
547
+
548
+ before := make ([]byte , len (p ))
549
+ copy (before , p )
550
+
551
+ n , err := h .Write (p )
552
+ if err != nil || n != len (p ) {
553
+ t .Errorf ("Write returned error; got (%v, %v), want (nil, %v)" , err , n , len (p ))
554
+ }
555
+
556
+ if ! bytes .Equal (p , before ) {
557
+ t .Errorf ("Write modified input slice; got %x, want %x" , p , before )
558
+ }
559
+ }
0 commit comments