Source file src/cmd/internal/hash/hash.go

     1  // Copyright 2024 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 implements hash functions used in the compiler toolchain.
     6  package hash
     7  
     8  // TODO(rsc): Delete the 16 and 20 forms and use 32 at all call sites.
     9  
    10  import (
    11  	"crypto/sha256"
    12  	"hash"
    13  )
    14  
    15  const (
    16  	// Size32 is the size of the 32-byte hash checksum.
    17  	Size32 = 32
    18  	// Size20 is the size of the 20-byte hash checksum.
    19  	Size20 = 20
    20  	// Size16 is the size of the 16-byte hash checksum.
    21  	Size16 = 16
    22  )
    23  
    24  type shortHash struct {
    25  	hash.Hash
    26  	n int
    27  }
    28  
    29  func (h *shortHash) Sum(b []byte) []byte {
    30  	old := b
    31  	sum := h.Hash.Sum(b)
    32  	return sum[:len(old)+h.n]
    33  }
    34  
    35  // New32 returns a new [hash.Hash] computing the 32 bytes hash checksum.
    36  func New32() hash.Hash {
    37  	h := sha256.New()
    38  	_, _ = h.Write([]byte{1}) // make this hash different from sha256
    39  	return h
    40  }
    41  
    42  // New20 returns a new [hash.Hash] computing the 20 bytes hash checksum.
    43  func New20() hash.Hash {
    44  	return &shortHash{New32(), 20}
    45  }
    46  
    47  // New16 returns a new [hash.Hash] computing the 16 bytes hash checksum.
    48  func New16() hash.Hash {
    49  	return &shortHash{New32(), 16}
    50  }
    51  
    52  // Sum32 returns the 32 bytes checksum of the data.
    53  func Sum32(data []byte) [Size32]byte {
    54  	sum := sha256.Sum256(data)
    55  	sum[0] ^= 1 // make this hash different from sha256
    56  	return sum
    57  }
    58  
    59  // Sum20 returns the 20 bytes checksum of the data.
    60  func Sum20(data []byte) [Size20]byte {
    61  	sum := Sum32(data)
    62  	var short [Size20]byte
    63  	copy(short[:], sum[4:])
    64  	return short
    65  }
    66  
    67  // Sum16 returns the 16 bytes checksum of the data.
    68  func Sum16(data []byte) [Size16]byte {
    69  	sum := Sum32(data)
    70  	var short [Size16]byte
    71  	copy(short[:], sum[8:])
    72  	return short
    73  }
    74  

View as plain text