github.com/matrixorigin/matrixone@v1.2.0/pkg/vectorize/instr/instr.go (about)

     1  // Copyright 2022 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //	http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package instr
    16  
    17  import (
    18  	"strings"
    19  	"unicode"
    20  )
    21  
    22  func isASCII(s string) bool {
    23  	for i := 0; i < len(s); i++ {
    24  		if s[i] > unicode.MaxASCII {
    25  			return false
    26  		}
    27  	}
    28  	return true
    29  }
    30  
    31  func kmp(r1, r2 []rune) int64 {
    32  	next := make([]int, len(r2))
    33  	next[0] = -1
    34  	for i, j := 0, -1; i < len(r2)-1; {
    35  		if j == -1 || r2[i] == r2[j] {
    36  			i++
    37  			j++
    38  			next[i] = j
    39  		} else {
    40  			j = next[j]
    41  		}
    42  	}
    43  	for i, j := 0, 0; i < len(r1); {
    44  		if j == -1 || r1[i] == r2[j] {
    45  			i++
    46  			j++
    47  		} else {
    48  			j = next[j]
    49  		}
    50  		if j == len(r2) {
    51  			return int64(i - j + 1)
    52  		}
    53  	}
    54  	return 0
    55  }
    56  
    57  func Single(str string, substr string) int64 {
    58  	if len(substr) == 0 {
    59  		return 1
    60  	}
    61  	if isASCII(str) {
    62  		if !isASCII(substr) {
    63  			return 0
    64  		}
    65  		return int64(strings.Index(strings.ToLower(str), strings.ToLower(substr)) + 1)
    66  	}
    67  
    68  	r1, r2 := []rune(strings.ToLower(str)), []rune(strings.ToLower(substr))
    69  	return kmp(r1, r2)
    70  }