github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/hash/position_inertia.go (about)

     1  // Copyright 2020 PingCAP, Inc.
     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  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package hash
    15  
    16  import (
    17  	"hash"
    18  	"hash/crc32"
    19  
    20  	"github.com/pingcap/log"
    21  	"go.uber.org/zap"
    22  )
    23  
    24  const hashMagicNumber = 0
    25  
    26  // PositionInertia is a 8-bits hash which is bytes partitions inertia
    27  type PositionInertia struct {
    28  	hashValue uint32
    29  	hasher    hash.Hash32
    30  }
    31  
    32  // NewPositionInertia creates a new position inertia algorithm hash builder
    33  func NewPositionInertia() *PositionInertia {
    34  	return &PositionInertia{
    35  		hashValue: hashMagicNumber,
    36  		hasher:    crc32.NewIEEE(),
    37  	}
    38  }
    39  
    40  // Write writes the bytes into the PositionInertia
    41  func (p *PositionInertia) Write(bss ...[]byte) {
    42  	p.hasher.Reset()
    43  	for _, bs := range bss {
    44  		_, err := p.hasher.Write(bs)
    45  		if err != nil {
    46  			log.Panic("failed to write hash", zap.Error(err))
    47  		}
    48  	}
    49  	rawHash := p.hasher.Sum32()
    50  	p.hashValue ^= rawHash
    51  }
    52  
    53  // Sum32 returns the 32-bits hash
    54  func (p *PositionInertia) Sum32() uint32 {
    55  	return p.hashValue
    56  }
    57  
    58  // Reset resets the PositionInertia
    59  func (p *PositionInertia) Reset() {
    60  	p.hashValue = hashMagicNumber
    61  }