ghash_pjw.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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/gogf/gf.
  6. package ghash
  7. // PJW implements the classic PJW hash algorithm for 32 bits.
  8. func PJW(str []byte) uint32 {
  9. var (
  10. BitsInUnsignedInt uint32 = 32 // 4 * 8
  11. ThreeQuarters = (BitsInUnsignedInt * 3) / 4
  12. OneEighth = BitsInUnsignedInt / 8
  13. HighBits uint32 = (0xFFFFFFFF) << (BitsInUnsignedInt - OneEighth)
  14. hash uint32
  15. test uint32
  16. )
  17. for i := 0; i < len(str); i++ {
  18. hash = (hash << OneEighth) + uint32(str[i])
  19. if test = hash & HighBits; test != 0 {
  20. hash = (hash ^ (test >> ThreeQuarters)) & (^HighBits + 1)
  21. }
  22. }
  23. return hash
  24. }
  25. // PJW64 implements the classic PJW hash algorithm for 64 bits.
  26. func PJW64(str []byte) uint64 {
  27. var (
  28. BitsInUnsignedInt uint64 = 32 // 4 * 8
  29. ThreeQuarters = (BitsInUnsignedInt * 3) / 4
  30. OneEighth = BitsInUnsignedInt / 8
  31. HighBits uint64 = (0xFFFFFFFFFFFFFFFF) << (BitsInUnsignedInt - OneEighth)
  32. hash uint64
  33. test uint64
  34. )
  35. for i := 0; i < len(str); i++ {
  36. hash = (hash << OneEighth) + uint64(str[i])
  37. if test = hash & HighBits; test != 0 {
  38. hash = (hash ^ (test >> ThreeQuarters)) & (^HighBits + 1)
  39. }
  40. }
  41. return hash
  42. }