Skip to content
Myr

chars_test.go

This file

Path

src/util/chars_test.go

273 lines · 8.2 KiB · Go

Last changed by

Clean up comments and testsJunegunn Choibefore adoption2885df8

History of this file

Take it

1package util23import (4	"fmt"5	"math/rand"6	"strings"7	"testing"8	"unicode/utf8"9	"unsafe"10)1112func TestCountRunes(t *testing.T) {13	for _, str := range []string{14		"", "a", "abc", "한글", "🎉🎉", "\tabc한글  ",15		strings.Repeat("漢字", 50), strings.Repeat("a", 33) + "é",16	} {17		if got, exp := countRunes([]byte(str)), utf8.RuneCountInString(str); got != exp {18			t.Errorf("countRunes(%q) = %d, expected %d", str, got, exp)19		}20	}21}2223func TestCountRunesRandom(t *testing.T) {24	rng := rand.New(rand.NewSource(1))2526	// Exact on valid UTF-827	for trial := range 20000 {28		var sb strings.Builder29		for range rng.Intn(20) {30			r := rune(rng.Intn(utf8.MaxRune + 1))31			for r >= 0xD800 && r <= 0xDFFF {32				r = rune(rng.Intn(utf8.MaxRune + 1))33			}34			sb.WriteRune(r)35		}36		str := sb.String()37		if got, exp := countRunes([]byte(str)), utf8.RuneCountInString(str); got != exp {38			t.Fatalf("trial %d: countRunes(%q) = %d, expected %d", trial, str, got, exp)39		}40	}4142	// Never an overcount on arbitrary bytes, so the capacity hint never truncates43	for trial := range 20000 {44		buf := make([]byte, rng.Intn(40))45		rng.Read(buf)46		if got, exp := countRunes(buf), utf8.RuneCount(buf); got > exp {47			t.Fatalf("trial %d: countRunes(%x) = %d, overcounts %d", trial, buf, got, exp)48		}49	}50}5152// ToChars must produce exactly what a []rune conversion produces, including53// one RuneError per invalid byte, and must size the rune slice exactly when54// the input is valid UTF-8.55func TestToCharsIntegrity(t *testing.T) {56	rng := rand.New(rand.NewSource(2))57	check := func(buf []byte, exactCap bool) {58		chars := ToChars(buf)59		exp := []rune(string(buf))60		if chars.Length() != len(exp) {61			t.Fatalf("ToChars(%x).Length() = %d, expected %d", buf, chars.Length(), len(exp))62		}63		for i, r := range exp {64			if chars.Get(i) != r {65				t.Fatalf("ToChars(%x).Get(%d) = %q, expected %q", buf, i, chars.Get(i), r)66			}67		}68		if runes := chars.optionalRunes(); runes != nil && exactCap && cap(runes) != len(exp) {69			t.Fatalf("ToChars(%x) cap = %d, expected %d", buf, cap(runes), len(exp))70		}71	}7273	for range 5000 {74		var sb strings.Builder75		sb.WriteString("ascii")76		for range 1 + rng.Intn(10) {77			r := rune(0x80 + rng.Intn(utf8.MaxRune-0x80))78			for r >= 0xD800 && r <= 0xDFFF {79				r = rune(0x80 + rng.Intn(utf8.MaxRune-0x80))80			}81			sb.WriteRune(r)82		}83		check([]byte(sb.String()), true)84	}8586	// Invalid UTF-8: still correct, capacity may grow87	for range 5000 {88		buf := make([]byte, 1+rng.Intn(40))89		rng.Read(buf)90		buf[rng.Intn(len(buf))] |= 0x80 // force the rune path91		check(buf, false)92	}93}9495func TestToCharsAscii(t *testing.T) {96	chars := ToChars([]byte("foobar"))97	if !chars.IsBytes() || chars.ToString() != "foobar" {98		t.Error()99	}100}101102func TestCharsLength(t *testing.T) {103	chars := ToChars([]byte("\tabc한글  "))104	if chars.IsBytes() || chars.Length() != 8 || chars.TrimLength() != 5 {105		t.Error()106	}107}108109func TestCharsToString(t *testing.T) {110	text := "\tabc한글  "111	chars := ToChars([]byte(text))112	if chars.ToString() != text {113		t.Error()114	}115}116117func TestTrimLength(t *testing.T) {118	check := func(str string, exp uint16) {119		chars := ToChars([]byte(str))120		trimmed := chars.TrimLength()121		if trimmed != exp {122			t.Errorf("Invalid TrimLength result for '%s': %d (expected %d)",123				str, trimmed, exp)124		}125	}126	check("hello", 5)127	check("hello ", 5)128	check("hello  ", 5)129	check(" hello", 5)130	check("  hello", 5)131	check(" hello ", 5)132	check("  hello  ", 5)133	check("h   o", 5)134	check("  h   o  ", 5)135	check("         ", 0)136}137138func TestCharsLines(t *testing.T) {139	chars := ToChars([]byte("abcdef\n가나다\n\tdef"))140	check := func(multiLine bool, maxLines int, wrapCols int, wrapSignWidth int, tabstop int, expectedNumLines int, expectedOverflow bool) {141		lines, overflow := chars.Lines(multiLine, maxLines, wrapCols, wrapSignWidth, tabstop, false)142		fmt.Println(lines, overflow)143		if len(lines) != expectedNumLines || overflow != expectedOverflow {144			t.Errorf("Invalid result: %d %v (expected %d %v)", len(lines), overflow, expectedNumLines, expectedOverflow)145		}146	}147148	// No wrap149	check(true, 1, 0, 0, 8, 1, true)150	check(true, 2, 0, 0, 8, 2, true)151	check(true, 3, 0, 0, 8, 3, false)152153	// Wrap (2)154	check(true, 4, 2, 0, 8, 4, true)155	check(true, 5, 2, 0, 8, 5, true)156	check(true, 6, 2, 0, 8, 6, true)157	check(true, 7, 2, 0, 8, 7, true)158	check(true, 8, 2, 0, 8, 8, true)159	check(true, 9, 2, 0, 8, 9, false)160	check(true, 9, 2, 0, 1, 8, false) // Smaller tab size161162	// With wrap sign (3 + 1)163	check(true, 100, 3, 1, 1, 8, false)164165	// With wrap sign (3 + 2)166	check(true, 100, 3, 2, 1, 10, false)167168	// With wrap sign (3 + 2) and no multi-line169	check(false, 100, 3, 2, 1, 13, false)170}171172func TestCharsLinesWrapWord(t *testing.T) {173	// "hello world foo bar" with width 12 should break at word boundaries174	chars := ToChars([]byte("hello world foo bar"))175	lines, overflow := chars.Lines(false, 100, 12, 0, 8, true)176	// "hello world " (12) | "foo bar" (7)177	if len(lines) != 2 || overflow {178		t.Errorf("Expected 2 lines, got %d (overflow: %v): %v", len(lines), overflow, lines)179	}180	if string(lines[0]) != "hello world " {181		t.Errorf("Expected first line 'hello world ', got %q", string(lines[0]))182	}183	if string(lines[1]) != "foo bar" {184		t.Errorf("Expected second line 'foo bar', got %q", string(lines[1]))185	}186187	// No word boundary: a single long word falls back to character wrap188	chars2 := ToChars([]byte("abcdefghijklmnop"))189	lines2, _ := chars2.Lines(false, 100, 10, 0, 8, true)190	if len(lines2) != 2 {191		t.Errorf("Expected 2 lines for long word, got %d: %v", len(lines2), lines2)192	}193	if string(lines2[0]) != "abcdefghij" {194		t.Errorf("Expected first line 'abcdefghij', got %q", string(lines2[0]))195	}196197	// wrapWord=false still character-wraps198	chars3 := ToChars([]byte("hello world"))199	lines3, _ := chars3.Lines(false, 100, 8, 0, 8, false)200	if len(lines3) != 2 {201		t.Errorf("Expected 2 lines with wrapWord=false, got %d: %v", len(lines3), lines3)202	}203	if string(lines3[0]) != "hello wo" {204		t.Errorf("Expected first line 'hello wo', got %q", string(lines3[0]))205	}206}207208// Chars is one per input line, so its size matters. It has no spare padding,209// which is why new state goes in the flags byte rather than a field.210// Derive the expectation from the slice header so the invariant holds on211// 32-bit builds too, where the header is 12 bytes and Chars is 20.212func TestCharsSize(t *testing.T) {213	var slice []byte214	// flags 1 + trimLengthKnown 1 + trimLength 2 + Index 4, no padding215	want := unsafe.Sizeof(slice) + 8216	if size := unsafe.Sizeof(Chars{}); size != want {217		t.Errorf("unsafe.Sizeof(Chars{}) = %d, expected %d", size, want)218	}219}220221func TestMayFoldFlag(t *testing.T) {222	for _, c := range []struct {223		text string224		fold bool225	}{226		{"한글/src", false}, {"漢字", false}, {"мир", false}, {"🎉", false},227		{"café", true}, {"Müller", true}, {"Å", true}, {"full", true},228	} {229		chars := ToChars([]byte(c.text))230		if chars.MayFoldToAscii() != c.fold {231			t.Errorf("ToChars(%q).MayFoldToAscii() = %v, expected %v", c.text, chars.MayFoldToAscii(), c.fold)232		}233		if runes := RunesToChars([]rune(c.text)); runes.MayFoldToAscii() != c.fold {234			t.Errorf("RunesToChars(%q).MayFoldToAscii() = %v, expected %v", c.text, runes.MayFoldToAscii(), c.fold)235		}236	}237238	// Prepend can introduce foldable runes239	chars := ToChars([]byte("한글"))240	if chars.MayFoldToAscii() {241		t.Fatal("baseline should not be foldable")242	}243	chars.Prepend("é")244	if !chars.MayFoldToAscii() {245		t.Error("Prepend of a foldable prefix must set the flag")246	}247}248249// Runes and ToRunes alias the text in rune mode, so a consumer that mutates250// what they return changes the text without updating the cached fold bit. This251// verifies the aliasing so the read-only contract on those methods is not252// silently dropped later.253func TestRuneSlicesAliasTheText(t *testing.T) {254	chars := ToChars([]byte("한글abc"))255	runes := chars.Runes()256	if runes == nil {257		t.Fatal("expected rune mode")258	}259	if &runes[0] != &chars.ToRunes()[0] {260		t.Error("Runes and ToRunes should return the same backing array")261	}262	if chars.MayFoldToAscii() {263		t.Fatal("baseline should not be foldable")264	}265	// Demonstrates why callers must copy: the flag does not follow the text.266	runes[0] = 'e'267	if chars.MayFoldToAscii() {268		t.Error("flag unexpectedly updated")269	}270	if got := chars.ToString(); got != "e글abc" {271		t.Errorf("expected the write to reach the text, got %q", got)272	}273}