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

1package util23import (4	"bytes"5	"fmt"6	"math/bits"7	"unicode"8	"unicode/utf8"9	"unsafe"10)1112const (13	overflow64 uint64 = 0x808080808080808014	overflow32 uint32 = 0x8080808015)1617const (18	flagInBytes uint8 = 1 << iota19	flagMayFold20)2122type Chars struct {23	slice []byte // or []rune24	// Only ever set, never cleared, so a reader racing a Prepend sees either25	// the old or the new value and both are safe. trimLength* is kept out26	// because TrimLength rewrites it.27	flags           uint828	trimLengthKnown bool29	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}3536// Rune ranges that case folding or normalization can turn into ASCII, derived37// from algo's normalization table and unicode.ToLower, then merged. They are a38// superset of the exact set, which TestMayFoldToAsciiIsSuperset in the algo39// package verifies. Grouped tightly on purpose: a wider merge would include40// 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 the42// 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}8889func 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}108109// countRunes counts the bytes that are not UTF-8 continuation bytes, which is110// 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}128129// ToChars converts byte array into rune array130func ToChars(bytes []byte) Chars {131	inBytes, bytesUntil := checkAscii(bytes)132	if inBytes {133		return Chars{slice: bytes, flags: flagInBytes}134	}135136	runes := make([]rune, bytesUntil, bytesUntil+countRunes(bytes[bytesUntil:]))137	for i := range bytesUntil {138		runes[i] = rune(bytes[i])139	}140	mayFold := false141	for i := bytesUntil; i < len(bytes); {142		// utf8.DecodeRune has an ASCII path of its own, but it is too complex143		// 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			continue149		}150		r, sz := utf8.DecodeRune(bytes[i:])151		i += sz152		mayFold = mayFold || MayFoldToAscii(r)153		runes = append(runes, r)154	}155	return runesToChars(runes, mayFold)156}157158// RunesToChars adopts the caller's slice rather than copying it, so the caller159// must not keep mutating it. See Runes for why.160func RunesToChars(runes []rune) Chars {161	mayFold := false162	for _, r := range runes {163		if MayFoldToAscii(r) {164			mayFold = true165			break166		}167	}168	return runesToChars(runes, mayFold)169}170171func 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}178179func (chars *Chars) IsBytes() bool {180	return chars.flags&flagInBytes != 0181}182183// MayFoldToAscii reports whether the text holds a rune that case folding or184// 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}190191// Runes returns the underlying rune slice, or nil if the text is kept as192// 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.195func (chars *Chars) Runes() []rune {196	return chars.optionalRunes()197}198199func (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 {233	if chars.IsBytes() {234		return nil235	}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 {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}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}345346// ToRunes returns the text as runes. In rune mode the result aliases the text347// and must not be mutated, see Runes. In byte mode it is a fresh slice.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...)376	}377	for _, r := range prefix {378		if MayFoldToAscii(r) {379			chars.flags |= flagMayFold380			break381		}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}