Debian Codegraph @

src/util/chars_test.go

raw
1 package util
2
3 import (
4 "fmt"
5 "math/rand"
6 "strings"
7 "testing"
8 "unicode/utf8"
9 "unsafe"
10 )
11
12 func 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 }
22
23 func TestCountRunesRandom(t *testing.T) {
24 rng := rand.New(rand.NewSource(1))
25
26 // Exact on valid UTF-8
27 for trial := range 20000 {
28 var sb strings.Builder
29 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 }
41
42 // Never an overcount on arbitrary bytes, so the capacity hint never truncates
43 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 }
51
52 // ToChars must produce exactly what a []rune conversion produces, including
53 // one RuneError per invalid byte, and must size the rune slice exactly when
54 // the input is valid UTF-8.
55 func 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 }
72
73 for range 5000 {
74 var sb strings.Builder
75 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 }
85
86 // Invalid UTF-8: still correct, capacity may grow
87 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 path
91 check(buf, false)
92 }
93 }
94
95 func TestToCharsAscii(t *testing.T) {
96 chars := ToChars([]byte("foobar"))
97 if !chars.IsBytes() || chars.ToString() != "foobar" {
98 t.Error()
99 }
100 }
101
102 func TestCharsLength(t *testing.T) {
103 chars := ToChars([]byte("\tabc한글 "))
104 if chars.IsBytes() || chars.Length() != 8 || chars.TrimLength() != 5 {
105 t.Error()
106 }
107 }
108
109 func TestCharsToString(t *testing.T) {
110 text := "\tabc한글 "
111 chars := ToChars([]byte(text))
112 if chars.ToString() != text {
113 t.Error()
114 }
115 }
116
117 func 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 }
137
138 func 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 }
147
148 // No wrap
149 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)
152
153 // 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 size
161
162 // With wrap sign (3 + 1)
163 check(true, 100, 3, 1, 1, 8, false)
164
165 // With wrap sign (3 + 2)
166 check(true, 100, 3, 2, 1, 10, false)
167
168 // With wrap sign (3 + 2) and no multi-line
169 check(false, 100, 3, 2, 1, 13, false)
170 }
171
172 func TestCharsLinesWrapWord(t *testing.T) {
173 // "hello world foo bar" with width 12 should break at word boundaries
174 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 }
186
187 // No word boundary: a single long word falls back to character wrap
188 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 }
196
197 // wrapWord=false still character-wraps
198 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 }
207
208 // 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 on
211 // 32-bit builds too, where the header is 12 bytes and Chars is 20.
212 func TestCharsSize(t *testing.T) {
213 var slice []byte
214 // flags 1 + trimLengthKnown 1 + trimLength 2 + Index 4, no padding
215 want := unsafe.Sizeof(slice) + 8
216 if size := unsafe.Sizeof(Chars{}); size != want {
217 t.Errorf("unsafe.Sizeof(Chars{}) = %d, expected %d", size, want)
218 }
219 }
220
221 func TestMayFoldFlag(t *testing.T) {
222 for _, c := range []struct {
223 text string
224 fold bool
225 }{
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 }
237
238 // Prepend can introduce foldable runes
239 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 }
248
249 // Runes and ToRunes alias the text in rune mode, so a consumer that mutates
250 // what they return changes the text without updating the cached fold bit. This
251 // verifies the aliasing so the read-only contract on those methods is not
252 // silently dropped later.
253 func 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 }