Debian Codegraph @

shiny/text/text_test.go

raw symbols SCIP
1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package text
6
7 import (
8 "bytes"
9 "fmt"
10 "image"
11 "io"
12 "math/rand"
13 "reflect"
14 "sort"
15 "strings"
16 "testing"
17 "unicode/utf8"
18
19 "golang.org/x/image/font"
20 "golang.org/x/image/math/fixed"
21 )
22
23 func readAllText(dst []byte, f *Frame) []byte {
24 for p := f.FirstParagraph(); p != nil; p = p.Next(f) {
25 for l := p.FirstLine(f); l != nil; l = l.Next(f) {
26 for b := l.FirstBox(f); b != nil; b = b.Next(f) {
27 dst = append(dst, b.Text(f)...)
28 }
29 }
30 }
31 return dst
32 }
33
34 func readAllRunes(dst []rune, rr io.RuneReader) ([]rune, error) {
35 for {
36 r, size, err := rr.ReadRune()
37 if err == io.EOF {
38 return dst, nil
39 }
40 if err != nil {
41 return nil, err
42 }
43
44 // Check that r and size are consistent.
45 if wantSize := utf8.RuneLen(r); size == wantSize {
46 // OK.
47 } else if r == utf8.RuneError && size == 1 {
48 // Also OK; one byte of invalid UTF-8 was replaced by '\ufffd'.
49 } else {
50 return nil, fmt.Errorf("rune %#x: got size %d, want %d", r, size, wantSize)
51 }
52
53 dst = append(dst, r)
54 }
55 }
56
57 func runesEqual(xs, ys []rune) bool {
58 if len(xs) != len(ys) {
59 return false
60 }
61 for i := range xs {
62 if xs[i] != ys[i] {
63 return false
64 }
65 }
66 return true
67 }
68
69 func allASCII(rs []rune) bool {
70 for _, r := range rs {
71 if r >= 128 {
72 return false
73 }
74 }
75 return true
76 }
77
78 func runesLen(rs []rune) (n int) {
79 for _, r := range rs {
80 n += utf8.RuneLen(r)
81 }
82 return n
83 }
84
85 // insert inserts the insert argument into buf at the given offset.
86 //
87 // cap(buf) must be >= len(buf) + len(insert).
88 func insert(buf, insert []byte, offset int) []byte {
89 n := len(insert)
90 buf = buf[:len(buf)+n]
91 copy(buf[offset+n:], buf[offset:])
92 copy(buf[offset:offset+n], insert)
93 return buf
94 }
95
96 func rngIntPair(rng *rand.Rand, n int) (x, y int) {
97 x = rng.Intn(n)
98 y = rng.Intn(n)
99 if x > y {
100 x, y = y, x
101 }
102 return x, y
103 }
104
105 // toyFace implements the font.Face interface by measuring every rune's width
106 // as 1 pixel.
107 type toyFace struct{}
108
109 func (toyFace) Close() error {
110 return nil
111 }
112
113 func (toyFace) Glyph(dot fixed.Point26_6, r rune) (image.Rectangle, image.Image, image.Point, fixed.Int26_6, bool) {
114 panic("unimplemented")
115 }
116
117 func (toyFace) GlyphBounds(r rune) (fixed.Rectangle26_6, fixed.Int26_6, bool) {
118 panic("unimplemented")
119 }
120
121 func (toyFace) GlyphAdvance(r rune) (fixed.Int26_6, bool) {
122 return fixed.I(1), true
123 }
124
125 func (toyFace) Kern(r0, r1 rune) fixed.Int26_6 {
126 return 0
127 }
128
129 func (toyFace) Metrics() font.Metrics {
130 return font.Metrics{
131 Ascent: fixed.I(2),
132 Descent: fixed.I(1),
133 }
134 }
135
136 const toyFaceLineHeight = 3
137
138 // iRobot is some text that contains both ASCII and non-ASCII runes.
139 const iRobot = "\"I, Robot\" in Russian is \"Я, робот\".\nIt's about robots.\n"
140
141 var (
142 iRobotBytes = []byte(iRobot)
143 iRobotRunes = []rune(iRobot)
144 )
145
146 func iRobotFrame(maxWidth int) *Frame {
147 f := new(Frame)
148 f.SetFace(toyFace{})
149 f.SetMaxWidth(fixed.I(maxWidth))
150 c := f.NewCaret()
151 c.WriteString(iRobot)
152 c.Close()
153 return f
154 }
155
156 func TestZeroFrame(t *testing.T) {
157 f := new(Frame)
158 if err := checkInvariants(f); err != nil {
159 t.Fatal(err)
160 }
161 }
162
163 func TestSeek(t *testing.T) {
164 f := iRobotFrame(10)
165 c := f.NewCaret()
166 defer c.Close()
167 rng := rand.New(rand.NewSource(1))
168 seen := [1 + len(iRobot)]bool{}
169 for i := 0; i < 10*len(iRobot); i++ {
170 wantPos := int64(rng.Intn(len(iRobot) + 1))
171 gotPos, err := c.Seek(wantPos, SeekSet)
172 if err != nil {
173 t.Fatalf("i=%d: Seek: %v", i, err)
174 }
175 if gotPos != wantPos {
176 t.Fatalf("i=%d: Seek: got %d, want %d", i, gotPos, wantPos)
177 }
178 seen[gotPos] = true
179 if err := checkInvariants(f); err != nil {
180 t.Fatalf("i=%d: %v", i, err)
181 }
182
183 gotByte, gotErr := c.ReadByte()
184 wantByte, wantErr := byte(0), io.EOF
185 if gotPos < int64(len(iRobot)) {
186 wantByte, wantErr = iRobot[gotPos], nil
187 }
188 if gotByte != wantByte || gotErr != wantErr {
189 t.Fatalf("i=%d: ReadByte: got %d, %v, want %d, %v", i, gotByte, gotErr, wantByte, wantErr)
190 }
191 }
192 for i, s := range seen {
193 if !s {
194 t.Errorf("randomly generated positions weren't exhaustive: position %d / %d not seen", i, len(iRobot))
195 }
196 }
197 }
198
199 func testRead(f *Frame, want string) error {
200 c := f.NewCaret()
201 defer c.Close()
202 asBytes, err := io.ReadAll(c)
203 if err != nil {
204 return fmt.Errorf("ReadAll: %v", err)
205 }
206 if got := string(asBytes); got != want {
207 return fmt.Errorf("Read\ngot: %q\nwant: %q", got, want)
208 }
209 return nil
210 }
211
212 func TestRead(t *testing.T) {
213 f := iRobotFrame(10)
214 if err := checkInvariants(f); err != nil {
215 t.Fatal(err)
216 }
217 if err := testRead(f, iRobot); err != nil {
218 t.Fatal(err)
219 }
220 }
221
222 func TestReadByte(t *testing.T) {
223 f := iRobotFrame(10)
224 c := f.NewCaret()
225 defer c.Close()
226 got, want := []byte(nil), []byte(iRobot)
227 for {
228 x, err := c.ReadByte()
229 if err == io.EOF {
230 break
231 }
232 if err != nil {
233 t.Fatalf("ReadByte: %v", err)
234 }
235 if err := checkInvariants(f); err != nil {
236 t.Fatal(err)
237 }
238 got = append(got, x)
239 }
240 if err := checkInvariants(f); err != nil {
241 t.Fatal(err)
242 }
243 if !reflect.DeepEqual(got, want) {
244 t.Fatalf("\ngot: %v\nwant: %v", got, want)
245 }
246 }
247
248 func TestReadRune(t *testing.T) {
249 f := iRobotFrame(10)
250 c := f.NewCaret()
251 defer c.Close()
252 got, want := []rune(nil), []rune(iRobot)
253 for {
254 r, _, err := c.ReadRune()
255 if err == io.EOF {
256 break
257 }
258 if err != nil {
259 t.Fatalf("ReadRune: %v", err)
260 }
261 if err := checkInvariants(f); err != nil {
262 t.Fatal(err)
263 }
264 got = append(got, r)
265 }
266 if err := checkInvariants(f); err != nil {
267 t.Fatal(err)
268 }
269 if !reflect.DeepEqual(got, want) {
270 t.Fatalf("\ngot: %v\nwant: %v", got, want)
271 }
272 }
273
274 func TestWrite(t *testing.T) {
275 f := new(Frame)
276 c := f.NewCaret()
277 c.Write([]byte{0xff, 0xfe, 0xfd})
278 c.WriteByte(0x80)
279 c.WriteRune('\U0001f4a9')
280 c.WriteString("abc\x00")
281 c.Close()
282 if err := checkInvariants(f); err != nil {
283 t.Fatal(err)
284 }
285 got := f.text[:f.len]
286 want := []byte{0xff, 0xfe, 0xfd, 0x80, 0xf0, 0x9f, 0x92, 0xa9, 0x61, 0x62, 0x63, 0x00}
287 if !bytes.Equal(got, want) {
288 t.Fatalf("\ngot % x\nwant % x", got, want)
289 }
290 }
291
292 func TestManyWrites(t *testing.T) {
293 f := new(Frame)
294 f.SetFace(toyFace{})
295 f.SetMaxWidth(fixed.I(10))
296 c := f.NewCaret()
297 defer c.Close()
298
299 const n, abc16 = 100, "abcdefghijkl\n "
300 rng := rand.New(rand.NewSource(1))
301 buf := make([]byte, n)
302 for i := range buf {
303 buf[i] = abc16[rng.Intn(len(abc16))]
304 }
305
306 for i := 0; i < 100; i++ {
307 x, y := rngIntPair(rng, len(buf)+1)
308 c.Write(buf[x:y])
309 if err := checkInvariants(f); err != nil {
310 t.Fatalf("i=%d: %v", i, err)
311 }
312 }
313 }
314
315 func TestRandomAccessWrite(t *testing.T) {
316 f := new(Frame)
317 c := f.NewCaret()
318 defer c.Close()
319
320 rng := rand.New(rand.NewSource(1))
321 gotBuf := make([]byte, 0, 10000)
322 want := make([]byte, 0, 10000)
323 buf := make([]byte, 10)
324 x := byte(0)
325 for i := 0; i < 100; i++ {
326 n := rng.Intn(len(buf) + 1)
327 for j := range buf[:n] {
328 buf[j] = x
329 x++
330 }
331 offset := rng.Intn(len(want) + 1)
332
333 // Insert buf[:n] into the Frame at the given offset.
334 c.Seek(int64(offset), SeekSet)
335 c.Write(buf[:n])
336 if err := checkInvariants(f); err != nil {
337 t.Fatalf("i=%d: %v", i, err)
338 }
339
340 // Insert buf[:n] into want at the given offset.
341 want = insert(want, buf[:n], offset)
342
343 if got := readAllText(gotBuf[:0], f); !bytes.Equal(got, want) {
344 t.Errorf("i=%d:\ngot % x\nwant % x", i, got, want)
345 }
346 }
347 }
348
349 func TestWriteAtStart(t *testing.T) {
350 f := iRobotFrame(10)
351 c := f.NewCaret()
352 defer c.Close()
353
354 prefix := "The Truth of the Matter\n(insofaras): "
355 gotBuf := make([]byte, len(prefix)+len(iRobot))
356 want := make([]byte, len(iRobot), len(prefix)+len(iRobot))
357 copy(want, iRobot)
358
359 for i := 0; i < len(prefix); i++ {
360 x := prefix[len(prefix)-1-i]
361
362 c.Seek(0, SeekSet)
363 c.WriteByte(x)
364 if err := checkInvariants(f); err != nil {
365 t.Fatalf("i=%d: %v", i, err)
366 }
367
368 want = want[:len(want)+1]
369 copy(want[1:], want)
370 want[0] = x
371
372 if got := readAllText(gotBuf[:0], f); !bytes.Equal(got, want) {
373 t.Fatalf("i=%d:\ngot % x\nwant % x", i, got, want)
374 }
375 }
376
377 if nl, nb := f.nUsedLines(), f.nUsedBoxes(); nl == nb {
378 t.Fatalf("before compaction: using %d lines and %d boxes, should be not equal", nl, nb)
379 }
380 f.compactText()
381 if nl, nb := f.nUsedLines(), f.nUsedBoxes(); nl != nb {
382 t.Fatalf("after compaction: using %d lines and %d boxes, should be equal", nl, nb)
383 }
384 }
385
386 func TestLineCount(t *testing.T) {
387 f := iRobotFrame(0)
388
389 testCases := []struct {
390 desc string
391 maxWidth int
392 wantLines []string
393 wantLineCounts []int
394 }{{
395 desc: "infinite maxWidth",
396 maxWidth: 0,
397 wantLines: []string{
398 `"I, Robot" in Russian is "Я, робот".`,
399 `It's about robots.`,
400 ``,
401 },
402 wantLineCounts: []int{1, 1, 1},
403 }, {
404 desc: "finite maxWidth",
405 maxWidth: 10,
406 wantLines: []string{
407 `"I, Robot"`,
408 `in Russian`,
409 `is "Я,`,
410 `робот".`,
411 `It's about`,
412 `robots.`,
413 ``,
414 },
415 wantLineCounts: []int{4, 2, 1},
416 }}
417 for _, tc := range testCases {
418 f.SetMaxWidth(fixed.I(tc.maxWidth))
419 lines, lineCounts := []string{}, []int{}
420 for p := f.FirstParagraph(); p != nil; p = p.Next(f) {
421 for l := p.FirstLine(f); l != nil; l = l.Next(f) {
422 var line []byte
423 for b := l.FirstBox(f); b != nil; b = b.Next(f) {
424 line = append(line, b.TrimmedText(f)...)
425 }
426 lines = append(lines, string(line))
427 }
428 lineCounts = append(lineCounts, p.LineCount(f))
429 }
430
431 if got, want := f.LineCount(), len(tc.wantLines); got != want {
432 t.Errorf("%s: LineCount: got %d, want %d", tc.desc, got, want)
433 continue
434 }
435 if !reflect.DeepEqual(lines, tc.wantLines) {
436 t.Errorf("%s: lines: got %q, want %q", tc.desc, lines, tc.wantLines)
437 continue
438 }
439 if got, want := f.ParagraphCount(), len(tc.wantLineCounts); got != want {
440 t.Errorf("%s: ParagraphCount: got %d, want %d", tc.desc, got, want)
441 continue
442 }
443 if !reflect.DeepEqual(lineCounts, tc.wantLineCounts) {
444 t.Errorf("%s: lineCounts: got %d, want %d", tc.desc, lineCounts, tc.wantLineCounts)
445 continue
446 }
447 if got, want := f.Height(), toyFaceLineHeight*len(tc.wantLines); got != want {
448 t.Errorf("%s: Height: got %d, want %d", tc.desc, got, want)
449 continue
450 }
451 }
452 }
453
454 func TestSetMaxWidth(t *testing.T) {
455 f := new(Frame)
456 f.SetFace(toyFace{})
457 want := ""
458 rng := rand.New(rand.NewSource(1))
459 for i := 0; i < 100; i++ {
460 if i%20 == 5 {
461 c := f.NewCaret()
462 c.WriteString(iRobot)
463 c.Close()
464 want += iRobot
465 }
466 maxWidth := rng.Intn(20)
467 f.SetMaxWidth(fixed.I(maxWidth))
468 if err := checkInvariants(f); err != nil {
469 t.Fatalf("i=%d: %v", i, err)
470 }
471 if err := testRead(f, want); err != nil {
472 t.Fatalf("i=%d: %v", i, err)
473 }
474 if want == "" {
475 continue
476 }
477 // Check that a zero (which means infinite) maxWidth corresponds to one
478 // Line per Paragraph.
479 np, nl := f.nUsedParagraphs(), f.nUsedLines()
480 if maxWidth == 0 {
481 if np != nl {
482 t.Fatalf("i=%d: maxWidth=0: got %d paragraphs and %d lines, should be equal", i, np, nl)
483 }
484 } else {
485 if np == nl {
486 t.Fatalf("i=%d: maxWidth=%d: got %d paragraphs and %d lines, should be unequal", i, maxWidth, np, nl)
487 }
488 }
489 }
490 }
491
492 func TestReadRuneAcrossBoxes(t *testing.T) {
493 rng := rand.New(rand.NewSource(1))
494 for i := 0; i < 6; i++ {
495 // text is a mixture of valid and invalid UTF-8.
496 text := "ab_\u0100\u0101_\ufffd中文_\xff\xffñ\xff_z_\U0001f4a9_\U0001f600" +
497 strings.Repeat("\xff", i)
498
499 wantBytes := []byte(text)
500 wantRunes := []rune(text)
501 gotBytesBuf := make([]byte, 0, len(text))
502 gotRunesBuf := make([]rune, 0, len(text))
503
504 for j := 0; j < 100; j++ {
505 f := new(Frame)
506
507 {
508 c := f.NewCaret()
509 c.WriteString(text)
510 // Split the sole Line into multiple Boxes at random byte offsets,
511 // possibly cutting across multi-byte UTF-8 encoded runes.
512 for {
513 if rng.Intn(8) == 0 {
514 break
515 }
516 c.Seek(int64(rng.Intn(len(text)+1)), SeekSet)
517 c.splitBox(false)
518 }
519 c.Close()
520
521 if err := checkInvariants(f); err != nil {
522 t.Fatalf("i=%d, j=%d: %v", i, j, err)
523 }
524 if gotBytes := readAllText(gotBytesBuf[:0], f); !bytes.Equal(gotBytes, wantBytes) {
525 t.Fatalf("i=%d, j=%d: bytes\ngot % x\nwant % x", i, j, gotBytes, wantBytes)
526 }
527 }
528
529 // Test lineReader.ReadRune.
530 {
531 p := f.firstP
532 l := f.paragraphs[p].firstL
533 b := f.lines[l].firstB
534 lr := f.lineReader(b, f.boxes[b].i)
535 gotRunes, err := readAllRunes(gotRunesBuf[:0], lr)
536 if err != nil {
537 t.Fatalf("i=%d, j=%d: lineReader readAllRunes: %v", i, j, err)
538 }
539 if !runesEqual(gotRunes, wantRunes) {
540 t.Fatalf("i=%d, j=%d: lineReader readAllRunes:\ngot %#x\nwant %#x",
541 i, j, gotRunes, wantRunes)
542 }
543 }
544
545 // Test Caret.ReadRune.
546 {
547 c := f.NewCaret()
548 gotRunes, err := readAllRunes(gotRunesBuf[:0], c)
549 c.Close()
550 if err != nil {
551 t.Fatalf("i=%d, j=%d: Caret readAllRunes: %v", i, j, err)
552 }
553 if !runesEqual(gotRunes, wantRunes) {
554 t.Fatalf("i=%d, j=%d: Caret readAllRunes:\ngot %#x\nwant %#x",
555 i, j, gotRunes, wantRunes)
556 }
557 }
558 }
559 }
560 }
561
562 func TestDelete(t *testing.T) {
563 rng := rand.New(rand.NewSource(1))
564 gotBytesBuf := make([]byte, 0, len(iRobot))
565 wantBytesBuf := make([]byte, 0, len(iRobot))
566
567 for i := 0; i < 100; i++ {
568 f := iRobotFrame(rng.Intn(len(iRobot) + 1))
569 c := f.NewCaret()
570 defer c.Close()
571 wantBytes := append(wantBytesBuf[:0], iRobot...)
572 for j := 0; j < 8; j++ {
573 // Delete the text in the byte range [x, y).
574 x, y := rngIntPair(rng, len(wantBytes)+1)
575 got, want := 0, y-x
576 if rng.Intn(2) == 0 {
577 c.Seek(int64(x), SeekSet)
578 got = c.Delete(Forwards, want)
579 } else {
580 c.Seek(int64(y), SeekSet)
581 got = c.Delete(Backwards, want)
582 }
583 if err := checkInvariants(f); err != nil {
584 t.Fatalf("i=%d, j=%d, x=%d, y=%d: %v", i, j, x, y, err)
585 }
586 if got != want {
587 t.Fatalf("i=%d, j=%d, x=%d, y=%d: Delete: got %d, want %d", i, j, x, y, got, want)
588 }
589
590 gotBytes := readAllText(gotBytesBuf[:0], f)
591 wantBytes = append(wantBytes[:x], wantBytes[y:]...)
592 if !bytes.Equal(gotBytes, wantBytes) {
593 t.Fatalf("i=%d, j=%d, x=%d, y=%d:\ngot %q\nwant %q", i, j, x, y, gotBytes, wantBytes)
594 }
595 }
596 }
597 }
598
599 func TestDeleteRunes(t *testing.T) {
600 rng := rand.New(rand.NewSource(1))
601 gotBytesBuf := make([]byte, 0, len(iRobot))
602 wantRunesBuf := make([]rune, 0, len(iRobot))
603 wantBytesBuf := make([]byte, 0, len(iRobot))
604
605 for i := 0; i < 100; i++ {
606 f := iRobotFrame(rng.Intn(len(iRobot) + 1))
607 c := f.NewCaret()
608 defer c.Close()
609 wantRunes := append(wantRunesBuf[:0], iRobotRunes...)
610 wantBytes := append(wantBytesBuf[:0], iRobot...)
611 for j := 0; j < 8; j++ {
612 xR, yR := rngIntPair(rng, len(wantRunes)+1)
613 xB := runesLen(wantRunes[:xR])
614 yB := runesLen(wantRunes[:yR])
615
616 // Delete the text in the byte range [xB, yB).
617 gotR, gotB, wantR, wantB := 0, 0, yR-xR, yB-xB
618 if rng.Intn(2) == 0 {
619 c.Seek(int64(xB), SeekSet)
620 gotR, gotB = c.DeleteRunes(Forwards, wantR)
621 } else {
622 c.Seek(int64(yB), SeekSet)
623 gotR, gotB = c.DeleteRunes(Backwards, wantR)
624 }
625 if err := checkInvariants(f); err != nil {
626 t.Fatalf("i=%d, j=%d, xR=%d, xB=%d, yR=%d, yB=%d: %v", i, j, xR, xB, yR, yB, err)
627 }
628 if gotR != wantR || gotB != wantB {
629 t.Fatalf("i=%d, j=%d, xR=%d, xB=%d, yR=%d, yB=%d: Delete: got %d runes, %d bytes, want %d, %d",
630 i, j, xR, xB, yR, yB, gotR, gotB, wantR, wantB)
631 }
632
633 gotBytes := readAllText(gotBytesBuf[:0], f)
634 wantRunes = append(wantRunes[:xR], wantRunes[yR:]...)
635 wantBytes = append(wantBytes[:xB], wantBytes[yB:]...)
636 if !bytes.Equal(gotBytes, wantBytes) {
637 t.Fatalf("i=%d, j=%d, xR=%d, xB=%d, yR=%d, yB=%d:\ngot %q\nwant %q",
638 i, j, xR, xB, yR, yB, gotBytes, wantBytes)
639 }
640 }
641 }
642 }
643
644 func TestDeleteTooMuch(t *testing.T) {
645 if len(iRobot) < 17+15 {
646 t.Fatal("iRobot string is too short")
647 }
648
649 f := iRobotFrame(10)
650 c := f.NewCaret()
651 defer c.Close()
652
653 c.Seek(-15, SeekEnd)
654 if got, want := c.Delete(Forwards, 16), 15; got != want {
655 t.Errorf("Delete Forwards: got %d, want %d", got, want)
656 }
657
658 c.Seek(+17, SeekSet)
659 if got, want := c.Delete(Backwards, 18), 17; got != want {
660 t.Errorf("Delete Backwards: got %d, want %d", got, want)
661 }
662
663 got := string(readAllText(nil, f))
664 want := iRobot[17 : len(iRobot)-15]
665 if got != want {
666 t.Errorf("\ngot %q\nwant %q", got, want)
667 }
668 }
669
670 func TestDeleteRunesTooMuch(t *testing.T) {
671 if len(iRobotRunes) < 30+24 {
672 t.Fatal("iRobotRunes []rune is too short")
673 }
674 prefix := iRobotRunes[:30]
675 suffix := iRobotRunes[len(iRobotRunes)-24:]
676 if allASCII(prefix) {
677 t.Fatal("prefix contains no non-ASCII runes")
678 }
679 if allASCII(suffix) {
680 t.Fatal("suffix contains no non-ASCII runes")
681 }
682 prefixB := runesLen(prefix)
683 suffixB := runesLen(suffix)
684
685 f := iRobotFrame(10)
686 c := f.NewCaret()
687 defer c.Close()
688
689 c.Seek(-int64(suffixB), SeekEnd)
690 wantR, wantB := len(suffix), suffixB
691 if gotR, gotB := c.DeleteRunes(Forwards, 25); gotR != wantR || gotB != wantB {
692 t.Errorf("DeleteRunes Forwards: got %d runes, %d bytes, want %d, %d", gotR, gotB, wantR, wantB)
693 }
694
695 c.Seek(+int64(prefixB), SeekSet)
696 wantR, wantB = len(prefix), prefixB
697 if gotR, gotB := c.DeleteRunes(Backwards, 31); gotR != wantR || gotB != wantB {
698 t.Errorf("DeleteRunes Backwards: got %d runes, %d bytes, want %d, %d", gotR, gotB, wantR, wantB)
699 }
700
701 got := string(readAllText(nil, f))
702 want := iRobot[prefixB : len(iRobot)-suffixB]
703 if got != want {
704 t.Errorf("\ngot %q\nwant %q", got, want)
705 }
706 }
707
708 func TestCompactText(t *testing.T) {
709 f := new(Frame)
710 f.SetFace(toyFace{})
711 f.SetMaxWidth(fixed.I(80))
712 c := f.NewCaret()
713 defer c.Close()
714
715 const n, abc64 = 1024, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\n "
716 rng := rand.New(rand.NewSource(1))
717 buf := make([]byte, n)
718 for i := range buf {
719 buf[i] = abc64[rng.Intn(len(abc64))]
720 }
721
722 written, wantLen := 0, 0
723 for i := 0; written < 131072; i++ {
724 if rng.Intn(10) != 0 {
725 x, y := rngIntPair(rng, len(buf)+1)
726 c.Seek(int64(rng.Intn(f.Len()+1)), SeekSet)
727 c.Write(buf[x:y])
728 written += y - x
729 wantLen += y - x
730 }
731
732 if rng.Intn(10) != 0 {
733 x, y := rngIntPair(rng, wantLen+1)
734 c.Seek(int64(x), SeekSet)
735 c.Delete(Forwards, y-x)
736 wantLen -= y - x
737 }
738
739 // Calculate cached counts, some of the time.
740 if rng.Intn(3) == 0 {
741 f.ParagraphCount()
742 }
743 if rng.Intn(4) == 0 {
744 f.LineCount()
745 }
746 if rng.Intn(5) == 0 {
747 c.Seek(int64(rng.Intn(f.Len()+1)), SeekSet)
748 f.paragraphs[c.p].LineCount(f)
749 }
750
751 if err := checkInvariants(f); err != nil {
752 t.Fatalf("i=%d: %v", i, err)
753 }
754 if gotLen := f.Len(); gotLen != wantLen {
755 t.Fatalf("i=%d: length: got %d, want %d", i, gotLen, wantLen)
756 }
757 }
758 if len(f.text) == written {
759 t.Fatal("f.text was not compacted")
760 }
761 }
762
763 func TestMergeIntoOneLine(t *testing.T) {
764 rng := rand.New(rand.NewSource(1))
765 for i := 0; i < 100; i++ {
766 f := new(Frame)
767 f.SetMaxWidth(fixed.I(100))
768
769 if !f.initialized() {
770 f.initialize()
771 }
772 p := f.firstP
773 pp := &f.paragraphs[p]
774 l := pp.firstL
775 ll := &f.lines[l]
776 b := ll.firstB
777 bb := &f.boxes[b]
778
779 // Make some Lines and Boxes.
780 wantNUsedBoxes := 0
781 prevIJ := int32(0)
782 emptyRun := true
783 for j := 0; ; j++ {
784 length := rng.Intn(3)
785 bb.i = prevIJ
786 prevIJ += int32(length)
787 bb.j = prevIJ
788 f.len += length
789 if length > 0 && emptyRun {
790 emptyRun = false
791 wantNUsedBoxes++
792 }
793
794 if rng.Intn(20) == 0 {
795 break
796 }
797
798 if rng.Intn(4) == 0 {
799 // Make a new Box on a new Line.
800 l1, realloc := f.newLine()
801 if realloc {
802 ll = &f.lines[l]
803 }
804 ll1 := &f.lines[l1]
805 ll.next = l1
806 ll1.prev = l
807 l, ll = l1, ll1
808
809 ll.firstB, _ = f.newBox()
810 b = ll.firstB
811 bb = &f.boxes[b]
812
813 } else {
814 // Make a new Box on the same Line.
815 b1, realloc := f.newBox()
816 if realloc {
817 bb = &f.boxes[b]
818 }
819 bb1 := &f.boxes[b1]
820 bb.next = b1
821 bb1.prev = b
822 b, bb = b1, bb1
823 }
824
825 if rng.Intn(5) == 0 {
826 // Put an i/j gap between this run and the previous one.
827 prevIJ += 1 + int32(rng.Intn(5))
828 emptyRun = true
829 }
830 }
831
832 // We normally remove all empty Boxes. However, if there is no text
833 // whatsoever, we still need one Box.
834 if f.len == 0 {
835 if wantNUsedBoxes != 0 {
836 t.Fatalf("i=%d: no text: wantNUsedBoxes: got %d, want 0", i, wantNUsedBoxes)
837 }
838 wantNUsedBoxes = 1
839 }
840
841 // Make f.text long enough to hold all of the Boxes' i's and j's.
842 f.text = make([]byte, prevIJ)
843 for i := range f.text {
844 f.text[i] = byte('a' + i%16)
845 }
846
847 // Do the merge.
848 if err := checkSomeInvariants(f, ignoreInvariantEmptyBoxes); err != nil {
849 t.Fatalf("i=%d: before: %v", i, err)
850 }
851 f.mergeIntoOneLine(p)
852 if err := checkInvariants(f); err != nil {
853 t.Fatalf("i=%d: after: %v", i, err)
854 }
855
856 // Check that there is only one Line in use.
857 if n := f.nUsedLines(); n != 1 {
858 t.Errorf("i=%d: nUsedLines: got %d, want %d", i, n, 1)
859 }
860
861 // Check the number of Boxes in use.
862 if n := f.nUsedBoxes(); n != wantNUsedBoxes {
863 t.Errorf("i=%d: nUsedBoxes: got %d, want %d", i, n, wantNUsedBoxes)
864 }
865 }
866 }
867
868 // TestMultipleCarets tests multiple Carets all seeking, reading, writing and
869 // deleting text.
870 func TestMultipleCarets(t *testing.T) {
871 f := new(Frame)
872 f.SetFace(toyFace{})
873 f.SetMaxWidth(fixed.I(10))
874
875 rng := rand.New(rand.NewSource(1))
876 gotBuf := make([]byte, 0, 10000)
877 want := make([]byte, 0, 10000)
878 positions := map[*Caret]int{}
879 carets := []*Caret{}
880 defer func() {
881 for _, c := range carets {
882 c.Close()
883 }
884 }()
885
886 for i := 0; i < 1000; i++ {
887 if err := checkInvariants(f); err != nil {
888 t.Fatalf("i=%d: %v", i, err)
889 }
890 if len(carets) == 0 || rng.Intn(20) == 0 {
891 c := f.NewCaret()
892 carets = append(carets, c)
893 positions[c] = 0
894 continue
895 }
896 caretsIndex := rng.Intn(len(carets))
897 c := carets[caretsIndex]
898
899 if rng.Intn(40) == 0 {
900 c.Close()
901 carets[caretsIndex] = carets[len(carets)-1]
902 carets[len(carets)-1] = nil
903 carets = carets[:len(carets)-1]
904 delete(positions, c)
905 continue
906 }
907
908 // Seek, read, delete or write, with a slight bias to writing.
909 switch rng.Intn(5) {
910 case 0: // Seek.
911 p := rng.Intn(len(want) + 1)
912 c.Seek(int64(p), SeekSet)
913 positions[c] = p
914
915 case 1: // ReadByte.
916 gotB, gotErr := c.ReadByte()
917 wantB, wantErr := byte(0), io.EOF
918 if p := positions[c]; p < len(want) {
919 wantB, wantErr = want[p], nil
920 positions[c] = p + 1
921 }
922 if gotB != wantB || gotErr != wantErr {
923 t.Fatalf("i=%d: ReadByte: got %d, %v, want %d, %v", i, gotB, gotErr, wantB, wantErr)
924 }
925
926 case 2: // Delete.
927 dir := Direction(rng.Intn(2) == 0)
928 nBytes, dBytes := rng.Intn(len(want)), 0
929 pos, x, y := positions[c], 0, 0
930 if dir == Forwards {
931 dBytes = min(nBytes, len(want)-pos)
932 x, y = pos, pos+dBytes
933 } else {
934 dBytes = min(nBytes, pos)
935 x, y = pos-dBytes, pos
936 }
937 if d := c.Delete(dir, nBytes); d != dBytes {
938 t.Fatalf("i=%d: Delete: got %d bytes, want %d", i, d, dBytes)
939 }
940 want = append(want[:x], want[y:]...)
941 for _, cc := range carets {
942 if cc == c {
943 positions[cc] = x
944 continue
945 }
946 switch p := positions[cc]; {
947 case p <= x:
948 // No-op.
949 case p <= y:
950 positions[cc] = x
951 default:
952 positions[cc] -= dBytes
953 }
954 }
955
956 default: // Write.
957 i, j := rngIntPair(rng, len(iRobotBytes))
958 s := iRobotBytes[i:j]
959 c.Write(s)
960 pos := positions[c]
961 want = insert(want, s, pos)
962 for _, cc := range carets {
963 if cc == c || positions[cc] > pos {
964 positions[cc] += j - i
965 }
966 }
967 }
968
969 badPos := false
970 for ci, cc := range carets {
971 if int(cc.pos) != positions[cc] {
972 badPos = true
973 t.Errorf("i=%d, ci=%d: position: got %d, want %d", i, ci, cc.pos, positions[cc])
974 }
975 }
976 if badPos {
977 t.Fatalf("i=%d: there were inconsistent Caret positions", i)
978 }
979
980 if got := readAllText(gotBuf[:0], f); !bytes.Equal(got, want) {
981 t.Fatalf("i=%d:\ngot % x\nwant % x", i, got, want)
982 }
983 }
984 if err := checkInvariants(f); err != nil {
985 t.Fatal(err)
986 }
987 }
988
989 type ijRange struct {
990 i, j int32
991 }
992
993 type byI []ijRange
994
995 func (b byI) Len() int { return len(b) }
996 func (b byI) Less(x, y int) bool { return b[x].i < b[y].i }
997 func (b byI) Swap(x, y int) { b[x], b[y] = b[y], b[x] }
998
999 const (
1000 ignoreInvariantEmptyBoxes = 1 << iota
1001 )
1002
1003 func checkInvariants(f *Frame) error {
1004 return checkSomeInvariants(f, 0)
1005 }
1006
1007 func checkSomeInvariants(f *Frame, ignoredInvariants uint32) error {
1008 const infinity = 1e6
1009
1010 if !f.initialized() {
1011 if !reflect.DeepEqual(*f, Frame{}) {
1012 return fmt.Errorf("uninitialized Frame is not zero-valued")
1013 }
1014 return nil
1015 }
1016
1017 // Iterate through the Paragraphs, Lines and Boxes. Check that every first
1018 // child has no previous sibling, and no child is the first child of
1019 // multiple parents. Also check the cached Paragraph and Line counts.
1020 nUsedParagraphs, nUsedLines, nUsedBoxes := 0, 0, 0
1021 {
1022 firstLines := map[int32]bool{}
1023 firstBoxes := map[int32]bool{}
1024 p := f.firstP
1025 if p == 0 {
1026 return fmt.Errorf("firstP is zero")
1027 }
1028 if x := f.paragraphs[p].prev; x != 0 {
1029 return fmt.Errorf("first Paragraph %d's prev: got %d, want 0", p, x)
1030 }
1031
1032 for ; p != 0; p = f.paragraphs[p].next {
1033 l := f.paragraphs[p].firstL
1034 if l == 0 {
1035 return fmt.Errorf("paragraphs[%d].firstL is zero", p)
1036 }
1037 if x := f.lines[l].prev; x != 0 {
1038 return fmt.Errorf("first Line %d's prev: got %d, want 0", l, x)
1039 }
1040 if firstLines[l] {
1041 return fmt.Errorf("duplicate first Line %d", l)
1042 }
1043 firstLines[l] = true
1044
1045 nUsedLinesThisParagraph := 0
1046 for ; l != 0; l = f.lines[l].next {
1047 b := f.lines[l].firstB
1048 if b == 0 {
1049 return fmt.Errorf("lines[%d].firstB is zero", l)
1050 }
1051 if x := f.boxes[b].prev; x != 0 {
1052 return fmt.Errorf("first Box %d's prev: got %d, want 0", b, x)
1053 }
1054 if firstBoxes[b] {
1055 return fmt.Errorf("duplicate first Box %d", b)
1056 }
1057 firstBoxes[b] = true
1058
1059 for ; b != 0; b = f.boxes[b].next {
1060 nUsedBoxes++
1061 if nUsedBoxes >= infinity {
1062 return fmt.Errorf("too many used Boxes (infinite loop?)")
1063 }
1064 }
1065 nUsedLines++
1066 nUsedLinesThisParagraph++
1067 }
1068 nUsedParagraphs++
1069
1070 if n := int(f.paragraphs[p].cachedLineCountPlus1 - 1); n >= 0 && n != nUsedLinesThisParagraph {
1071 return fmt.Errorf("Paragraph cached Line count: got %d, want %d", n, nUsedLinesThisParagraph)
1072 }
1073 }
1074 if n := int(f.cachedLineCountPlus1 - 1); n >= 0 && n != nUsedLines {
1075 return fmt.Errorf("Frame cached Line count: got %d, want %d", n, nUsedLines)
1076 }
1077 if n := int(f.cachedParagraphCountPlus1 - 1); n >= 0 && n != nUsedParagraphs {
1078 return fmt.Errorf("Frame cached Paragraph count: got %d, want %d", n, nUsedParagraphs)
1079 }
1080 }
1081
1082 // Check that only the last Box can be empty.
1083 if ignoredInvariants&ignoreInvariantEmptyBoxes == 0 {
1084 for p := f.firstP; p != 0; {
1085 nextP := f.paragraphs[p].next
1086 for l := f.paragraphs[p].firstL; l != 0; {
1087 nextL := f.lines[l].next
1088 for b := f.lines[l].firstB; b != 0; {
1089 nextB := f.boxes[b].next
1090
1091 emptyBox := f.boxes[b].i == f.boxes[b].j
1092 lastBox := nextP == 0 && nextL == 0 && nextB == 0
1093 if emptyBox && !lastBox {
1094 return fmt.Errorf("boxes[%d] is empty, but isn't the last Box", b)
1095 }
1096
1097 b = nextB
1098 }
1099 l = nextL
1100 }
1101 p = nextP
1102 }
1103 }
1104
1105 // Check the paragraphs.
1106 for p, pp := range f.paragraphs {
1107 if p == 0 {
1108 if pp != (Paragraph{}) {
1109 return fmt.Errorf("paragraphs[0] is a non-zero Paragraph: %v", pp)
1110 }
1111 continue
1112 }
1113 if pp.next < 0 || len(f.paragraphs) <= int(pp.next) {
1114 return fmt.Errorf("invalid paragraphs[%d].next: got %d, want in [0, %d)", p, pp.next, len(f.paragraphs))
1115 }
1116 if len(f.paragraphs) <= int(pp.prev) {
1117 return fmt.Errorf("invalid paragraphs[%d].prev: got %d, want in [0, %d)", p, pp.prev, len(f.paragraphs))
1118 }
1119 if pp.prev < 0 {
1120 // The Paragraph is in the free-list, which is checked separately below.
1121 continue
1122 }
1123 if pp.next != 0 && f.paragraphs[pp.next].prev != int32(p) {
1124 return fmt.Errorf("invalid links: paragraphs[%d].next=%d, paragraphs[%d].prev=%d",
1125 p, pp.next, pp.next, f.paragraphs[pp.next].prev)
1126 }
1127 if pp.prev != 0 && f.paragraphs[pp.prev].next != int32(p) {
1128 return fmt.Errorf("invalid links: paragraphs[%d].prev=%d, paragraphs[%d].next=%d",
1129 p, pp.prev, pp.prev, f.paragraphs[pp.prev].next)
1130 }
1131 }
1132
1133 // Check the paragraphs' free-list.
1134 nFreeParagraphs := 0
1135 for p := f.freeP; p != 0; nFreeParagraphs++ {
1136 if nFreeParagraphs >= infinity {
1137 return fmt.Errorf("Paragraph free-list is too long (infinite loop?)")
1138 }
1139 if p < 0 || len(f.paragraphs) <= int(p) {
1140 return fmt.Errorf("invalid Paragraph free-list index: got %d, want in [0, %d)", p, len(f.paragraphs))
1141 }
1142 pp := &f.paragraphs[p]
1143 if pp.prev >= 0 {
1144 return fmt.Errorf("paragraphs[%d] is an invalid free-list element: %#v", p, *pp)
1145 }
1146 p = pp.next
1147 }
1148
1149 // Check the lines.
1150 for l, ll := range f.lines {
1151 if l == 0 {
1152 if ll != (Line{}) {
1153 return fmt.Errorf("lines[0] is a non-zero Line: %v", ll)
1154 }
1155 continue
1156 }
1157 if ll.next < 0 || len(f.lines) <= int(ll.next) {
1158 return fmt.Errorf("invalid lines[%d].next: got %d, want in [0, %d)", l, ll.next, len(f.lines))
1159 }
1160 if len(f.lines) <= int(ll.prev) {
1161 return fmt.Errorf("invalid lines[%d].prev: got %d, want in [0, %d)", l, ll.prev, len(f.lines))
1162 }
1163 if ll.prev < 0 {
1164 // The Line is in the free-list, which is checked separately below.
1165 continue
1166 }
1167 if ll.next != 0 && f.lines[ll.next].prev != int32(l) {
1168 return fmt.Errorf("invalid links: lines[%d].next=%d, lines[%d].prev=%d",
1169 l, ll.next, ll.next, f.lines[ll.next].prev)
1170 }
1171 if ll.prev != 0 && f.lines[ll.prev].next != int32(l) {
1172 return fmt.Errorf("invalid links: lines[%d].prev=%d, lines[%d].next=%d",
1173 l, ll.prev, ll.prev, f.lines[ll.prev].next)
1174 }
1175 }
1176
1177 // Check the lines' free-list.
1178 nFreeLines := 0
1179 for l := f.freeL; l != 0; nFreeLines++ {
1180 if nFreeLines >= infinity {
1181 return fmt.Errorf("Line free-list is too long (infinite loop?)")
1182 }
1183 if l < 0 || len(f.lines) <= int(l) {
1184 return fmt.Errorf("invalid Line free-list index: got %d, want in [0, %d)", l, len(f.lines))
1185 }
1186 ll := &f.lines[l]
1187 if ll.prev >= 0 {
1188 return fmt.Errorf("lines[%d] is an invalid free-list element: %#v", l, *ll)
1189 }
1190 l = ll.next
1191 }
1192
1193 // Check the boxes.
1194 for b, bb := range f.boxes {
1195 if b == 0 {
1196 if bb != (Box{}) {
1197 return fmt.Errorf("boxes[0] is a non-zero Box: %v", bb)
1198 }
1199 continue
1200 }
1201 if bb.next < 0 || len(f.boxes) <= int(bb.next) {
1202 return fmt.Errorf("invalid boxes[%d].next: got %d, want in [0, %d)", b, bb.next, len(f.boxes))
1203 }
1204 if len(f.boxes) <= int(bb.prev) {
1205 return fmt.Errorf("invalid boxes[%d].prev: got %d, want in [0, %d)", b, bb.prev, len(f.boxes))
1206 }
1207 if bb.prev < 0 {
1208 // The Box is in the free-list, which is checked separately below.
1209 continue
1210 }
1211 if bb.next != 0 && f.boxes[bb.next].prev != int32(b) {
1212 return fmt.Errorf("invalid links: boxes[%d].next=%d, boxes[%d].prev=%d",
1213 b, bb.next, bb.next, f.boxes[bb.next].prev)
1214 }
1215 if bb.prev != 0 && f.boxes[bb.prev].next != int32(b) {
1216 return fmt.Errorf("invalid links: boxes[%d].prev=%d, boxes[%d].next=%d",
1217 b, bb.prev, bb.prev, f.boxes[bb.prev].next)
1218 }
1219 if 0 > bb.i || bb.i > bb.j || bb.j > int32(len(f.text)) {
1220 return fmt.Errorf("invalid boxes[%d] i/j range: i=%d, j=%d, len=%d", b, bb.i, bb.j, len(f.text))
1221 }
1222 }
1223
1224 // Check the boxes' free-list.
1225 nFreeBoxes := 0
1226 for b := f.freeB; b != 0; nFreeBoxes++ {
1227 if nFreeBoxes >= infinity {
1228 return fmt.Errorf("Box free-list is too long (infinite loop?)")
1229 }
1230 if b < 0 || len(f.boxes) <= int(b) {
1231 return fmt.Errorf("invalid Box free-list index: got %d, want in [0, %d)", b, len(f.boxes))
1232 }
1233 bb := &f.boxes[b]
1234 if bb.i != 0 || bb.j != 0 || bb.prev >= 0 {
1235 return fmt.Errorf("boxes[%d] is an invalid free-list element: %#v", b, *bb)
1236 }
1237 b = bb.next
1238 }
1239
1240 // Check that the boxes' i:j ranges do not overlap, and their total length
1241 // equals f.len.
1242 nText, ijRanges := 0, []ijRange{}
1243 for _, bb := range f.boxes {
1244 if bb.i < bb.j {
1245 nText += int(bb.j - bb.i)
1246 ijRanges = append(ijRanges, ijRange{i: bb.i, j: bb.j})
1247 }
1248 }
1249 sort.Sort(byI(ijRanges))
1250 for x := range ijRanges {
1251 if x == 0 {
1252 continue
1253 }
1254 if ijRanges[x-1].j > ijRanges[x].i {
1255 return fmt.Errorf("overlapping Box i:j ranges: %v and %v", ijRanges[x-1], ijRanges[x])
1256 }
1257 }
1258 if nText != f.len {
1259 return fmt.Errorf("text length: got %d, want %d", nText, f.len)
1260 }
1261
1262 // Check that every Paragraph, Line and Box, other than the 0th of each, is
1263 // either used or free.
1264 if len(f.paragraphs) != 1+nUsedParagraphs+nFreeParagraphs {
1265 return fmt.Errorf("#paragraphs (%d) != 1 + #used (%d) + #free (%d)",
1266 len(f.paragraphs), nUsedParagraphs, nFreeParagraphs)
1267 }
1268 if len(f.lines) != 1+nUsedLines+nFreeLines {
1269 return fmt.Errorf("#lines (%d) != 1 + #used (%d) + #free (%d)", len(f.lines), nUsedLines, nFreeLines)
1270 }
1271 if len(f.boxes) != 1+nUsedBoxes+nFreeBoxes {
1272 return fmt.Errorf("#boxes (%d) != 1 + #used (%d) + #free (%d)", len(f.boxes), nUsedBoxes, nFreeBoxes)
1273 }
1274
1275 // Check that each Caret's pos is in the Frame's 0:len range. If the
1276 // Caret's cached {p,l,b,k} values are valid, also check that the Caret's k
1277 // is in its Box's i:j range, and its Box b is in its Line l is in its
1278 // Paragraph p.
1279 for i, c := range f.carets {
1280 if c.pos < 0 || f.len < int(c.pos) {
1281 return fmt.Errorf("caret[%d]: pos %d outside range [0, %d]", i, c.pos, f.len)
1282 }
1283 if c.seqNum != f.seqNum {
1284 continue
1285 }
1286
1287 if c.b < 1 || len(f.boxes) < int(c.b) {
1288 return fmt.Errorf("caret[%d]: c.b %d outside range [1, %d]", i, c.b, len(f.boxes))
1289 }
1290 bb := &f.boxes[c.b]
1291 if c.k < bb.i || bb.j < c.k {
1292 return fmt.Errorf("caret[%d]: c.k %d outside range [%d, %d]", i, c.k, bb.i, bb.j)
1293 }
1294
1295 if c.l < 1 || len(f.lines) < int(c.l) {
1296 return fmt.Errorf("caret[%d]: c.l %d outside range [1, %d]", i, c.l, len(f.lines))
1297 }
1298 if !f.lines[c.l].contains(f, c.b) {
1299 return fmt.Errorf("caret[%d]: Line %d does not contain Box %d", i, c.l, c.b)
1300 }
1301
1302 if c.p < 1 || len(f.paragraphs) < int(c.p) {
1303 return fmt.Errorf("caret[%d]: c.p %d outside range [1, %d]", i, c.p, len(f.paragraphs))
1304 }
1305 if !f.paragraphs[c.p].contains(f, c.l) {
1306 return fmt.Errorf("caret[%d]: Paragraph %d does not contain Line %d", i, c.p, c.l)
1307 }
1308 }
1309
1310 return nil
1311 }
1312
1313 func (f *Frame) nUsedParagraphs() (n int) {
1314 for p, pp := range f.paragraphs {
1315 // The 0th index is a special case. A negative prev means that the
1316 // Paragraph is in the free-list.
1317 if p != 0 && pp.prev >= 0 {
1318 n++
1319 }
1320 }
1321 return n
1322 }
1323
1324 func (f *Frame) nUsedLines() (n int) {
1325 for l, ll := range f.lines {
1326 // The 0th index is a special case. A negative prev means that the
1327 // Line is in the free-list.
1328 if l != 0 && ll.prev >= 0 {
1329 n++
1330 }
1331 }
1332 return n
1333 }
1334
1335 func (f *Frame) nUsedBoxes() (n int) {
1336 for b, bb := range f.boxes {
1337 // The 0th index is a special case. A negative prev means that the
1338 // Box is in the free-list.
1339 if b != 0 && bb.prev >= 0 {
1340 n++
1341 }
1342 }
1343 return n
1344 }
1345
1346 func (p *Paragraph) contains(f *Frame, l int32) bool {
1347 for x := p.firstL; x != 0; x = f.lines[x].next {
1348 if x == l {
1349 return true
1350 }
1351 }
1352 return false
1353 }
1354
1355 func (l *Line) contains(f *Frame, b int32) bool {
1356 for x := l.firstB; x != 0; x = f.boxes[x].next {
1357 if x == b {
1358 return true
1359 }
1360 }
1361 return false
1362 }
1363
1364 // dump is used for debugging.
1365 func dump(w io.Writer, f *Frame) {
1366 for p := f.FirstParagraph(); p != nil; p = p.Next(f) {
1367 for l := p.FirstLine(f); l != nil; l = l.Next(f) {
1368 for b := l.FirstBox(f); b != nil; b = b.Next(f) {
1369 fmt.Fprintf(w, "[%s]", b.TrimmedText(f))
1370 }
1371 fmt.Fprintln(w)
1372 }
1373 }
1374 }