1
2
3
4
5
6
7 package language
8
9
10
11
12 import (
13 "errors"
14 "fmt"
15 "strings"
16 )
17
18 const (
19
20
21 maxCoreSize = 12
22
23
24
25 max99thPercentileSize = 32
26
27
28
29 maxSimpleUExtensionSize = 14
30 )
31
32
33
34
35 type Tag struct {
36
37
38
39
40
41 LangID Language
42 RegionID Region
43
44
45
46
47
48
49
50 ScriptID Script
51 pVariant byte
52 pExt uint16
53
54
55
56 str string
57 }
58
59
60
61 func Make(s string) Tag {
62 t, _ := Parse(s)
63 return t
64 }
65
66
67
68
69 func (t Tag) Raw() (b Language, s Script, r Region) {
70 return t.LangID, t.ScriptID, t.RegionID
71 }
72
73
74 func (t Tag) equalTags(a Tag) bool {
75 return t.LangID == a.LangID && t.ScriptID == a.ScriptID && t.RegionID == a.RegionID
76 }
77
78
79 func (t Tag) IsRoot() bool {
80 if int(t.pVariant) < len(t.str) {
81 return false
82 }
83 return t.equalTags(Und)
84 }
85
86
87
88 func (t Tag) IsPrivateUse() bool {
89 return t.str != "" && t.pVariant == 0
90 }
91
92
93
94
95 func (t *Tag) RemakeString() {
96 if t.str == "" {
97 return
98 }
99 extra := t.str[t.pVariant:]
100 if t.pVariant > 0 {
101 extra = extra[1:]
102 }
103 if t.equalTags(Und) && strings.HasPrefix(extra, "x-") {
104 t.str = extra
105 t.pVariant = 0
106 t.pExt = 0
107 return
108 }
109 var buf [max99thPercentileSize]byte
110 b := buf[:t.genCoreBytes(buf[:])]
111 if extra != "" {
112 diff := len(b) - int(t.pVariant)
113 b = append(b, '-')
114 b = append(b, extra...)
115 t.pVariant = uint8(int(t.pVariant) + diff)
116 t.pExt = uint16(int(t.pExt) + diff)
117 } else {
118 t.pVariant = uint8(len(b))
119 t.pExt = uint16(len(b))
120 }
121 t.str = string(b)
122 }
123
124
125
126
127 func (t *Tag) genCoreBytes(buf []byte) int {
128 n := t.LangID.StringToBuf(buf[:])
129 if t.ScriptID != 0 {
130 n += copy(buf[n:], "-")
131 n += copy(buf[n:], t.ScriptID.String())
132 }
133 if t.RegionID != 0 {
134 n += copy(buf[n:], "-")
135 n += copy(buf[n:], t.RegionID.String())
136 }
137 return n
138 }
139
140
141 func (t Tag) String() string {
142 if t.str != "" {
143 return t.str
144 }
145 if t.ScriptID == 0 && t.RegionID == 0 {
146 return t.LangID.String()
147 }
148 buf := [maxCoreSize]byte{}
149 return string(buf[:t.genCoreBytes(buf[:])])
150 }
151
152
153 func (t Tag) MarshalText() (text []byte, err error) {
154 if t.str != "" {
155 text = append(text, t.str...)
156 } else if t.ScriptID == 0 && t.RegionID == 0 {
157 text = append(text, t.LangID.String()...)
158 } else {
159 buf := [maxCoreSize]byte{}
160 text = buf[:t.genCoreBytes(buf[:])]
161 }
162 return text, nil
163 }
164
165
166 func (t *Tag) UnmarshalText(text []byte) error {
167 tag, err := Parse(string(text))
168 *t = tag
169 return err
170 }
171
172
173
174 func (t Tag) Variants() string {
175 if t.pVariant == 0 {
176 return ""
177 }
178 return t.str[t.pVariant:t.pExt]
179 }
180
181
182 func (t Tag) VariantOrPrivateUseTags() string {
183 if t.pExt > 0 {
184 return t.str[t.pVariant:t.pExt]
185 }
186 return t.str[t.pVariant:]
187 }
188
189
190
191 func (t Tag) HasString() bool {
192 return t.str != ""
193 }
194
195
196
197
198 func (t Tag) Parent() Tag {
199 if t.str != "" {
200
201 b, s, r := t.Raw()
202 t = Tag{LangID: b, ScriptID: s, RegionID: r}
203 if t.RegionID == 0 && t.ScriptID != 0 && t.LangID != 0 {
204 base, _ := addTags(Tag{LangID: t.LangID})
205 if base.ScriptID == t.ScriptID {
206 return Tag{LangID: t.LangID}
207 }
208 }
209 return t
210 }
211 if t.LangID != 0 {
212 if t.RegionID != 0 {
213 maxScript := t.ScriptID
214 if maxScript == 0 {
215 max, _ := addTags(t)
216 maxScript = max.ScriptID
217 }
218
219 for i := range parents {
220 if Language(parents[i].lang) == t.LangID && Script(parents[i].maxScript) == maxScript {
221 for _, r := range parents[i].fromRegion {
222 if Region(r) == t.RegionID {
223 return Tag{
224 LangID: t.LangID,
225 ScriptID: Script(parents[i].script),
226 RegionID: Region(parents[i].toRegion),
227 }
228 }
229 }
230 }
231 }
232
233
234 base, _ := addTags(Tag{LangID: t.LangID})
235 if base.ScriptID != maxScript {
236 return Tag{LangID: t.LangID, ScriptID: maxScript}
237 }
238 return Tag{LangID: t.LangID}
239 } else if t.ScriptID != 0 {
240
241
242 base, _ := addTags(Tag{LangID: t.LangID})
243 if base.ScriptID != t.ScriptID {
244 return Und
245 }
246 return Tag{LangID: t.LangID}
247 }
248 }
249 return Und
250 }
251
252
253 func ParseExtension(s string) (ext string, err error) {
254 defer func() {
255 if recover() != nil {
256 ext = ""
257 err = ErrSyntax
258 }
259 }()
260
261 scan := makeScannerString(s)
262 var end int
263 if n := len(scan.token); n != 1 {
264 return "", ErrSyntax
265 }
266 scan.toLower(0, len(scan.b))
267 end = parseExtension(&scan)
268 if end != len(s) {
269 return "", ErrSyntax
270 }
271 return string(scan.b), nil
272 }
273
274
275 func (t Tag) HasVariants() bool {
276 return uint16(t.pVariant) < t.pExt
277 }
278
279
280 func (t Tag) HasExtensions() bool {
281 return int(t.pExt) < len(t.str)
282 }
283
284
285
286
287 func (t Tag) Extension(x byte) (ext string, ok bool) {
288 for i := int(t.pExt); i < len(t.str)-1; {
289 var ext string
290 i, ext = getExtension(t.str, i)
291 if ext[0] == x {
292 return ext, true
293 }
294 }
295 return "", false
296 }
297
298
299 func (t Tag) Extensions() []string {
300 e := []string{}
301 for i := int(t.pExt); i < len(t.str)-1; {
302 var ext string
303 i, ext = getExtension(t.str, i)
304 e = append(e, ext)
305 }
306 return e
307 }
308
309
310
311
312
313
314
315
316
317 func (t Tag) TypeForKey(key string) string {
318 if _, start, end, _ := t.findTypeForKey(key); end != start {
319 s := t.str[start:end]
320 if p := strings.IndexByte(s, '-'); p >= 0 {
321 s = s[:p]
322 }
323 return s
324 }
325 return ""
326 }
327
328 var (
329 errPrivateUse = errors.New("cannot set a key on a private use tag")
330 errInvalidArguments = errors.New("invalid key or type")
331 )
332
333
334
335
336
337 func (t Tag) SetTypeForKey(key, value string) (Tag, error) {
338 if t.IsPrivateUse() {
339 return t, errPrivateUse
340 }
341 if len(key) != 2 {
342 return t, errInvalidArguments
343 }
344
345
346 if value == "" {
347 start, sep, end, _ := t.findTypeForKey(key)
348 if start != sep {
349
350 switch {
351 case t.str[start-2] != '-':
352 case end == len(t.str),
353 end+2 < len(t.str) && t.str[end+2] == '-':
354 start -= 2
355 }
356 if start == int(t.pVariant) && end == len(t.str) {
357 t.str = ""
358 t.pVariant, t.pExt = 0, 0
359 } else {
360 t.str = fmt.Sprintf("%s%s", t.str[:start], t.str[end:])
361 }
362 }
363 return t, nil
364 }
365
366 if len(value) < 3 || len(value) > 8 {
367 return t, errInvalidArguments
368 }
369
370 var (
371 buf [maxCoreSize + maxSimpleUExtensionSize]byte
372 uStart int
373 )
374
375
376 if t.str == "" {
377 uStart = t.genCoreBytes(buf[:])
378 buf[uStart] = '-'
379 uStart++
380 }
381
382
383 b := buf[uStart:]
384 copy(b, "u-")
385 copy(b[2:], key)
386 b[4] = '-'
387 b = b[:5+copy(b[5:], value)]
388 scan := makeScanner(b)
389 if parseExtensions(&scan); scan.err != nil {
390 return t, scan.err
391 }
392
393
394 if t.str == "" {
395 t.pVariant, t.pExt = byte(uStart-1), uint16(uStart-1)
396 t.str = string(buf[:uStart+len(b)])
397 } else {
398 s := t.str
399 start, sep, end, hasExt := t.findTypeForKey(key)
400 if start == sep {
401 if hasExt {
402 b = b[2:]
403 }
404 t.str = fmt.Sprintf("%s-%s%s", s[:sep], b, s[end:])
405 } else {
406 t.str = fmt.Sprintf("%s-%s%s", s[:start+3], value, s[end:])
407 }
408 }
409 return t, nil
410 }
411
412
413
414
415
416
417 func (t Tag) findTypeForKey(key string) (start, sep, end int, hasExt bool) {
418 p := int(t.pExt)
419 if len(key) != 2 || p == len(t.str) || p == 0 {
420 return p, p, p, false
421 }
422 s := t.str
423
424
425 for p++; s[p] != 'u'; p++ {
426 if s[p] > 'u' {
427 p--
428 return p, p, p, false
429 }
430 if p = nextExtension(s, p); p == len(s) {
431 return len(s), len(s), len(s), false
432 }
433 }
434
435 p++
436
437
438 curKey := ""
439
440
441 for {
442 end = p
443 for p++; p < len(s) && s[p] != '-'; p++ {
444 }
445 n := p - end - 1
446 if n <= 2 && curKey == key {
447 if sep < end {
448 sep++
449 }
450 return start, sep, end, true
451 }
452 switch n {
453 case 0,
454 1:
455 return end, end, end, true
456 case 2:
457
458 curKey = s[end+1 : p]
459 if curKey > key {
460 return end, end, end, true
461 }
462 start = end
463 sep = p
464 }
465 }
466 }
467
468
469
470
471 func ParseBase(s string) (l Language, err error) {
472 defer func() {
473 if recover() != nil {
474 l = 0
475 err = ErrSyntax
476 }
477 }()
478
479 if n := len(s); n < 2 || 3 < n {
480 return 0, ErrSyntax
481 }
482 var buf [3]byte
483 return getLangID(buf[:copy(buf[:], s)])
484 }
485
486
487
488
489 func ParseScript(s string) (scr Script, err error) {
490 defer func() {
491 if recover() != nil {
492 scr = 0
493 err = ErrSyntax
494 }
495 }()
496
497 if len(s) != 4 {
498 return 0, ErrSyntax
499 }
500 var buf [4]byte
501 return getScriptID(script, buf[:copy(buf[:], s)])
502 }
503
504
505
506 func EncodeM49(r int) (Region, error) {
507 return getRegionM49(r)
508 }
509
510
511
512
513 func ParseRegion(s string) (r Region, err error) {
514 defer func() {
515 if recover() != nil {
516 r = 0
517 err = ErrSyntax
518 }
519 }()
520
521 if n := len(s); n < 2 || 3 < n {
522 return 0, ErrSyntax
523 }
524 var buf [3]byte
525 return getRegionID(buf[:copy(buf[:], s)])
526 }
527
528
529
530 func (r Region) IsCountry() bool {
531 if r == 0 || r.IsGroup() || r.IsPrivateUse() && r != _XK {
532 return false
533 }
534 return true
535 }
536
537
538
539 func (r Region) IsGroup() bool {
540 if r == 0 {
541 return false
542 }
543 return int(regionInclusion[r]) < len(regionContainment)
544 }
545
546
547
548 func (r Region) Contains(c Region) bool {
549 if r == c {
550 return true
551 }
552 g := regionInclusion[r]
553 if g >= nRegionGroups {
554 return false
555 }
556 m := regionContainment[g]
557
558 d := regionInclusion[c]
559 b := regionInclusionBits[d]
560
561
562
563
564 if d >= nRegionGroups {
565 return b&m != 0
566 }
567 return b&^m == 0
568 }
569
570 var errNoTLD = errors.New("language: region is not a valid ccTLD")
571
572
573
574
575
576
577
578
579 func (r Region) TLD() (Region, error) {
580
581
582 if r == _GB {
583 r = _UK
584 }
585 if (r.typ() & ccTLD) == 0 {
586 return 0, errNoTLD
587 }
588 return r, nil
589 }
590
591
592
593
594 func (r Region) Canonicalize() Region {
595 if cr := normRegion(r); cr != 0 {
596 return cr
597 }
598 return r
599 }
600
601
602 type Variant struct {
603 ID uint8
604 str string
605 }
606
607
608
609 func ParseVariant(s string) (v Variant, err error) {
610 defer func() {
611 if recover() != nil {
612 v = Variant{}
613 err = ErrSyntax
614 }
615 }()
616
617 s = strings.ToLower(s)
618 if id, ok := variantIndex[s]; ok {
619 return Variant{id, s}, nil
620 }
621 return Variant{}, NewValueError([]byte(s))
622 }
623
624
625 func (v Variant) String() string {
626 return v.str
627 }
628
View as plain text