| 1 |
package util |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
"math/bits" |
| 7 |
"unicode" |
| 8 |
"unicode/utf8" |
| 9 |
"unsafe" |
| 10 |
) |
| 11 |
|
| 12 |
const ( |
| 13 |
overflow64 uint64 = 0x8080808080808080 |
| 14 |
overflow32 uint32 = 0x80808080 |
| 15 |
) |
| 16 |
|
| 17 |
const ( |
| 18 |
flagInBytes uint8 = 1 << iota |
| 19 |
flagMayFold |
| 20 |
) |
| 21 |
|
| 22 |
type Chars struct { |
| 23 |
slice []byte // or []rune |
| 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 out |
| 26 |
// because TrimLength rewrites it. |
| 27 |
flags uint8 |
| 28 |
trimLengthKnown bool |
| 29 |
trimLength uint16 |
| 30 |
|
| 31 |
// XXX Piggybacking item index here is a horrible idea. But I'm trying to |
| 32 |
// minimize the memory footprint by not wasting padded spaces. |
| 33 |
Index int32 |
| 34 |
} |
| 35 |
|
| 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 a |
| 38 |
// superset of the exact set, which TestMayFoldToAsciiIsSuperset in the algo |
| 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 |
| 42 |
// prefilter. Cyrillic, Greek, Hebrew, Arabic, Thai, Devanagari, CJK, Hangul, |
| 43 |
// kana, emoji, punctuation and box drawing are all outside. |
| 44 |
const ( |
| 45 |
foldLo = 0x00C0 |
| 46 |
foldHi = 0xFF61 |
| 47 |
) |
| 48 |
|
| 49 |
var foldableRanges = [...][2]rune{ |
| 50 |
{0x00C0, 0x01B6}, // Latin-1 Supplement, Latin Extended-A and -B |
| 51 |
{0x01CD, 0x02AE}, // rest of Latin Extended-B and IPA Extensions |
| 52 |
{0x0363, 0x036F}, // combining Latin small letters |
| 53 |
{0x1D00, 0x1D22}, // Phonetic Extensions, small capitals |
| 54 |
{0x1D62, 0x1D65}, // subscript letters |
| 55 |
{0x1E00, 0x1EF9}, // Latin Extended Additional |
| 56 |
{0x2071, 0x2071}, // superscript i |
| 57 |
{0x2095, 0x209C}, // subscript letters |
| 58 |
{0x212A, 0x212B}, // KELVIN SIGN and ANGSTROM SIGN, which fold by case |
| 59 |
{0x2183, 0x2184}, // reversed roman numeral one hundred |
| 60 |
{0x2C62, 0x2C7F}, // Latin Extended-C |
| 61 |
{0xA78D, 0xA78D}, // Latin Extended-D |
| 62 |
{0xA7AA, 0xA7B2}, // more Latin Extended-D |
| 63 |
{0xA7C5, 0xA7C5}, |
| 64 |
{0xFF01, 0xFF61}, // fullwidth ASCII forms, and halfwidth ideographic full stop |
| 65 |
} |
| 66 |
|
| 67 |
// Walking the ranges costs a serial chain of comparisons per rune, which is |
| 68 |
// measurable at ingestion, so precompute a bitmap instead. |
| 69 |
var 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 - foldLo |
| 73 |
bits[i>>3] |= 1 << (i & 7) |
| 74 |
} |
| 75 |
} |
| 76 |
return |
| 77 |
}() |
| 78 |
|
| 79 |
// MayFoldToAscii reports whether case folding or normalization could turn r |
| 80 |
// into an ASCII character. |
| 81 |
func MayFoldToAscii(r rune) bool { |
| 82 |
i := uint32(r - foldLo) |
| 83 |
if i > foldHi-foldLo { |
| 84 |
return false |
| 85 |
} |
| 86 |
return foldableBits[i>>3]&(1<<(i&7)) != 0 |
| 87 |
} |
| 88 |
|
| 89 |
func checkAscii(bytes []byte) (bool, int) { |
| 90 |
i := 0 |
| 91 |
for ; i <= len(bytes)-8; i += 8 { |
| 92 |
if (overflow64 & *(*uint64)(unsafe.Pointer(&bytes[i]))) > 0 { |
| 93 |
return false, i |
| 94 |
} |
| 95 |
} |
| 96 |
for ; i <= len(bytes)-4; i += 4 { |
| 97 |
if (overflow32 & *(*uint32)(unsafe.Pointer(&bytes[i]))) > 0 { |
| 98 |
return false, i |
| 99 |
} |
| 100 |
} |
| 101 |
for ; i < len(bytes); i++ { |
| 102 |
if bytes[i] >= utf8.RuneSelf { |
| 103 |
return false, i |
| 104 |
} |
| 105 |
} |
| 106 |
return true, 0 |
| 107 |
} |
| 108 |
|
| 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 own |
| 111 |
// RuneError, so the result can undercount but never overcount, making it safe |
| 112 |
// as a capacity hint. |
| 113 |
func countRunes(bytes []byte) int { |
| 114 |
n, i := 0, 0 |
| 115 |
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 each |
| 118 |
// 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 n |
| 127 |
} |
| 128 |
|
| 129 |
// ToChars converts byte array into rune array |
| 130 |
func ToChars(bytes []byte) Chars { |
| 131 |
inBytes, bytesUntil := checkAscii(bytes) |
| 132 |
if inBytes { |
| 133 |
return Chars{slice: bytes, flags: flagInBytes} |
| 134 |
} |
| 135 |
|
| 136 |
runes := make([]rune, bytesUntil, bytesUntil+countRunes(bytes[bytesUntil:])) |
| 137 |
for i := range bytesUntil { |
| 138 |
runes[i] = rune(bytes[i]) |
| 139 |
} |
| 140 |
mayFold := false |
| 141 |
for i := bytesUntil; i < len(bytes); { |
| 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. |
| 144 |
// An ASCII rune never sets the fold bit either, so skip both calls. |
| 145 |
if b := bytes[i]; b < utf8.RuneSelf { |
| 146 |
runes = append(runes, rune(b)) |
| 147 |
i++ |
| 148 |
continue |
| 149 |
} |
| 150 |
r, sz := utf8.DecodeRune(bytes[i:]) |
| 151 |
i += sz |
| 152 |
mayFold = mayFold || MayFoldToAscii(r) |
| 153 |
runes = append(runes, r) |
| 154 |
} |
| 155 |
return runesToChars(runes, mayFold) |
| 156 |
} |
| 157 |
|
| 158 |
// RunesToChars adopts the caller's slice rather than copying it, so the caller |
| 159 |
// must not keep mutating it. See Runes for why. |
| 160 |
func RunesToChars(runes []rune) Chars { |
| 161 |
mayFold := false |
| 162 |
for _, r := range runes { |
| 163 |
if MayFoldToAscii(r) { |
| 164 |
mayFold = true |
| 165 |
break |
| 166 |
} |
| 167 |
} |
| 168 |
return runesToChars(runes, mayFold) |
| 169 |
} |
| 170 |
|
| 171 |
func runesToChars(runes []rune, mayFold bool) Chars { |
| 172 |
var flags uint8 |
| 173 |
if mayFold { |
| 174 |
flags = flagMayFold |
| 175 |
} |
| 176 |
return Chars{slice: *(*[]byte)(unsafe.Pointer(&runes)), flags: flags} |
| 177 |
} |
| 178 |
|
| 179 |
func (chars *Chars) IsBytes() bool { |
| 180 |
return chars.flags&flagInBytes != 0 |
| 181 |
} |
| 182 |
|
| 183 |
// MayFoldToAscii reports whether the text holds a rune that case folding or |
| 184 |
// normalization could turn into an ASCII character. When false, an ASCII |
| 185 |
// pattern character can only match the identical ASCII rune, which is what |
| 186 |
// lets the prefilter scan the rune array directly. |
| 187 |
func (chars *Chars) MayFoldToAscii() bool { |
| 188 |
return chars.flags&flagMayFold != 0 |
| 189 |
} |
| 190 |
|
| 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 change |
| 193 |
// the text without updating the cached fold bit, and the prefilter would then |
| 194 |
// reject items it should match. Copy before mutating. |
| 195 |
func (chars *Chars) Runes() []rune { |
| 196 |
return chars.optionalRunes() |
| 197 |
} |
| 198 |
|
| 199 |
func (chars *Chars) Bytes() []byte { |
| 200 |
return chars.slice |
| 201 |
} |
| 202 |
|
| 203 |
func (chars *Chars) NumLines(atMost int) (int, bool) { |
| 204 |
lines := 1 |
| 205 |
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, true |
| 212 |
} |
| 213 |
} |
| 214 |
return lines, false |
| 215 |
} |
| 216 |
|
| 217 |
for idx := 0; idx < len(chars.slice); idx++ { |
| 218 |
found := bytes.IndexByte(chars.slice[idx:], '\n') |
| 219 |
if found < 0 { |
| 220 |
break |
| 221 |
} |
| 222 |
|
| 223 |
idx += found |
| 224 |
lines++ |
| 225 |
if lines > atMost { |
| 226 |
return atMost, true |
| 227 |
} |
| 228 |
} |
| 229 |
return lines, false |
| 230 |
} |
| 231 |
|
| 232 |
func (chars *Chars) optionalRunes() []rune { |
| 233 |
if chars.IsBytes() { |
| 234 |
return nil |
| 235 |
} |
| 236 |
return *(*[]rune)(unsafe.Pointer(&chars.slice)) |
| 237 |
} |
| 238 |
|
| 239 |
func (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 |
} |
| 245 |
|
| 246 |
func (chars *Chars) Length() int { |
| 247 |
if runes := chars.optionalRunes(); runes != nil { |
| 248 |
return len(runes) |
| 249 |
} |
| 250 |
return len(chars.slice) |
| 251 |
} |
| 252 |
|
| 253 |
// String returns the string representation of a Chars object. |
| 254 |
func (chars *Chars) String() string { |
| 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) |
| 256 |
} |
| 257 |
|
| 258 |
// TrimLength returns the length after trimming leading and trailing whitespaces |
| 259 |
func (chars *Chars) TrimLength() uint16 { |
| 260 |
if chars.trimLengthKnown { |
| 261 |
return chars.trimLength |
| 262 |
} |
| 263 |
chars.trimLengthKnown = true |
| 264 |
var i int |
| 265 |
len := chars.Length() |
| 266 |
for i = len - 1; i >= 0; i-- { |
| 267 |
char := chars.Get(i) |
| 268 |
if !unicode.IsSpace(char) { |
| 269 |
break |
| 270 |
} |
| 271 |
} |
| 272 |
// Completely empty |
| 273 |
if i < 0 { |
| 274 |
return 0 |
| 275 |
} |
| 276 |
|
| 277 |
var j int |
| 278 |
for j = 0; j < len; j++ { |
| 279 |
char := chars.Get(j) |
| 280 |
if !unicode.IsSpace(char) { |
| 281 |
break |
| 282 |
} |
| 283 |
} |
| 284 |
chars.trimLength = AsUint16(i - j + 1) |
| 285 |
return chars.trimLength |
| 286 |
} |
| 287 |
|
| 288 |
func (chars *Chars) LeadingWhitespaces() int { |
| 289 |
whitespaces := 0 |
| 290 |
for i := 0; i < chars.Length(); i++ { |
| 291 |
char := chars.Get(i) |
| 292 |
if !unicode.IsSpace(char) { |
| 293 |
break |
| 294 |
} |
| 295 |
whitespaces++ |
| 296 |
} |
| 297 |
return whitespaces |
| 298 |
} |
| 299 |
|
| 300 |
func (chars *Chars) TrailingWhitespaces() int { |
| 301 |
whitespaces := 0 |
| 302 |
for i := chars.Length() - 1; i >= 0; i-- { |
| 303 |
char := chars.Get(i) |
| 304 |
if !unicode.IsSpace(char) { |
| 305 |
break |
| 306 |
} |
| 307 |
whitespaces++ |
| 308 |
} |
| 309 |
return whitespaces |
| 310 |
} |
| 311 |
|
| 312 |
func (chars *Chars) TrimTrailingWhitespaces(maxIndex int) { |
| 313 |
whitespaces := chars.TrailingWhitespaces() |
| 314 |
end := len(chars.slice) - whitespaces |
| 315 |
chars.slice = chars.slice[0:max(end, maxIndex)] |
| 316 |
} |
| 317 |
|
| 318 |
func (chars *Chars) TrimSuffix(runes []rune) { |
| 319 |
lastIdx := len(chars.slice) |
| 320 |
firstIdx := lastIdx - len(runes) |
| 321 |
if firstIdx < 0 { |
| 322 |
return |
| 323 |
} |
| 324 |
|
| 325 |
for i := firstIdx; i < lastIdx; i++ { |
| 326 |
char := chars.Get(i) |
| 327 |
if char != runes[i-firstIdx] { |
| 328 |
return |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
chars.slice = chars.slice[0:firstIdx] |
| 333 |
} |
| 334 |
|
| 335 |
func (chars *Chars) SliceRight(last int) { |
| 336 |
chars.slice = chars.slice[:last] |
| 337 |
} |
| 338 |
|
| 339 |
func (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 |
|
| 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. |
| 348 |
func (chars *Chars) ToRunes() []rune { |
| 349 |
if runes := chars.optionalRunes(); runes != nil { |
| 350 |
return runes |
| 351 |
} |
| 352 |
bytes := chars.slice |
| 353 |
runes := make([]rune, len(bytes)) |
| 354 |
for idx, b := range bytes { |
| 355 |
runes[idx] = rune(b) |
| 356 |
} |
| 357 |
return runes |
| 358 |
} |
| 359 |
|
| 360 |
func (chars *Chars) CopyRunes(dest []rune, from int) { |
| 361 |
if runes := chars.optionalRunes(); runes != nil { |
| 362 |
copy(dest, runes[from:]) |
| 363 |
return |
| 364 |
} |
| 365 |
for idx, b := range chars.slice[from:][:len(dest)] { |
| 366 |
dest[idx] = rune(b) |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
func (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...) |
| 376 |
} |
| 377 |
for _, r := range prefix { |
| 378 |
if MayFoldToAscii(r) { |
| 379 |
chars.flags |= flagMayFold |
| 380 |
break |
| 381 |
} |
| 382 |
} |
| 383 |
} |
| 384 |
|
| 385 |
func (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()) |
| 388 |
|
| 389 |
lines := [][]rune{} |
| 390 |
overflow := false |
| 391 |
if !multiLine { |
| 392 |
lines = append(lines, text) |
| 393 |
} else { |
| 394 |
from := 0 |
| 395 |
for off := range text { |
| 396 |
if text[off] == '\n' { |
| 397 |
lines = append(lines, text[from:off+1]) // Include '\n' |
| 398 |
from = off + 1 |
| 399 |
if len(lines) >= maxLines { |
| 400 |
break |
| 401 |
} |
| 402 |
} |
| 403 |
} |
| 404 |
|
| 405 |
var lastLine []rune |
| 406 |
if from < len(text) { |
| 407 |
lastLine = text[from:] |
| 408 |
} |
| 409 |
|
| 410 |
overflow = false |
| 411 |
if len(lines) >= maxLines { |
| 412 |
overflow = true |
| 413 |
} else { |
| 414 |
lines = append(lines, lastLine) |
| 415 |
} |
| 416 |
} |
| 417 |
|
| 418 |
// If wrapping is disabled, we're done |
| 419 |
if wrapCols == 0 { |
| 420 |
return lines, overflow |
| 421 |
} |
| 422 |
|
| 423 |
wrapped := [][]rune{} |
| 424 |
for _, line := range lines { |
| 425 |
// Remove trailing '\n' and remember if it was there |
| 426 |
newline := len(line) > 0 && line[len(line)-1] == '\n' |
| 427 |
if newline { |
| 428 |
line = line[:len(line)-1] |
| 429 |
} |
| 430 |
|
| 431 |
hasWrapSign := false |
| 432 |
for { |
| 433 |
cols := wrapCols |
| 434 |
if hasWrapSign { |
| 435 |
cols -= wrapSignWidth |
| 436 |
} |
| 437 |
_, overflowIdx := RunesWidth(line, 0, tabstop, cols) |
| 438 |
if overflowIdx >= 0 { |
| 439 |
// Might be a wide character |
| 440 |
if overflowIdx == 0 { |
| 441 |
overflowIdx = 1 |
| 442 |
} |
| 443 |
if wrapWord { |
| 444 |
// Find last space/tab at or before overflowIdx |
| 445 |
breakIdx := -1 |
| 446 |
for k := overflowIdx; k > 0; k-- { |
| 447 |
if line[k-1] == ' ' || line[k-1] == '\t' { |
| 448 |
breakIdx = k |
| 449 |
break |
| 450 |
} |
| 451 |
} |
| 452 |
if breakIdx > 0 { |
| 453 |
overflowIdx = breakIdx |
| 454 |
} |
| 455 |
} |
| 456 |
if len(wrapped) >= maxLines { |
| 457 |
return wrapped, true |
| 458 |
} |
| 459 |
wrapped = append(wrapped, line[:overflowIdx]) |
| 460 |
hasWrapSign = true |
| 461 |
line = line[overflowIdx:] |
| 462 |
continue |
| 463 |
} |
| 464 |
hasWrapSign = false |
| 465 |
|
| 466 |
// Restore trailing '\n' |
| 467 |
if newline { |
| 468 |
line = append(line, '\n') |
| 469 |
} |
| 470 |
|
| 471 |
if len(wrapped) >= maxLines { |
| 472 |
return wrapped, true |
| 473 |
} |
| 474 |
|
| 475 |
wrapped = append(wrapped, line) |
| 476 |
break |
| 477 |
} |
| 478 |
} |
| 479 |
|
| 480 |
return wrapped, overflow |
| 481 |
} |