istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/util/hash/hash.go (about)

     1  // Copyright Istio Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package hash
    16  
    17  import (
    18  	"encoding/hex"
    19  
    20  	"github.com/cespare/xxhash/v2"
    21  )
    22  
    23  type Hash interface {
    24  	Write(p []byte) (n int)
    25  	WriteString(s string) (n int)
    26  	Sum() string
    27  	Sum64() uint64
    28  }
    29  
    30  type instance struct {
    31  	hash *xxhash.Digest
    32  }
    33  
    34  var _ Hash = &instance{}
    35  
    36  func New() Hash {
    37  	return &instance{
    38  		hash: xxhash.New(),
    39  	}
    40  }
    41  
    42  // Write wraps the Hash.Write function call
    43  // Hash.Write error always return nil, this func simplify caller handle error
    44  func (i *instance) Write(p []byte) (n int) {
    45  	n, _ = i.hash.Write(p)
    46  	return
    47  }
    48  
    49  // Write wraps the Hash.Write function call
    50  // Hash.Write error always return nil, this func simplify caller handle error
    51  func (i *instance) WriteString(s string) (n int) {
    52  	n, _ = i.hash.WriteString(s)
    53  	return
    54  }
    55  
    56  func (i *instance) Sum64() uint64 {
    57  	return i.hash.Sum64()
    58  }
    59  
    60  func (i *instance) Sum() string {
    61  	sum := i.hash.Sum(nil)
    62  	return hex.EncodeToString(sum)
    63  }