github.com/andybalholm/brotli@v1.0.6/find_match_length.go (about)

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