1package bidi
2
3import (
4 "slices"
5 "testing"
6 "unicode"
7)
8
9// The left-to-right fast path must match the full algorithm on every rune
10// it accepts, alone and next to other accepted runes.
11func TestLeftToRightOnlyMatchesFullAlgorithm(t *testing.T) {
12 var accepted []rune
13 for r := rune(0); r <= unicode.MaxRune; r++ {
14 if (r >= 0xd800 && r <= 0xdfff) || !leftToRightOnly([]rune{r}) {
15 continue
16 }
17 accepted = append(accepted, r)
18 }
19 if len(accepted) < 1000 {
20 t.Fatalf("only %d runes accepted", len(accepted))
21 }
22 check := func(text []rune) {
23 t.Helper()
24 breaks := []int{len(text)}
25 if len(text) > 1 {
26 breaks = []int{1, len(text)} // L1 on a line end inside the paragraph
27 }
28 for _, base := range []BaseDirection{Auto, LTR} {
29 fast, fastBase, err := Resolve(text, base, breaks)
30 if err != nil {
31 t.Fatal(err)
32 }
33 full, fullBase, err := resolveFull(text, base, breaks)
34 if err != nil {
35 t.Fatal(err)
36 }
37 if fastBase != fullBase || !slices.Equal(fast, full) {
38 t.Fatalf("%U base %d: fast %v/%d, full %v/%d", text, base, fast, fastBase, full, fullBase)
39 }
40 }
41 }
42 for _, r := range accepted {
43 check([]rune{r})
44 check([]rune{'1', r, '2'})
45 check([]rune{'(', r, ' ', '1', ')'})
46 }
47 check([]rune("Value: 42, (x+y) = -3.5% \t#1"))
48}
49
50func TestAllocResolveLeftToRight(t *testing.T) {
51 text := []rune("Value: 42")
52 breaks := []int{len(text)}
53 if got := testing.AllocsPerRun(100, func() { _, _, _ = Resolve(text, Auto, breaks) }); got > 1 {
54 t.Fatalf("allocs = %v, want at most 1 (the result)", got)
55 }
56 dst := make([]uint8, 0, len(text))
57 if got := testing.AllocsPerRun(100, func() { dst, _, _ = ResolveInto(dst, text, Auto, breaks) }); got != 0 {
58 t.Fatalf("ResolveInto allocs = %v, want 0", got)
59 }
60 dst[0] = 7 // stale levels must be cleared on reuse
61 if levels, _, _ := ResolveInto(dst, text, Auto, breaks); levels[0] != 0 {
62 t.Fatalf("reused levels not cleared: %v", levels)
63 }
64}
65
66func TestResolveIntoFullPathIgnoresDst(t *testing.T) {
67 text := []rune("abc \u05d0\u05d1\u05d2 12")
68 breaks := []int{len(text)}
69 for _, base := range []BaseDirection{Auto, RTL} {
70 want, wantPara, err := Resolve(text, base, breaks)
71 if err != nil {
72 t.Fatal(err)
73 }
74 dst := make([]uint8, len(text))
75 for i := range dst {
76 dst[i] = 7
77 }
78 got, para, err := ResolveInto(dst, text, base, breaks)
79 if err != nil || para != wantPara || !slices.Equal(got, want) {
80 t.Fatalf("base %d: got %v %d %v, want %v %d", base, got, para, err, want, wantPara)
81 }
82 if &got[0] == &dst[0] || dst[0] != 7 {
83 t.Fatalf("base %d: full path wrote into dst", base)
84 }
85 }
86}