Skip to content
Myr

Speed up initial scanning with bitwise AND operation

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Junegunn Choi · committed by Junegunn Choi · parent 9e85cba · Browse files · 1 file+36 added−22 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+36 added−22 removed

  • other:+36 added−22 removed

1 file+36 added−22 removed

modified:src/util/chars.go+36 added-22 removed
4 unmodified lines
5 "unicode/utf8"6 "unsafe"7)89const (10 overflow64 uint64 = 0x808080808080808011 overflow32 uint32 = 0x8080808012)1314type Chars struct {15 slice []byte // or []rune16 inBytes bool17 trimLengthKnown bool
3 unmodified lines
21 // minimize the memory footprint by not wasting padded spaces.22 Index int3223}2420// ToChars converts byte array into rune array21func ToChars(bytes []byte) Chars {22 var runes []rune23 inBytes := true24 numBytes := len(bytes)25 for i := 0; i < numBytes; {26 if bytes[i] < utf8.RuneSelf {27 if !inBytes {28 runes = append(runes, rune(bytes[i]))29 }30 i++31 } else {32 if inBytes {33 inBytes = false34 runes = make([]rune, i, numBytes)35 for j := 0; j < i; j++ {36 runes[j] = rune(bytes[j])37 }38 }39 r, sz := utf8.DecodeRune(bytes[i:])40 i += sz41 runes = append(runes, r)25func checkAscii(bytes []byte) (bool, int) {26 i := 027 for ; i < len(bytes)-8; i += 8 {28 if (overflow64 & *(*uint64)(unsafe.Pointer(&bytes[i]))) > 0 {29 return false, i30 }31 }32 for ; i < len(bytes)-4; i += 4 {33 if (overflow32 & *(*uint32)(unsafe.Pointer(&bytes[i]))) > 0 {34 return false, i35 }36 }37 for ; i < len(bytes); i++ {38 if bytes[i] >= utf8.RuneSelf {39 return false, i40 }41 }42 return true, 043}4445// ToChars converts byte array into rune array46func ToChars(bytes []byte) Chars {47 inBytes, bytesUntil := checkAscii(bytes)48 if inBytes {49 return Chars{slice: bytes, inBytes: inBytes}50 }5152 runes := make([]rune, bytesUntil, len(bytes))53 for i := 0; i < bytesUntil; i++ {54 runes[i] = rune(bytes[i])55 }56 for i := bytesUntil; i < len(bytes); {57 r, sz := utf8.DecodeRune(bytes[i:])58 i += sz59 runes = append(runes, r)60 }61 return RunesToChars(runes)62}6364func RunesToChars(runes []rune) Chars {
138 unmodified lines