@@ -24,33 +24,16 @@ const (
24
24
// If MaxLen is not 0, make sure MaxLen >= 4.
25
25
var MaxLen int
26
26
27
- // FIXME: the logic of HashStrBytes, HashStrRevBytes, IndexRabinKarpBytes and HashStr, HashStrRev ,
28
- // IndexRabinKarp are exactly the same, except that the types are different. Can we eliminate
29
- // three of them without causing allocation?
27
+ // FIXME: the logic of IndexRabinKarpBytes and IndexRabinKarp are exactly the same ,
28
+ // except that the types are different.
29
+ // Can we eliminate three of them without causing allocation?
30
30
31
31
// PrimeRK is the prime base used in Rabin-Karp algorithm.
32
32
const PrimeRK = 16777619
33
33
34
- // HashStrBytes returns the hash and the appropriate multiplicative
35
- // factor for use in Rabin-Karp algorithm.
36
- func HashStrBytes (sep []byte ) (uint32 , uint32 ) {
37
- hash := uint32 (0 )
38
- for i := 0 ; i < len (sep ); i ++ {
39
- hash = hash * PrimeRK + uint32 (sep [i ])
40
- }
41
- var pow , sq uint32 = 1 , PrimeRK
42
- for i := len (sep ); i > 0 ; i >>= 1 {
43
- if i & 1 != 0 {
44
- pow *= sq
45
- }
46
- sq *= sq
47
- }
48
- return hash , pow
49
- }
50
-
51
34
// HashStr returns the hash and the appropriate multiplicative
52
35
// factor for use in Rabin-Karp algorithm.
53
- func HashStr (sep string ) (uint32 , uint32 ) {
36
+ func HashStr [ T string | [] byte ] (sep T ) (uint32 , uint32 ) {
54
37
hash := uint32 (0 )
55
38
for i := 0 ; i < len (sep ); i ++ {
56
39
hash = hash * PrimeRK + uint32 (sep [i ])
@@ -65,26 +48,9 @@ func HashStr(sep string) (uint32, uint32) {
65
48
return hash , pow
66
49
}
67
50
68
- // HashStrRevBytes returns the hash of the reverse of sep and the
69
- // appropriate multiplicative factor for use in Rabin-Karp algorithm.
70
- func HashStrRevBytes (sep []byte ) (uint32 , uint32 ) {
71
- hash := uint32 (0 )
72
- for i := len (sep ) - 1 ; i >= 0 ; i -- {
73
- hash = hash * PrimeRK + uint32 (sep [i ])
74
- }
75
- var pow , sq uint32 = 1 , PrimeRK
76
- for i := len (sep ); i > 0 ; i >>= 1 {
77
- if i & 1 != 0 {
78
- pow *= sq
79
- }
80
- sq *= sq
81
- }
82
- return hash , pow
83
- }
84
-
85
51
// HashStrRev returns the hash of the reverse of sep and the
86
52
// appropriate multiplicative factor for use in Rabin-Karp algorithm.
87
- func HashStrRev (sep string ) (uint32 , uint32 ) {
53
+ func HashStrRev [ T string | [] byte ] (sep T ) (uint32 , uint32 ) {
88
54
hash := uint32 (0 )
89
55
for i := len (sep ) - 1 ; i >= 0 ; i -- {
90
56
hash = hash * PrimeRK + uint32 (sep [i ])
@@ -103,7 +69,7 @@ func HashStrRev(sep string) (uint32, uint32) {
103
69
// first occurrence of substr in s, or -1 if not present.
104
70
func IndexRabinKarpBytes (s , sep []byte ) int {
105
71
// Rabin-Karp search
106
- hashsep , pow := HashStrBytes (sep )
72
+ hashsep , pow := HashStr (sep )
107
73
n := len (sep )
108
74
var h uint32
109
75
for i := 0 ; i < n ; i ++ {
0 commit comments