...
1
2
3
4
5
6
7 package colltab
8
9 import (
10 "sort"
11
12 "golang.org/x/text/language"
13 )
14
15
16
17
18
19
20
21
22
23
24
25 func MatchLang(t language.Tag, tags []language.Tag) int {
26
27 t, _ = language.All.Canonicalize(t)
28
29 base, conf := t.Base()
30
31 if conf < language.High {
32
33
34 return 0
35 }
36
37
38 if _, s, r := t.Raw(); (r != language.Region{}) {
39 p, _ := language.Raw.Compose(base, s, r)
40
41 p = p.Parent()
42
43 t, _ = language.Raw.Compose(p, r, t.Extensions())
44 } else {
45
46 t, _ = language.Raw.Compose(base, s, t.Extensions())
47 }
48
49
50 start := 1 + sort.Search(len(tags)-1, func(i int) bool {
51 b, _, _ := tags[i+1].Raw()
52 return base.String() <= b.String()
53 })
54 if start < len(tags) {
55 if b, _, _ := tags[start].Raw(); b != base {
56 return 0
57 }
58 }
59
60
61
62
63
64 tdef, _ := language.Raw.Compose(t.Raw())
65 tdef, _ = tdef.SetTypeForKey("va", t.TypeForKey("va"))
66
67
68 try := []language.Tag{tdef}
69 if co := t.TypeForKey("co"); co != "" {
70 tco, _ := tdef.SetTypeForKey("co", co)
71 try = []language.Tag{tco, tdef}
72 }
73
74 for _, tx := range try {
75 for ; tx != language.Und; tx = parent(tx) {
76 for i, t := range tags[start:] {
77 if b, _, _ := t.Raw(); b != base {
78 break
79 }
80 if tx == t {
81 return start + i
82 }
83 }
84 }
85 }
86 return 0
87 }
88
89
90
91 func parent(t language.Tag) language.Tag {
92 if t.TypeForKey("va") != "" {
93 t, _ = t.SetTypeForKey("va", "")
94 return t
95 }
96 result := language.Und
97 if b, s, r := t.Raw(); (r != language.Region{}) {
98 result, _ = language.Raw.Compose(b, s, t.Extensions())
99 } else if (s != language.Script{}) {
100 result, _ = language.Raw.Compose(b, t.Extensions())
101 } else if (b != language.Base{}) {
102 result, _ = language.Raw.Compose(t.Extensions())
103 }
104 return result
105 }
106
View as plain text