Source file src/hash/example_test.go

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package hash_test
     6  
     7  import (
     8  	"bytes"
     9  	"crypto/sha256"
    10  	"encoding"
    11  	"fmt"
    12  	"log"
    13  )
    14  
    15  func Example_binaryMarshaler() {
    16  	const (
    17  		input1 = "The tunneling gopher digs downwards, "
    18  		input2 = "unaware of what he will find."
    19  	)
    20  
    21  	first := sha256.New()
    22  	first.Write([]byte(input1))
    23  
    24  	marshaler, ok := first.(encoding.BinaryMarshaler)
    25  	if !ok {
    26  		log.Fatal("first does not implement encoding.BinaryMarshaler")
    27  	}
    28  	state, err := marshaler.MarshalBinary()
    29  	if err != nil {
    30  		log.Fatal("unable to marshal hash:", err)
    31  	}
    32  
    33  	second := sha256.New()
    34  
    35  	unmarshaler, ok := second.(encoding.BinaryUnmarshaler)
    36  	if !ok {
    37  		log.Fatal("second does not implement encoding.BinaryUnmarshaler")
    38  	}
    39  	if err := unmarshaler.UnmarshalBinary(state); err != nil {
    40  		log.Fatal("unable to unmarshal hash:", err)
    41  	}
    42  
    43  	first.Write([]byte(input2))
    44  	second.Write([]byte(input2))
    45  
    46  	fmt.Printf("%x\n", first.Sum(nil))
    47  	fmt.Println(bytes.Equal(first.Sum(nil), second.Sum(nil)))
    48  	// Output:
    49  	// 57d51a066f3a39942649cd9a76c77e97ceab246756ff3888659e6aa5a07f4a52
    50  	// true
    51  }
    52  

View as plain text