Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

faster case-insensitive search #48

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 43 additions & 2 deletions format_common.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package monday

import "strings"
import (
"strings"
"unicode"
"unicode/utf8"
)

func findInString(where string, what string, foundIndex *int, trimRight *int) (found bool) {
ind := strings.Index(strings.ToLower(where), strings.ToLower(what))
ind := caseFoldingIndex(where, what)
if ind != -1 {
*foundIndex = ind
*trimRight = len(where) - ind - len(what)
Expand All @@ -13,6 +17,43 @@ func findInString(where string, what string, foundIndex *int, trimRight *int) (f
return false
}

// caseFoldingIndex is like strings.Index, except that it compares strings using case folding.
// It returns the index of the first instance of substr in s, or -1 if substr is not present in s.
func caseFoldingIndex(s, substr string) int {
n := len(substr)
switch {
case n == 0:
return 0
case n == 1:
byteIndex := strings.IndexByte(s, substr[0])
if byteIndex != -1 {
return byteIndex
}
r, _ := utf8.DecodeRuneInString(substr)
for nextr := unicode.SimpleFold(r); nextr != r; nextr = unicode.SimpleFold(nextr) {
runeIndex := strings.IndexRune(s, nextr)
if runeIndex != -1 {
return runeIndex
}
}
case n == len(s):
if substr == s || strings.EqualFold(s, substr) {
return 0
}
case n > len(s):
return -1
default:
for i := 0; i <= len(s)-n; i++ {
window := []byte(s)
window = window[i : i+n]
if strings.EqualFold(string(window), substr) {
return i
}
}
}
return -1
}

// commonFormatFunc is used for languages which don't have changed forms of month names dependent
// on their position (after day or standalone)
func commonFormatFunc(value, format string,
Expand Down