github.com/wangyougui/gf/v2@v2.6.5/encoding/ghash/ghash_pjw.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package ghash
     8  
     9  // PJW implements the classic PJW hash algorithm for 32 bits.
    10  func PJW(str []byte) uint32 {
    11  	var (
    12  		BitsInUnsignedInt uint32 = 32 // 4 * 8
    13  		ThreeQuarters            = (BitsInUnsignedInt * 3) / 4
    14  		OneEighth                = BitsInUnsignedInt / 8
    15  		HighBits          uint32 = (0xFFFFFFFF) << (BitsInUnsignedInt - OneEighth)
    16  		hash              uint32
    17  		test              uint32
    18  	)
    19  	for i := 0; i < len(str); i++ {
    20  		hash = (hash << OneEighth) + uint32(str[i])
    21  		if test = hash & HighBits; test != 0 {
    22  			hash = (hash ^ (test >> ThreeQuarters)) & (^HighBits + 1)
    23  		}
    24  	}
    25  	return hash
    26  }
    27  
    28  // PJW64 implements the classic PJW hash algorithm for 64 bits.
    29  func PJW64(str []byte) uint64 {
    30  	var (
    31  		BitsInUnsignedInt uint64 = 32 // 4 * 8
    32  		ThreeQuarters            = (BitsInUnsignedInt * 3) / 4
    33  		OneEighth                = BitsInUnsignedInt / 8
    34  		HighBits          uint64 = (0xFFFFFFFFFFFFFFFF) << (BitsInUnsignedInt - OneEighth)
    35  		hash              uint64
    36  		test              uint64
    37  	)
    38  	for i := 0; i < len(str); i++ {
    39  		hash = (hash << OneEighth) + uint64(str[i])
    40  		if test = hash & HighBits; test != 0 {
    41  			hash = (hash ^ (test >> ThreeQuarters)) & (^HighBits + 1)
    42  		}
    43  	}
    44  	return hash
    45  }