Skip to content
Myr

chars.go

This file

Path

src/util/chars.go

481 lines · 11.7 KiB · Go

Last changed by

Clean up comments and testsJunegunn Choibefore adoption2885df8

History of this file

Take it

The walk stopped after 200 commits: lines older than 76efddd point at it.

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 1–5why, one step back
1package util
23import (4 "bytes"5 "fmt"

Avoid over-allocation in ToCharsJunegunn Choibefore adoption759b7c3

line 6why, one step back
6 "math/bits"

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 7–16why, one step back
7 "unicode"
8 "unicode/utf8"9 "unsafe"10)1112const (13 overflow64 uint64 = 0x808080808080808014 overflow32 uint32 = 0x8080808015)16

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

lines 17–21why, one step back
17const (
18 flagInBytes uint8 = 1 << iota19 flagMayFold20)21

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

line 22why, one step back
22type Chars struct {

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

line 23why, one step back
23 slice []byte // or []rune

Copy the item text in replace-queryJunegunn Choibefore adoption7b16e44

lines 24–26why, one step back
24 // Only ever set, never cleared, so a reader racing a Prepend sees either
25 // the old or the new value and both are safe. trimLength* is kept out26 // because TrimLength rewrites it.

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

line 27why, one step back
27 flags uint8

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 28–35why, one step back
28 trimLengthKnown bool
29 trimLength uint163031 // XXX Piggybacking item index here is a horrible idea. But I'm trying to32 // minimize the memory footprint by not wasting padded spaces.33 Index int3234}35

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

lines 36–38why, one step back
36// Rune ranges that case folding or normalization can turn into ASCII, derived
37// from algo's normalization table and unicode.ToLower, then merged. They are a38// superset of the exact set, which TestMayFoldToAsciiIsSuperset in the algo

Clean up comments and testsJunegunn Choibefore adoption2885df8

lines 39–41why, one step back
39// package verifies. Grouped tightly on purpose: a wider merge would include
40// Greek Extended, General Punctuation and the currency and letterlike blocks,41// and every line holding a curly quote or an em dash would then lose the

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

lines 42–88why, one step back
42// prefilter. Cyrillic, Greek, Hebrew, Arabic, Thai, Devanagari, CJK, Hangul,
43// kana, emoji, punctuation and box drawing are all outside.44const (45 foldLo = 0x00C046 foldHi = 0xFF6147)4849var foldableRanges = [...][2]rune{50 {0x00C0, 0x01B6}, // Latin-1 Supplement, Latin Extended-A and -B51 {0x01CD, 0x02AE}, // rest of Latin Extended-B and IPA Extensions52 {0x0363, 0x036F}, // combining Latin small letters53 {0x1D00, 0x1D22}, // Phonetic Extensions, small capitals54 {0x1D62, 0x1D65}, // subscript letters55 {0x1E00, 0x1EF9}, // Latin Extended Additional56 {0x2071, 0x2071}, // superscript i57 {0x2095, 0x209C}, // subscript letters58 {0x212A, 0x212B}, // KELVIN SIGN and ANGSTROM SIGN, which fold by case59 {0x2183, 0x2184}, // reversed roman numeral one hundred60 {0x2C62, 0x2C7F}, // Latin Extended-C61 {0xA78D, 0xA78D}, // Latin Extended-D62 {0xA7AA, 0xA7B2}, // more Latin Extended-D63 {0xA7C5, 0xA7C5},64 {0xFF01, 0xFF61}, // fullwidth ASCII forms, and halfwidth ideographic full stop65}6667// Walking the ranges costs a serial chain of comparisons per rune, which is68// measurable at ingestion, so precompute a bitmap instead.69var foldableBits = func() (bits [(foldHi-foldLo)/8 + 1]byte) {70 for _, r := range foldableRanges {71 for c := r[0]; c <= r[1]; c++ {72 i := c - foldLo73 bits[i>>3] |= 1 << (i & 7)74 }75 }76 return77}()7879// MayFoldToAscii reports whether case folding or normalization could turn r80// into an ASCII character.81func MayFoldToAscii(r rune) bool {82 i := uint32(r - foldLo)83 if i > foldHi-foldLo {84 return false85 }86 return foldableBits[i>>3]&(1<<(i&7)) != 087}88

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 89–108why, one step back
89func checkAscii(bytes []byte) (bool, int) {
90 i := 091 for ; i <= len(bytes)-8; i += 8 {92 if (overflow64 & *(*uint64)(unsafe.Pointer(&bytes[i]))) > 0 {93 return false, i94 }95 }96 for ; i <= len(bytes)-4; i += 4 {97 if (overflow32 & *(*uint32)(unsafe.Pointer(&bytes[i]))) > 0 {98 return false, i99 }100 }101 for ; i < len(bytes); i++ {102 if bytes[i] >= utf8.RuneSelf {103 return false, i104 }105 }106 return true, 0107}108

Avoid over-allocation in ToCharsJunegunn Choibefore adoption759b7c3

lines 109–128why, one step back
109// countRunes counts the bytes that are not UTF-8 continuation bytes, which is
110// the rune count of valid UTF-8. Each invalid byte decodes to its own111// RuneError, so the result can undercount but never overcount, making it safe112// as a capacity hint.113func countRunes(bytes []byte) int {114 n, i := 0, 0115 for ; i <= len(bytes)-8; i += 8 {116 v := *(*uint64)(unsafe.Pointer(&bytes[i]))117 // Continuation byte: bit 7 set, bit 6 clear. In `v << 1` bit 7 of each118 // lane holds bit 6 of that same lane.119 n += 8 - bits.OnesCount64(v&^(v<<1)&overflow64)120 }121 for ; i < len(bytes); i++ {122 if bytes[i]&0xC0 != 0x80 {123 n++124 }125 }126 return n127}128

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 129–132why, one step back
129// ToChars converts byte array into rune array
130func ToChars(bytes []byte) Chars {131 inBytes, bytesUntil := checkAscii(bytes)132 if inBytes {

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

line 133why, one step back
133 return Chars{slice: bytes, flags: flagInBytes}

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 134–135why, one step back
134 }
135

Avoid over-allocation in ToCharsJunegunn Choibefore adoption759b7c3

line 136why, one step back
136 runes := make([]rune, bytesUntil, bytesUntil+countRunes(bytes[bytesUntil:]))

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 137–139why, one step back
137 for i := range bytesUntil {
138 runes[i] = rune(bytes[i])139 }

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

line 140why, one step back
140 mayFold := false

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

line 141why, one step back
141 for i := bytesUntil; i < len(bytes); {

Skip rune decoding for ASCII bytes in ToCharsJunegunn Choibefore adoption793e58b

lines 142–143why, one step back
142 // utf8.DecodeRune has an ASCII path of its own, but it is too complex
143 // to inline, so a mostly-ASCII line pays one call per byte for it.

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

line 144why, one step back
144 // An ASCII rune never sets the fold bit either, so skip both calls.

Skip rune decoding for ASCII bytes in ToCharsJunegunn Choibefore adoption793e58b

lines 145–149why, one step back
145 if b := bytes[i]; b < utf8.RuneSelf {
146 runes = append(runes, rune(b))147 i++148 continue149 }

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 150–151why, one step back
150 r, sz := utf8.DecodeRune(bytes[i:])
151 i += sz

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

line 152why, one step back
152 mayFold = mayFold || MayFoldToAscii(r)

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 153–154why, one step back
153 runes = append(runes, r)
154 }

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

line 155why, one step back
155 return runesToChars(runes, mayFold)

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 156–157why, one step back
156}
157

Copy the item text in replace-queryJunegunn Choibefore adoption7b16e44

lines 158–159why, one step back
158// RunesToChars adopts the caller's slice rather than copying it, so the caller
159// must not keep mutating it. See Runes for why.

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

line 160why, one step back
160func RunesToChars(runes []rune) Chars {

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

lines 161–168why, one step back
161 mayFold := false
162 for _, r := range runes {163 if MayFoldToAscii(r) {164 mayFold = true165 break166 }167 }168 return runesToChars(runes, mayFold)

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 169–170why, one step back
169}
170

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

lines 171–178why, one step back
171func runesToChars(runes []rune, mayFold bool) Chars {
172 var flags uint8173 if mayFold {174 flags = flagMayFold175 }176 return Chars{slice: *(*[]byte)(unsafe.Pointer(&runes)), flags: flags}177}178

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

line 179why, one step back
179func (chars *Chars) IsBytes() bool {

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

line 180why, one step back
180 return chars.flags&flagInBytes != 0

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 181–182why, one step back
181}
182

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

lines 183–190why, one step back
183// MayFoldToAscii reports whether the text holds a rune that case folding or
184// normalization could turn into an ASCII character. When false, an ASCII185// pattern character can only match the identical ASCII rune, which is what186// lets the prefilter scan the rune array directly.187func (chars *Chars) MayFoldToAscii() bool {188 return chars.flags&flagMayFold != 0189}190

Copy the item text in replace-queryJunegunn Choibefore adoption7b16e44

lines 191–194why, one step back
191// Runes returns the underlying rune slice, or nil if the text is kept as
192// bytes. Read only. The result aliases the text, so writing to it would change193// the text without updating the cached fold bit, and the prefilter would then194// reject items it should match. Copy before mutating.

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

lines 195–198why, one step back
195func (chars *Chars) Runes() []rune {
196 return chars.optionalRunes()197}198

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 199–232why, one step back
199func (chars *Chars) Bytes() []byte {
200 return chars.slice201}202203func (chars *Chars) NumLines(atMost int) (int, bool) {204 lines := 1205 if runes := chars.optionalRunes(); runes != nil {206 for _, r := range runes {207 if r == '\n' {208 lines++209 }210 if lines > atMost {211 return atMost, true212 }213 }214 return lines, false215 }216217 for idx := 0; idx < len(chars.slice); idx++ {218 found := bytes.IndexByte(chars.slice[idx:], '\n')219 if found < 0 {220 break221 }222223 idx += found224 lines++225 if lines > atMost {226 return atMost, true227 }228 }229 return lines, false230}231232func (chars *Chars) optionalRunes() []rune {

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

line 233why, one step back
233 if chars.IsBytes() {

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 234–254why, one step back
234 return nil
235 }236 return *(*[]rune)(unsafe.Pointer(&chars.slice))237}238239func (chars *Chars) Get(i int) rune {240 if runes := chars.optionalRunes(); runes != nil {241 return runes[i]242 }243 return rune(chars.slice[i])244}245246func (chars *Chars) Length() int {247 if runes := chars.optionalRunes(); runes != nil {248 return len(runes)249 }250 return len(chars.slice)251}252253// String returns the string representation of a Chars object.254func (chars *Chars) String() string {

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

line 255why, one step back
255 return fmt.Sprintf("Chars{slice: []byte(%q), inBytes: %v, mayFold: %v, trimLengthKnown: %v, trimLength: %d, Index: %d}", chars.slice, chars.IsBytes(), chars.MayFoldToAscii(), chars.trimLengthKnown, chars.trimLength, chars.Index)

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 256–345why, one step back
256}
257258// TrimLength returns the length after trimming leading and trailing whitespaces259func (chars *Chars) TrimLength() uint16 {260 if chars.trimLengthKnown {261 return chars.trimLength262 }263 chars.trimLengthKnown = true264 var i int265 len := chars.Length()266 for i = len - 1; i >= 0; i-- {267 char := chars.Get(i)268 if !unicode.IsSpace(char) {269 break270 }271 }272 // Completely empty273 if i < 0 {274 return 0275 }276277 var j int278 for j = 0; j < len; j++ {279 char := chars.Get(j)280 if !unicode.IsSpace(char) {281 break282 }283 }284 chars.trimLength = AsUint16(i - j + 1)285 return chars.trimLength286}287288func (chars *Chars) LeadingWhitespaces() int {289 whitespaces := 0290 for i := 0; i < chars.Length(); i++ {291 char := chars.Get(i)292 if !unicode.IsSpace(char) {293 break294 }295 whitespaces++296 }297 return whitespaces298}299300func (chars *Chars) TrailingWhitespaces() int {301 whitespaces := 0302 for i := chars.Length() - 1; i >= 0; i-- {303 char := chars.Get(i)304 if !unicode.IsSpace(char) {305 break306 }307 whitespaces++308 }309 return whitespaces310}311312func (chars *Chars) TrimTrailingWhitespaces(maxIndex int) {313 whitespaces := chars.TrailingWhitespaces()314 end := len(chars.slice) - whitespaces315 chars.slice = chars.slice[0:max(end, maxIndex)]316}317318func (chars *Chars) TrimSuffix(runes []rune) {319 lastIdx := len(chars.slice)320 firstIdx := lastIdx - len(runes)321 if firstIdx < 0 {322 return323 }324325 for i := firstIdx; i < lastIdx; i++ {326 char := chars.Get(i)327 if char != runes[i-firstIdx] {328 return329 }330 }331332 chars.slice = chars.slice[0:firstIdx]333}334335func (chars *Chars) SliceRight(last int) {336 chars.slice = chars.slice[:last]337}338339func (chars *Chars) ToString() string {340 if runes := chars.optionalRunes(); runes != nil {341 return string(runes)342 }343 return unsafe.String(unsafe.SliceData(chars.slice), len(chars.slice))344}345

Copy the item text in replace-queryJunegunn Choibefore adoption7b16e44

lines 346–347why, one step back
346// ToRunes returns the text as runes. In rune mode the result aliases the text
347// and must not be mutated, see Runes. In byte mode it is a fresh slice.

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 348–375why, one step back
348func (chars *Chars) ToRunes() []rune {
349 if runes := chars.optionalRunes(); runes != nil {350 return runes351 }352 bytes := chars.slice353 runes := make([]rune, len(bytes))354 for idx, b := range bytes {355 runes[idx] = rune(b)356 }357 return runes358}359360func (chars *Chars) CopyRunes(dest []rune, from int) {361 if runes := chars.optionalRunes(); runes != nil {362 copy(dest, runes[from:])363 return364 }365 for idx, b := range chars.slice[from:][:len(dest)] {366 dest[idx] = rune(b)367 }368}369370func (chars *Chars) Prepend(prefix string) {371 if runes := chars.optionalRunes(); runes != nil {372 runes = append([]rune(prefix), runes...)373 chars.slice = *(*[]byte)(unsafe.Pointer(&runes))374 } else {375 chars.slice = append([]byte(prefix), chars.slice...)

Prefilter rune-mode inputJunegunn Choibefore adoptiona650900

lines 376–381why, one step back
376 }
377 for _, r := range prefix {378 if MayFoldToAscii(r) {379 chars.flags |= flagMayFold380 break381 }

bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd

lines 382–481why, one step back
382 }
383}384385func (chars *Chars) Lines(multiLine bool, maxLines int, wrapCols int, wrapSignWidth int, tabstop int, wrapWord bool) ([][]rune, bool) {386 text := make([]rune, chars.Length())387 copy(text, chars.ToRunes())388389 lines := [][]rune{}390 overflow := false391 if !multiLine {392 lines = append(lines, text)393 } else {394 from := 0395 for off := range text {396 if text[off] == '\n' {397 lines = append(lines, text[from:off+1]) // Include '\n'398 from = off + 1399 if len(lines) >= maxLines {400 break401 }402 }403 }404405 var lastLine []rune406 if from < len(text) {407 lastLine = text[from:]408 }409410 overflow = false411 if len(lines) >= maxLines {412 overflow = true413 } else {414 lines = append(lines, lastLine)415 }416 }417418 // If wrapping is disabled, we're done419 if wrapCols == 0 {420 return lines, overflow421 }422423 wrapped := [][]rune{}424 for _, line := range lines {425 // Remove trailing '\n' and remember if it was there426 newline := len(line) > 0 && line[len(line)-1] == '\n'427 if newline {428 line = line[:len(line)-1]429 }430431 hasWrapSign := false432 for {433 cols := wrapCols434 if hasWrapSign {435 cols -= wrapSignWidth436 }437 _, overflowIdx := RunesWidth(line, 0, tabstop, cols)438 if overflowIdx >= 0 {439 // Might be a wide character440 if overflowIdx == 0 {441 overflowIdx = 1442 }443 if wrapWord {444 // Find last space/tab at or before overflowIdx445 breakIdx := -1446 for k := overflowIdx; k > 0; k-- {447 if line[k-1] == ' ' || line[k-1] == '\t' {448 breakIdx = k449 break450 }451 }452 if breakIdx > 0 {453 overflowIdx = breakIdx454 }455 }456 if len(wrapped) >= maxLines {457 return wrapped, true458 }459 wrapped = append(wrapped, line[:overflowIdx])460 hasWrapSign = true461 line = line[overflowIdx:]462 continue463 }464 hasWrapSign = false465466 // Restore trailing '\n'467 if newline {468 line = append(line, '\n')469 }470471 if len(wrapped) >= maxLines {472 return wrapped, true473 }474475 wrapped = append(wrapped, line)476 break477 }478 }479480 return wrapped, overflow481}