find_match_length.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package brotli
  2. import (
  3. "encoding/binary"
  4. "math/bits"
  5. "runtime"
  6. )
  7. /* Copyright 2010 Google Inc. All Rights Reserved.
  8. Distributed under MIT license.
  9. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  10. */
  11. /* Function to find maximal matching prefixes of strings. */
  12. func findMatchLengthWithLimit(s1 []byte, s2 []byte, limit uint) uint {
  13. var matched uint = 0
  14. _, _ = s1[limit-1], s2[limit-1] // bounds check
  15. switch runtime.GOARCH {
  16. case "amd64":
  17. // Compare 8 bytes at at time.
  18. for matched+8 <= limit {
  19. w1 := binary.LittleEndian.Uint64(s1[matched:])
  20. w2 := binary.LittleEndian.Uint64(s2[matched:])
  21. if w1 != w2 {
  22. return matched + uint(bits.TrailingZeros64(w1^w2)>>3)
  23. }
  24. matched += 8
  25. }
  26. case "386":
  27. // Compare 4 bytes at at time.
  28. for matched+4 <= limit {
  29. w1 := binary.LittleEndian.Uint32(s1[matched:])
  30. w2 := binary.LittleEndian.Uint32(s2[matched:])
  31. if w1 != w2 {
  32. return matched + uint(bits.TrailingZeros32(w1^w2)>>3)
  33. }
  34. matched += 4
  35. }
  36. }
  37. for matched < limit && s1[matched] == s2[matched] {
  38. matched++
  39. }
  40. return matched
  41. }