forked from couchbase/sync_gateway
/
maketables.go
837 lines (748 loc) · 20.7 KB
/
maketables.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
// Locale identifier table generator.
// Data read from the web.
package main
import (
"bufio"
"code.google.com/p/go.exp/locale/cldr"
"flag"
"fmt"
"hash"
"hash/fnv"
"io"
"log"
"math"
"net/http"
"os"
"path"
"reflect"
"sort"
"strconv"
"strings"
)
var (
url = flag.String("cldr",
"http://www.unicode.org/Public/cldr/"+cldr.Version+"/core.zip",
"URL of CLDR archive.")
iana = flag.String("iana",
"http://www.iana.org/assignments/language-subtag-registry",
"URL of IANA language subtag registry.")
test = flag.Bool("test", false,
"test existing tables; can be used to compare web data with package data.")
localFiles = flag.Bool("local", false,
"data files have been copied to the current directory; for debugging only.")
)
var comment = []string{
`
lang holds an alphabetically sorted list of BCP 47 language identifiers.
All entries are 4 bytes. The index of the identifier (divided by 4) is the language ID.
For 2-byte language identifiers, the two successive bytes have the following meaning:
- if the first letter of the 2- and 3-letter ISO codes are the same:
the second and third letter of the 3-letter ISO code.
- otherwise: a 0 and a by 2 bits right-shifted index into altLangISO3.
For 3-byte language identifiers the 4th byte is 0.`,
`
langNoIndex is a bit vector of all 3-letter language codes that are not used as an index
in lookup tables. The language ids for these language codes are derived directly
from the letters and are not consecutive.`,
`
altLangISO3 holds an alphabetically sorted list of 3-letter language code alternatives
to 2-letter language codes that cannot be derived using the method described above.
Each 3-letter code is followed by its 1-byte langID.`,
`
tagAlias holds a mapping from legacy and grandfathered tags to their locale ID.`,
`
langOldMap maps deprecated langIDs to their suggested replacements.`,
`
langMacroMap maps languages to their macro language replacement, if applicable.`,
`
script is an alphabetically sorted list of ISO 15924 codes. The index
of the script in the string, divided by 4, is the internal script ID.`,
`
isoRegionOffset needs to be added to the index of regionISO to obtain the regionID
for 2-letter ISO codes. (The first isoRegionOffset regionIDs are reserved for
the UN.M49 codes used for groups.)`,
`
regionISO holds a list of alphabetically sorted 2-letter ISO region codes.
Each 2-letter codes is followed by two bytes with the following meaning:
- [A-Z}{2}: the first letter of the 2-letter code plus these two
letters form the 3-letter ISO code.
- 0, n: index into altRegionISO3.`,
`
m49 maps regionIDs to UN.M49 codes. The first isoRegionOffset entries are
codes indicating collections of regions.`,
`
altRegionISO3 holds a list of 3-letter region codes that cannot be
mapped to 2-letter codes using the default algorithm. This is a short list.`,
`
altRegionIDs holsd a list of regionIDs the positions of which match those
of the 3-letter ISO codes in altRegionISO3.`,
`
currency holds an alphabetically sorted list of canonical 3-letter currency identifiers.
Each identifier is followed by a byte of which the 6 most significant bits
indicated the rounding and the least 2 significant bits indicate the
number of decimal positions.`,
`
suppressScript is an index from langID to the dominant script for that language,
if it exists. If a script is given, it should be suppressed from the language tag.`,
}
// TODO: consider changing some of these strutures to tries. This can reduce
// memory, but may increase the need for memory allocations. This could be
// mitigated if we can piggyback on locale strings for common cases.
func failOnError(e error) {
if e != nil {
log.Panic(e)
}
}
type setType int
const (
Indexed setType = 1 + iota // all elements must be of same size
Linear
)
type stringSet struct {
s []string
sorted, frozen bool
// We often need to update values after the creation of an index is completed.
// We include a convenience map for keeping track of this.
update map[string]string
typ setType // used for checking.
}
func (ss *stringSet) clone() stringSet {
c := *ss
c.s = append([]string(nil), c.s...)
return c
}
func (ss *stringSet) setType(t setType) {
if ss.typ != t && ss.typ != 0 {
log.Panicf("type %d cannot be assigned as it was already %d", t, ss.typ)
}
}
// parse parses a whitespace-separated string and initializes ss with its
// components.
func (ss *stringSet) parse(s string) {
scan := bufio.NewScanner(strings.NewReader(s))
scan.Split(bufio.ScanWords)
for scan.Scan() {
ss.add(scan.Text())
}
}
func (ss *stringSet) assertChangeable() {
if ss.frozen {
log.Panic("attempt to modify a frozen stringSet")
}
}
func (ss *stringSet) add(s string) {
ss.assertChangeable()
ss.s = append(ss.s, s)
ss.sorted = ss.frozen
}
func (ss *stringSet) freeze() {
ss.compact()
ss.frozen = true
}
func (ss *stringSet) compact() {
if ss.sorted {
return
}
a := ss.s
sort.Strings(a)
k := 0
for i := 1; i < len(a); i++ {
if a[k] != a[i] {
a[k+1] = a[i]
k++
}
}
ss.s = a[:k+1]
ss.sorted = ss.frozen
}
type funcSorter struct {
fn func(a, b string) bool
sort.StringSlice
}
func (s funcSorter) Less(i, j int) bool {
return s.fn(s.StringSlice[i], s.StringSlice[j])
}
func (ss *stringSet) sortFunc(f func(a, b string) bool) {
ss.compact()
sort.Sort(funcSorter{f, sort.StringSlice(ss.s)})
}
func (ss *stringSet) remove(s string) {
ss.assertChangeable()
if i, ok := ss.find(s); ok {
copy(ss.s[i:], ss.s[i+1:])
ss.s = ss.s[:len(ss.s)-1]
}
}
func (ss *stringSet) replace(ol, nu string) {
ss.s[ss.index(ol)] = nu
ss.sorted = ss.frozen
}
func (ss *stringSet) index(s string) int {
ss.setType(Indexed)
i, ok := ss.find(s)
if !ok {
if i < len(ss.s) {
log.Panicf("find: item %q is not in list. Closest match is %q.", s, ss.s[i])
}
log.Panicf("find: item %q is not in list", s)
}
return i
}
func (ss *stringSet) find(s string) (int, bool) {
ss.compact()
i := sort.SearchStrings(ss.s, s)
return i, i != len(ss.s) && ss.s[i] == s
}
func (ss *stringSet) slice() []string {
ss.compact()
return ss.s
}
func (ss *stringSet) updateLater(v, key string) {
if ss.update == nil {
ss.update = map[string]string{}
}
ss.update[v] = key
}
// join joins the string and ensures that all entries are of the same length.
func (ss *stringSet) join() string {
ss.setType(Indexed)
n := len(ss.s[0])
for _, s := range ss.s {
if len(s) != n {
log.Panic("join: not all entries are of the same length")
}
}
ss.s = append(ss.s, strings.Repeat("\xff", n))
return strings.Join(ss.s, "")
}
// ianaEntry holds information for an entry in the IANA Language Subtag Repository.
// All types use the same entry.
// See http://tools.ietf.org/html/bcp47#section-5.1 for a description of the various
// fields.
type ianaEntry struct {
typ string
tag string
description []string
scope string
added string
preferred string
deprecated string
suppressScript string
macro string
prefix []string
}
type builder struct {
w io.Writer // multi writer
out io.Writer // set to Stdout
hash32 hash.Hash32 // for checking whether tables have changed.
size int
data *cldr.CLDR
supp *cldr.SupplementalData
// indices
locale stringSet // common locales
lang stringSet // canonical language ids (2 or 3 letter ISO codes) with data
langNoIndex stringSet // 3-letter ISO codes with no associated data
script stringSet // 4-letter ISO codes
region stringSet // 2-letter ISO or 3-digit UN M49 codes
currency stringSet // 3-letter ISO currency codes
// langInfo
registry map[string]*ianaEntry
}
func openReader(url *string) io.ReadCloser {
if *localFiles {
pwd, _ := os.Getwd()
*url = "file://" + path.Join(pwd, path.Base(*url))
}
t := &http.Transport{}
t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
c := &http.Client{Transport: t}
resp, err := c.Get(*url)
failOnError(err)
if resp.StatusCode != 200 {
log.Fatalf(`bad GET status for "%s": %s`, *url, resp.Status)
}
return resp.Body
}
func newBuilder() *builder {
r := openReader(url)
defer r.Close()
d := &cldr.Decoder{}
d.SetDirFilter("supplemental")
data, err := d.DecodeZip(r)
failOnError(err)
b := builder{
out: os.Stdout,
data: data,
supp: data.Supplemental(),
hash32: fnv.New32(),
}
b.w = io.MultiWriter(b.out, b.hash32)
b.parseRegistry()
return &b
}
func (b *builder) parseRegistry() {
r := openReader(iana)
defer r.Close()
b.registry = make(map[string]*ianaEntry)
scan := bufio.NewScanner(r)
scan.Split(bufio.ScanWords)
var record *ianaEntry
for more := scan.Scan(); more; {
key := scan.Text()
more = scan.Scan()
value := scan.Text()
switch key {
case "Type:":
//log.Printf("%#v", record)
record = &ianaEntry{typ: value}
case "Subtag:", "Tag:":
record.tag = value
if info, ok := b.registry[value]; ok {
if info.typ != "language" || record.typ != "extlang" {
log.Fatalf("parseRegistry: tag %q already exists", value)
}
} else {
b.registry[value] = record
}
case "Suppress-Script:":
record.suppressScript = value
case "Added:":
record.added = value
case "Deprecated:":
record.deprecated = value
case "Macrolanguage:":
record.macro = value
case "Preferred-Value:":
record.preferred = value
case "Prefix:":
record.prefix = append(record.prefix, value)
case "Scope:":
record.scope = value
case "Description:":
buf := []byte(value)
for more = scan.Scan(); more; more = scan.Scan() {
b := scan.Bytes()
if b[0] == '%' || b[len(b)-1] == ':' {
break
}
buf = append(buf, ' ')
buf = append(buf, b...)
}
record.description = append(record.description, string(buf))
continue
default:
continue
}
more = scan.Scan()
}
if scan.Err() != nil {
log.Panic(scan.Err())
}
}
var commentIndex = make(map[string]string)
func init() {
for _, s := range comment {
key := strings.TrimSpace(strings.SplitN(s, " ", 2)[0])
commentIndex[key] = strings.Replace(s, "\n", "\n// ", -1)
}
}
func (b *builder) comment(name string) {
fmt.Fprintln(b.out, commentIndex[name])
}
func (b *builder) pf(f string, x ...interface{}) {
fmt.Fprintf(b.w, f, x...)
fmt.Fprint(b.w, "\n")
}
func (b *builder) p(x ...interface{}) {
fmt.Fprintln(b.w, x...)
}
func (b *builder) addSize(s int) {
b.size += s
b.pf("// Size: %d bytes", s)
}
func (b *builder) addArraySize(s, n int) {
b.size += s
b.pf("// Size: %d bytes, %d elements", s, n)
}
func (b *builder) writeConst(name string, x interface{}) {
b.comment(name)
b.pf("const %s = %v", name, x)
}
func (b *builder) writeSlice(name string, ss interface{}) {
b.comment(name)
v := reflect.ValueOf(ss)
t := v.Type().Elem()
b.addArraySize(v.Len()*int(t.Size()), v.Len())
fmt.Fprintf(b.w, `var %s = [%d]%s{`, name, v.Len(), t)
for i := 0; i < v.Len(); i++ {
if t.Kind() == reflect.Struct {
fmt.Fprintf(b.w, "\n\t%#v, ", v.Index(i).Interface())
} else {
if i%12 == 0 {
fmt.Fprintf(b.w, "\n\t")
}
fmt.Fprintf(b.w, "%d, ", v.Index(i).Interface())
}
}
b.p("\n}")
}
// writeStringSlice writes a slice of strings. This produces a lot
// of overhead. It should typically only be used for debugging.
// TODO: remove
func (b *builder) writeStringSlice(name string, ss []string) {
b.comment(name)
t := reflect.TypeOf(ss).Elem()
sz := len(ss) * int(t.Size())
for _, s := range ss {
sz += len(s)
}
b.addArraySize(sz, len(ss))
b.pf(`var %s = [%d]%s{`, name, len(ss), t)
for i := 0; i < len(ss); i++ {
b.pf("\t%q,", ss[i])
}
b.p("}")
}
func (b *builder) writeString(name, s string) {
b.comment(name)
b.addSize(len(s) + int(reflect.TypeOf(s).Size()))
if len(s) < 40 {
b.pf(`var %s string = %q`, name, s)
return
}
const cpl = 60
b.pf(`var %s string = "" +`, name)
for {
n := cpl
if n > len(s) {
n = len(s)
}
var q string
for {
q = strconv.Quote(s[:n])
if len(q) <= cpl+2 {
break
}
n--
}
if n < len(s) {
b.pf(` %s +`, q)
s = s[n:]
} else {
b.pf(` %s`, q)
break
}
}
}
const base = 'z' - 'a' + 1
func strToInt(s string) uint {
v := uint(0)
for i := 0; i < len(s); i++ {
v *= base
v += uint(s[i] - 'a')
}
return v
}
func (b *builder) writeBitVector(name string, ss []string) {
vec := make([]uint8, int(math.Ceil(math.Pow(base, float64(len(ss[0])))/8)))
for _, s := range ss {
v := strToInt(s)
vec[v/8] |= 1 << (v % 8)
}
b.writeSlice(name, vec)
}
// TODO: convert this type into a list or two-stage trie.
func (b *builder) writeMapFunc(name string, m map[string]string, f func(string) uint16) {
b.comment(name)
v := reflect.ValueOf(m)
sz := v.Len() * (2 + int(v.Type().Key().Size()))
for _, k := range m {
sz += len(k)
}
b.addSize(sz)
keys := []string{}
b.pf(`var %s = map[string]uint16{`, name)
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
b.pf("\t%q: %v,", k, f(m[k]))
}
b.p("}")
}
func (b *builder) langIndex(s string) uint16 {
if i, ok := b.lang.find(s); ok {
return uint16(i)
}
return uint16(strToInt(s)) + uint16(len(b.lang.s))
}
// inc advances the string to its lexicographical successor.
func inc(s string) string {
i := len(s) - 1
for ; s[i]+1 > 'z'; i-- {
}
return fmt.Sprintf("%s%s%s", s[:i], string(s[i]+1), s[i+1:])
}
func (b *builder) parseIndices() {
meta := b.supp.Metadata
for k, v := range b.registry {
var ss *stringSet
switch v.typ {
case "language":
if len(k) == 2 || v.suppressScript != "" || v.scope == "special" {
b.lang.add(k)
continue
} else {
ss = &b.langNoIndex
}
case "region":
ss = &b.region
case "script":
ss = &b.script
default:
continue
}
if s := strings.SplitN(k, "..", 2); len(s) > 1 {
for a := s[0]; a <= s[1]; a = inc(a) {
ss.add(a)
}
} else {
ss.add(k)
}
}
// currency codes
for _, reg := range b.supp.CurrencyData.Region {
for _, cur := range reg.Currency {
b.currency.add(cur.Iso4217)
}
}
// common locales
b.locale.parse(meta.DefaultContent.Locales)
}
// writeLanguage generates all tables needed for language canonicalization.
func (b *builder) writeLanguage() {
meta := b.supp.Metadata
b.writeConst("unknownLang", b.lang.index("und"))
// Get language codes that need to be mapped (overlong 3-letter codes, deprecated
// 2-letter codes and grandfathered tags.
langOldMap := stringSet{}
// Mappings for macro languages
langMacroMap := stringSet{}
// altLangISO3 get the alternative ISO3 names that need to be mapped.
altLangISO3 := stringSet{}
// legacyTag maps from tag to language code.
legacyTag := make(map[string]string)
lang := b.lang.clone()
for _, a := range meta.Alias.LanguageAlias {
if a.Replacement == "" {
a.Replacement = "und"
}
// TODO: support mapping to tags
repl := strings.SplitN(a.Replacement, "_", 2)[0]
if a.Reason == "overlong" {
if len(a.Replacement) == 2 && len(a.Type) == 3 {
lang.updateLater(a.Replacement, a.Type)
}
} else if len(a.Type) <= 3 {
if a.Reason != "deprecated" {
langMacroMap.add(a.Type)
langMacroMap.updateLater(a.Type, repl)
}
} else {
legacyTag[strings.Replace(a.Type, "_", "-", -1)] = repl
}
}
for k, v := range b.registry {
// Also add deprecated values for 3-letter ISO codes, which CLDR omits.
if v.typ == "language" && v.deprecated != "" && v.preferred != "" {
langOldMap.add(k)
langOldMap.updateLater(k, v.preferred)
}
}
// Fix CLDR mappings.
lang.updateLater("tl", "tgl")
lang.updateLater("sh", "hbs")
lang.updateLater("mo", "mol")
lang.updateLater("no", "nor")
lang.updateLater("tw", "twi")
lang.updateLater("nb", "nob")
lang.updateLater("ak", "aka")
// Ensure that each 2-letter code is matched with a 3-letter code.
for _, v := range lang.s {
s, ok := lang.update[v]
if !ok {
if s, ok = lang.update[langOldMap.update[v]]; !ok {
continue
}
lang.update[v] = s
}
if v[0] != s[0] {
altLangISO3.add(s)
altLangISO3.updateLater(s, v)
}
}
// Complete canonialized language tags.
lang.freeze()
for i, v := range lang.s {
// We can avoid these manual entries by using the IANI registry directly.
// Seems easier to update the list manually, as changes are rare.
// The panic in this loop will trigger if we miss an entry.
add := ""
if s, ok := lang.update[v]; ok {
if s[0] == v[0] {
add = s[1:]
} else {
add = string([]byte{0, byte(altLangISO3.index(s))})
}
} else if len(v) == 3 {
add = "\x00"
} else {
log.Panicf("no data for long form of %q", v)
}
lang.s[i] += add
}
b.writeString("lang", lang.join())
b.writeConst("langNoIndexOffset", len(b.lang.s))
// space of all valid 3-letter language identifiers.
b.writeBitVector("langNoIndex", b.langNoIndex.slice())
for i, s := range altLangISO3.slice() {
idx := b.lang.index(altLangISO3.update[s])
altLangISO3.s[i] += string([]byte{byte(idx)})
}
b.writeString("altLangISO3", altLangISO3.join())
makeMap := func(name string, ss *stringSet) {
ss.sortFunc(func(i, j string) bool {
return b.langIndex(i) < b.langIndex(j)
})
m := []struct{ from, to uint16 }{}
for _, s := range ss.s {
m = append(m, struct{ from, to uint16 }{
b.langIndex(s),
b.langIndex(ss.update[s]),
})
}
b.writeSlice(name, m)
}
makeMap("langOldMap", &langOldMap)
makeMap("langMacroMap", &langMacroMap)
b.writeMapFunc("tagAlias", legacyTag, func(s string) uint16 {
return uint16(b.langIndex(s))
})
}
func (b *builder) writeScript() {
unknown := uint8(b.script.index("Zzzz"))
b.writeConst("unknownScript", unknown)
b.writeString("script", b.script.join())
supp := make([]uint8, len(b.lang.slice()))
for i, v := range b.lang.slice() {
supp[i] = unknown
if sc := b.registry[v].suppressScript; sc != "" {
supp[i] = uint8(b.script.index(sc))
}
}
b.writeSlice("suppressScript", supp)
}
func parseM49(s string) uint16 {
if len(s) == 0 {
return 0
}
v, err := strconv.ParseUint(s, 10, 10)
failOnError(err)
return uint16(v)
}
func (b *builder) writeRegion() {
b.writeConst("unknownRegion", b.region.index("ZZ"))
isoOffset := b.region.index("AA")
m49map := make([]uint16, len(b.region.slice()))
altRegionISO3 := ""
altRegionIDs := []uint16{}
b.writeConst("isoRegionOffset", isoOffset)
// 2-letter region lookup and mapping to numeric codes.
regionISO := b.region.clone()
regionISO.s = regionISO.s[isoOffset:]
regionISO.sorted = false
for _, tc := range b.supp.CodeMappings.TerritoryCodes {
i := regionISO.index(tc.Type)
if len(tc.Alpha3) == 3 {
if tc.Alpha3[0] == tc.Type[0] {
regionISO.s[i] += tc.Alpha3[1:]
} else {
regionISO.s[i] += string([]byte{0, byte(len(altRegionISO3))})
altRegionISO3 += tc.Alpha3
altRegionIDs = append(altRegionIDs, uint16(isoOffset+i))
}
}
if d := m49map[isoOffset+i]; d != 0 {
log.Panicf("%s found as a duplicate UN.M49 code of %03d", tc.Numeric, d)
}
m49map[isoOffset+i] = parseM49(tc.Numeric)
}
for i, s := range regionISO.s {
if len(s) != 4 {
regionISO.s[i] = s + " "
}
}
b.writeString("regionISO", regionISO.join())
b.writeString("altRegionISO3", altRegionISO3)
b.writeSlice("altRegionIDs", altRegionIDs)
// 3-digit region lookup, groupings.
for i := 0; i < isoOffset; i++ {
m49map[i] = parseM49(b.region.s[i])
}
b.writeSlice("m49", m49map)
}
func (b *builder) writeLocale() {
b.writeStringSlice("locale", b.locale.slice())
}
func (b *builder) writeLanguageInfo() {
}
func (b *builder) writeCurrencies() {
unknown := b.currency.index("XXX")
digits := map[string]uint64{}
rounding := map[string]uint64{}
for _, info := range b.supp.CurrencyData.Fractions[0].Info {
var err error
digits[info.Iso4217], err = strconv.ParseUint(info.Digits, 10, 2)
failOnError(err)
rounding[info.Iso4217], err = strconv.ParseUint(info.Rounding, 10, 6)
failOnError(err)
}
for i, cur := range b.currency.slice() {
d := uint64(2) // default number of decimal positions
if dd, ok := digits[cur]; ok {
d = dd
}
var r uint64
if r = rounding[cur]; r == 0 {
r = 1 // default rounding increment in units 10^{-digits)
}
b.currency.s[i] += string([]byte{byte(r<<2 + d)})
}
b.writeString("currency", b.currency.join())
// Hack alert: gofmt indents a trailing comment after an indented string.
// Write this constant after currency to force a proper indentation of
// the final comment.
b.writeConst("unknownCurrency", unknown)
}
var header = `// Generated by running
// maketables -url=%s -iana=%s
// DO NOT EDIT
package locale
`
func main() {
flag.Parse()
b := newBuilder()
fmt.Fprintf(b.out, header, *url, *iana)
b.parseIndices()
b.writeLanguage()
b.writeScript()
b.writeRegion()
// TODO: b.writeLocale()
b.writeCurrencies()
fmt.Fprintf(b.out, "\n// Size: %.1fK (%d bytes); Check: %X\n", float32(b.size)/1024, b.size, b.hash32.Sum32())
}