/
main.go
1913 lines (1720 loc) · 48.7 KB
/
main.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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 Charlie Vieth. All rights reserved.
// Use of this source code is governed by the MIT license.
// gen generates the Unicode lookup tables used by strcase. The tables must
// be regenerated if this code is changed (`go generate`).
package main
import (
"bytes"
"cmp"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"go/format"
"log"
"math"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"runtime/pprof"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"github.com/schollz/progressbar/v3"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"golang.org/x/term"
"golang.org/x/text/unicode/rangetable"
"github.com/charlievieth/strcase/internal/gen/gen"
"github.com/charlievieth/strcase/internal/gen/ucd"
"github.com/charlievieth/strcase/internal/gen/util"
)
func init() {
initLogs()
// If $GOMAXPROCS isn't set, use the full capacity of the machine.
// For small machines, use at least 4 threads.
if os.Getenv("GOMAXPROCS") == "" {
n := runtime.NumCPU()
if n < 4 {
n = 4
}
runtime.GOMAXPROCS(n)
}
}
func initLogs() {
log.SetPrefix("")
log.SetFlags(log.Lshortfile)
log.SetOutput(os.Stdout) // use stdout instead of stderr
}
// WARN: we need to include 'İ' (0x0130) and 'ı' (0x0131) in _FoldMap because
// we don't want to fallback to using toUpperLower() since we don't accept the
// upper/lower-case variants of these runes (breaks simple folding semantics).
//
// We should remove these runes and any other runes in _FoldMap from _UpperLower
// and maybe remove 'İ' and 'ı' from _FoldMap as well.
//
// TODO: remove İ (0x0130) from _UpperLower and fix tests
// TODO: consider renaming the generated tables
const (
MaxChar = 0x10FFFF
caseFoldShift = 19
caseFoldSize = 8192
foldMapShift = 24
foldMapSize = 256
upperLowerTableSize = 8192
upperLowerTableShift = 19
)
const (
GenCookieKey = "b3d53e54921be5a951563a7e77bfcb1a"
GenCookieValue = "c1bbb5805a8c389e0dd50234d5c38cce"
)
type foldPair struct {
From uint32
To uint32
}
var (
categories *unicode.RangeTable
caseFolds []foldPair
caseRanges []unicode.CaseRange // used by toLower and toUpper
caseOrbit []foldPair // used by simpleFold
asciiFold [unicode.MaxASCII + 1]uint16
)
var (
chars = make([]Char, MaxChar+1)
scripts = make(map[string][]rune)
props = make(map[string][]rune) // a property looks like a script; can share the format
)
// TODO: move
func loadCaseFolds() {
ucd.Parse(gen.OpenUCDFile("CaseFolding.txt"), func(p *ucd.Parser) {
kind := p.String(1)
if kind != "C" && kind != "S" {
// Only care about 'common' and 'simple' foldings.
return
}
p1 := p.Rune(0)
p2 := p.Rune(2)
caseFolds = append(caseFolds, foldPair{uint32(p1), uint32(p2)})
chars[p1].foldCase = p2
})
slices.SortFunc(caseFolds, func(a, b foldPair) int {
return cmp.Compare(a.From, b.From)
})
}
var buildTags = map[string]struct{ version, buildTags, filename string }{
"13.0.0": {"13.0.0", "go1.16,!go1.21", "tables_go116.go"},
"15.0.0": {"15.0.0", "go1.21", "tables_go121.go"},
}
// tablesFileName is the names of the file to generate and is based off
// of the Go version this program is ran with.
//
// WARN: this must be called after command line flags are parsed
func tablesFileName(dirname string) string {
// gen.UnicodeVersion is set by the "-unicode" flag
if name := buildTags[gen.UnicodeVersion()].filename; name != "" {
return filepath.Join(dirname, name)
}
log.Panicf("unsupported Unicode version %q this script might need "+
"to be updated", gen.UnicodeVersion())
panic("unreachable")
}
type span struct {
Start, End int64
}
func generateSpans(start, end, delta int64) []span {
maxEnd := end
var spans []span
for i := start; i <= end; i += delta {
end := i + delta
if end >= maxEnd {
end = maxEnd
}
spans = append(spans, span{Start: i, End: end})
}
// Reverse spans since larger values are more likely to be better seeds.
// We previously randomly shuffled the spans, but led to non-deterministic
// behavior when more than one seed was ideal.
for i := len(spans)/2 - 1; i >= 0; i-- {
opp := len(spans) - 1 - i
spans[i], spans[opp] = spans[opp], spans[i]
}
return spans
}
func hash(seed, key, shift uint32) uint32 {
m := seed * key
return m >> shift
}
func shiftHash(seed, key, shift uint32) uint32 {
key |= key << 24 // fill top bits not occupied by unicode.MaxRune
m := seed * key
return m >> shift
}
type HashConfig struct {
TableName string
TableSize int
HashShift uint32 // TODO: this can be calculated from TableSize
// TODO: name is confusing with HashShift
ShiftHash bool // Use shiftHash instead of hash
// Use the first valid hash value instead of performing an exhaustive
// search to find the "best" hash seed. The seed is not deterministic
// and this is only meant for testing since it is much much faster.
FirstValidHash bool
}
var hashSeedCache = map[string]uint32{}
func cacheKey(inputs []uint32) string {
if !slices.IsSorted(inputs) {
slices.Sort(inputs)
}
b := make([]byte, len(inputs)*4)
for i, u := range inputs {
binary.LittleEndian.PutUint32(b[i*4:], u)
}
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:])
}
// TODO:
// - Return the first working hash value.
// - Find a better algorithm.
//
// GenerateHashValues performs a brute-force search for the best possible
// multiplicative hash seed for inputs. All uint32 values are checked.
func (conf *HashConfig) GenerateHashValues(inputs []uint32) (hashSeed uint32) {
const delta = 512 * 1024
if *useCachedSeeds {
if seed, ok := tableInfo.TableHashes[conf.TableName]; ok {
log.Printf("WARN: using cached seed %d for table: %s", seed, conf.TableName)
return seed
}
}
if seed, ok := hashSeedCache[cacheKey(inputs)]; ok {
log.Printf("Using previously computed seed (0x%04X) for the %s table",
seed, conf.TableName)
tableInfo.TableHashes[conf.TableName] = seed
return seed
}
if slices.IndexFunc(inputs, func(u uint32) bool { return u != 0 }) < 0 {
log.Panicf("Input is all zeros for table: %s", conf.TableName)
}
log.Printf("Generating values for the %s table (this may take a long time)...\n",
conf.TableName)
// This can take awhile so use a progress bar.
var bar *progressbar.ProgressBar
if term.IsTerminal(int(os.Stdout.Fd())) {
bar = progressbar.Default(math.MaxUint32)
} else {
bar = progressbar.DefaultSilent(math.MaxUint32)
}
start := time.Now()
// TODO: set GOMAXPROCS to NumCPU ??
numProcs := runtime.GOMAXPROCS(0)
// When FirstValidHash we exit before consuming all spans.
done := make(chan struct{})
defer close(done)
ch := make(chan *span, numProcs*2)
go func() {
spans := generateSpans(1, math.MaxUint32, delta)
for i := range spans {
select {
case ch <- &spans[i]:
case <-done:
return
}
}
close(ch)
}()
var (
bestIndex = int64(math.MaxInt64)
bestSeed uint32
foundSeed atomic.Bool
mu sync.Mutex
wg sync.WaitGroup
)
if seed := tableInfo.TableHashes[conf.TableName]; seed != 0 {
bestSeed = seed
}
for i := 0; i < numProcs; i++ {
wg.Add(1)
go func(inputs []uint32) {
defer wg.Done()
seen := make([]bool, conf.TableSize)
for sp := range ch {
if foundSeed.Load() {
return
}
best := atomic.LoadInt64(&bestIndex)
Loop:
for i := sp.Start; i <= sp.End && best >= int64(len(inputs)); i++ {
for i := range seen {
seen[i] = false // TODO: zero
}
// TODO: load more often
if i%8192 == 0 {
best = atomic.LoadInt64(&bestIndex)
}
var maxIdx int64
shift := conf.HashShift
seed := uint32(i)
useShiftHash := conf.ShiftHash
// TODO: is there anyway we can optimize this?
for _, x := range inputs {
var u int64
if useShiftHash {
u = int64(shiftHash(seed, x, shift))
} else {
u = int64(hash(seed, x, shift))
}
if u > best || seen[u] {
continue Loop
}
seen[u] = true
if u > maxIdx {
maxIdx = u
}
}
best = atomic.LoadInt64(&bestIndex)
if maxIdx < best {
// Use mutex to simplify updating both values
mu.Lock()
best = atomic.LoadInt64(&bestIndex) // re-check
if maxIdx < best {
atomic.StoreInt64(&bestIndex, maxIdx)
atomic.StoreUint32(&bestSeed, seed)
// Stop at the first valid has
if conf.FirstValidHash && foundSeed.CompareAndSwap(false, true) {
log.Println("WARN: -first-valid-hash flag provided: stopping early")
mu.Unlock()
return
}
}
mu.Unlock()
}
}
// TODO: figure out is we need to use `1 + sp.End - sp.Start`
if err := bar.Add64(sp.End - sp.Start); err != nil {
max := bar.GetMax64()
log.Panicf("error updating progress bar: %v: max: %d delta: %d",
err, max, 1+sp.End-sp.Start)
}
}
}(inputs)
}
wg.Wait()
bar.Close()
// TODO: we can probably just check bestSeed
if bestIndex == math.MaxInt64 || bestSeed == 0 {
log.Panicf("Failed to generate hash values for %s table: max_index: %d seed: %d",
conf.TableName, bestIndex, bestSeed)
}
if bestIndex <= int64(conf.TableSize/2) {
// Error if the algorithm found a table size that is a smaller power of 2
log.Panicf("The hash table size can be reduced to %d or less. The best index is: %d.",
conf.TableSize/2, bestIndex)
}
log.Printf("Successfully generated %s values in: %s\n"+
" max_index: %d\n"+
" seed: %d\n",
conf.TableName, time.Since(start), bestIndex, bestSeed)
// log.Printf("Successfully generated %s values in: %s", conf.TableName, time.Since(start))
// log.Printf(" max_index: %d", bestIndex)
// log.Printf(" seed: %d", bestSeed)
hashSeedCache[cacheKey(inputs)] = bestSeed // Cache result
tableInfo.TableHashes[conf.TableName] = bestSeed
return bestSeed
}
const (
CaseUpper = 1 << iota
CaseLower
CaseTitle
CaseNone = 0 // must be zero
CaseMissing = -1 // character not present; not a valid case state
)
type caseState struct {
point rune
_case int
deltaToUpper rune
deltaToLower rune
deltaToTitle rune
}
// Is d a continuation of the state of c?
func (c *caseState) adjacent(d *caseState) bool {
if d.point < c.point {
c, d = d, c
}
switch {
case d.point != c.point+1: // code points not adjacent (shouldn't happen)
return false
case d._case != c._case: // different cases
return c.upperLowerAdjacent(d)
case c._case == CaseNone:
return false
case c._case == CaseMissing:
return false
case d.deltaToUpper != c.deltaToUpper:
return false
case d.deltaToLower != c.deltaToLower:
return false
case d.deltaToTitle != c.deltaToTitle:
return false
}
return true
}
// Is d the same as c, but opposite in upper/lower case? this would make it
// an element of an UpperLower sequence.
func (c *caseState) upperLowerAdjacent(d *caseState) bool {
// check they're a matched case pair. we know they have adjacent values
switch {
case c._case == CaseUpper && d._case != CaseLower:
return false
case c._case == CaseLower && d._case != CaseUpper:
return false
}
// matched pair (at least in upper/lower). make the order Upper Lower
if c._case == CaseLower {
c, d = d, c
}
// for an Upper Lower sequence the deltas have to be in order
// c: 0 1 0
// d: -1 0 -1
switch {
case c.deltaToUpper != 0:
return false
case c.deltaToLower != 1:
return false
case c.deltaToTitle != 0:
return false
case d.deltaToUpper != -1:
return false
case d.deltaToLower != 0:
return false
case d.deltaToTitle != -1:
return false
}
return true
}
// Does this character start an UpperLower sequence?
func (c *caseState) isUpperLower() bool {
// for an Upper Lower sequence the deltas have to be in order
// c: 0 1 0
switch {
case c.deltaToUpper != 0:
return false
case c.deltaToLower != 1:
return false
case c.deltaToTitle != 0:
return false
}
return true
}
// Does this character start a LowerUpper sequence?
func (c *caseState) isLowerUpper() bool {
// for an Upper Lower sequence the deltas have to be in order
// c: -1 0 -1
switch {
case c.deltaToUpper != -1:
return false
case c.deltaToLower != 0:
return false
case c.deltaToTitle != -1:
return false
}
return true
}
func getCaseState(i rune) (c *caseState) {
c = &caseState{point: i, _case: CaseNone}
ch := &chars[i]
switch ch.codePoint {
case 0:
c._case = CaseMissing // Will get NUL wrong but that doesn't matter
return
case ch.upperCase:
c._case = CaseUpper
case ch.lowerCase:
c._case = CaseLower
case ch.titleCase:
c._case = CaseTitle
}
// Some things such as roman numeral U+2161 don't describe themselves
// as upper case, but have a lower case. Second-guess them.
if c._case == CaseNone && ch.lowerCase != 0 {
c._case = CaseUpper
}
// Same in the other direction.
if c._case == CaseNone && ch.upperCase != 0 {
c._case = CaseLower
}
if ch.upperCase != 0 {
c.deltaToUpper = ch.upperCase - i
}
if ch.lowerCase != 0 {
c.deltaToLower = ch.lowerCase - i
}
if ch.titleCase != 0 {
c.deltaToTitle = ch.titleCase - i
}
return
}
// TODO: we need to do this since we can't use the [unicode] package due to
// a version mismatch between the Unicode version we're generating for and
// Unicode version of Go version being used to generate this.
//
// TODO: fixup the above comment.
func generateCaseRanges() []unicode.CaseRange {
if gen.UnicodeVersion() == unicode.Version {
return unicode.CaseRanges
}
// The requested Unicode version does not match the stdlibs
var (
cases []unicode.CaseRange
startState *caseState // the start of a run; nil for not active
prevState = &caseState{} // the state of the previous character
)
for i := range chars {
state := getCaseState(rune(i))
if state.adjacent(prevState) {
prevState = state
continue
}
// end of run (possibly)
if c, ok := getCaseRange(startState, prevState); ok {
cases = append(cases, c)
}
// printCaseRange(startState, prevState)
startState = nil
if state._case != CaseMissing && state._case != CaseNone {
startState = state
}
prevState = state
}
return cases
}
// Modified version of golang.org/x/text/internal/export/unicode.printCaseRange
func getCaseRange(lo, hi *caseState) (unicode.CaseRange, bool) {
if lo == nil {
return unicode.CaseRange{}, false
}
if lo.deltaToUpper == 0 && lo.deltaToLower == 0 && lo.deltaToTitle == 0 {
// character represents itself in all cases - no need to mention it
return unicode.CaseRange{}, false
}
switch {
case hi.point > lo.point && lo.isUpperLower():
c := unicode.CaseRange{
Lo: uint32(lo.point),
Hi: uint32(hi.point),
Delta: [unicode.MaxCase]rune{
unicode.UpperLower,
unicode.UpperLower,
unicode.UpperLower,
},
}
return c, true
case hi.point > lo.point && lo.isLowerUpper():
log.Panicf("LowerUpper sequence: should not happen: %U. "+
"If it's real, need to fix To()", lo.point)
default:
c := unicode.CaseRange{
Lo: uint32(lo.point),
Hi: uint32(hi.point),
Delta: [unicode.MaxCase]rune{
lo.deltaToUpper,
lo.deltaToLower,
lo.deltaToTitle,
},
}
return c, true
}
return unicode.CaseRange{}, false
}
// simpleFold is the same as unicode.SimpleFold but uses the version of Unicode
// we loaded.
func simpleFold(r rune) rune {
if r < 0 || r > unicode.MaxRune {
return r
}
if int(r) < len(asciiFold) {
return rune(asciiFold[r])
}
// Consult caseOrbit table for special cases.
lo := 0
hi := len(caseOrbit)
for lo < hi {
m := lo + (hi-lo)/2
if rune(caseOrbit[m].From) < r {
lo = m + 1
} else {
hi = m
}
}
if lo < len(caseOrbit) && rune(caseOrbit[lo].From) == r {
return rune(caseOrbit[lo].To)
}
// No folding specified. This is a one- or two-element
// equivalence class containing rune and ToLower(rune)
// and ToUpper(rune) if they are different from rune.
if l := toLower(r); l != r {
return l
}
return toUpper(r)
}
// to maps the rune using the specified case mapping.
// It additionally reports whether caseRange contained a mapping for r.
func to(_case int, r rune, caseRange []unicode.CaseRange) (mappedRune rune) {
if len(caseRange) == 0 {
panic("empty caseRange")
}
if _case < 0 || unicode.MaxCase <= _case {
return unicode.ReplacementChar // as reasonable an error as any
}
// binary search over ranges
lo := 0
hi := len(caseRange)
for lo < hi {
m := lo + (hi-lo)/2
cr := caseRange[m]
if rune(cr.Lo) <= r && r <= rune(cr.Hi) {
delta := cr.Delta[_case]
if delta > unicode.MaxRune {
// In an Upper-Lower sequence, which always starts with
// an UpperCase letter, the real deltas always look like:
// {0, 1, 0} UpperCase (Lower is next)
// {-1, 0, -1} LowerCase (Upper, Title are previous)
// The characters at even offsets from the beginning of the
// sequence are upper case; the ones at odd offsets are lower.
// The correct mapping can be done by clearing or setting the low
// bit in the sequence offset.
// The constants UpperCase and TitleCase are even while LowerCase
// is odd so we take the low bit from _case.
return rune(cr.Lo) + ((r-rune(cr.Lo))&^1 | rune(_case&1))
}
return r + delta
}
if r < rune(cr.Lo) {
hi = m
} else {
lo = m + 1
}
}
return r
}
// toUpper is the same as unicode.ToUpper but uses the Unicode table we loaded.
func toUpper(r rune) rune {
if r <= unicode.MaxASCII {
if 'a' <= r && r <= 'z' {
r -= 'a' - 'A'
}
return r
}
return to(unicode.UpperCase, r, caseRanges)
}
// toLower is the same as unicode.ToLower but uses the Unicode table we loaded.
func toLower(r rune) rune {
if r <= unicode.MaxASCII {
if 'A' <= r && r <= 'Z' {
r += 'a' - 'A'
}
return r
}
return to(unicode.LowerCase, r, caseRanges)
}
func folds(sr rune) []rune {
r := simpleFold(sr)
runes := make([]rune, 1, 2)
runes[0] = sr
for r != sr {
runes = append(runes, r)
r = simpleFold(r)
}
return runes
}
func genCaseFolds(w *bytes.Buffer, firstValidHash bool) {
folds := caseFolds
inputs := make([]uint32, len(folds))
for i, p := range folds {
inputs[i] = p.From
}
conf := HashConfig{
TableName: "_CaseFolds",
TableSize: caseFoldSize,
HashShift: caseFoldShift,
FirstValidHash: firstValidHash,
}
seed := conf.GenerateHashValues(inputs)
// TODO: probably don't need this
pairs := make([]foldPair, len(folds))
copy(pairs, folds)
slices.SortFunc(pairs, func(a, b foldPair) int {
return cmp.Compare(a.From, b.From)
})
hashes := make([]foldPair, 0, len(pairs))
for i, p := range pairs {
hashes = append(hashes, foldPair{
From: hash(p.From, seed, caseFoldShift),
To: uint32(i),
})
}
slices.SortFunc(hashes, func(a, b foldPair) int {
return cmp.Compare(a.From, b.From)
})
fmt.Fprint(w, "\n")
fmt.Fprintf(w, "const _CaseFoldsSeed = 0x%04X\n", seed)
fmt.Fprintf(w, "const _CaseFoldsShift = %d\n", caseFoldShift)
fmt.Fprint(w, "\n")
fmt.Fprintln(w, "// _CaseFolds stores all Unicode simple case-folds.")
fmt.Fprintf(w, "var _CaseFolds = [%d]foldPair{\n", caseFoldSize)
for _, h := range hashes {
p := pairs[h.To]
fmt.Fprintf(w, "\t%d: {0x%04X, 0x%04X}, // %q => %q\n", h.From, p.From, p.To, p.From, p.To)
}
fmt.Fprint(w, "}\n\n")
}
func dedupe(r []rune) []rune {
if len(r) < 2 {
return r
}
slices.Sort(r)
return slices.Compact(r)
}
// TODO: consider renaming this table
func genFoldTable(w *bytes.Buffer, firstValidHash bool) {
runes := make(map[rune][]rune)
rangetable.Visit(categories, func(r rune) {
ff := folds(r)
if len(ff) > 2 {
runes[r] = append(runes[r], ff...)
}
if len(ff) == 1 && toUpper(r) != toLower(r) {
runes[r] = append(runes[r], ff...)
}
})
// FIXME: fix the below since we have to work around it in the code
// WARN: we should not need to add this manually
runes['İ'] = append(runes['İ'], 'İ')
runes['ß'] = append(runes['ß'], 'ẞ')
keys := make([]uint32, 0, len(runes))
for k, rs := range runes {
// Make sure the key is included (was an issue with: 'ß')
if !slices.Contains(rs, k) {
rs = append(rs, k)
}
runes[k] = dedupe(rs)
keys = append(keys, uint32(k))
}
conf := HashConfig{
TableName: "_FoldMap",
TableSize: foldMapSize,
HashShift: foldMapShift,
FirstValidHash: firstValidHash,
}
seed := conf.GenerateHashValues(keys)
// Make key the first element of the rune slice
folds := make([][]rune, 0, len(runes))
for k, rs := range runes {
if rs[0] != k {
a := []rune{k}
for _, r := range rs {
if r != k {
a = append(a, r)
}
}
rs = a
}
folds = append(folds, rs)
}
slices.SortFunc(folds, func(f1, f2 []rune) int {
return cmp.Compare(f1[0], f2[0])
})
fmt.Fprint(w, "\n")
fmt.Fprintf(w, "const _FoldMapSeed = 0x%04X\n", seed)
fmt.Fprintf(w, "const _FoldMapShift = %d\n", foldMapShift)
fmt.Fprint(w, "\n")
fmt.Fprintln(w, "// _FoldMap stores the Unicode case-folds for characters "+
"that have two or more folds.")
fmt.Fprintf(w, "var _FoldMap = [%d][4]uint16{\n", foldMapSize)
for _, ff := range folds {
fmt.Fprintf(w, "\t%d: {0x%04X", hash(uint32(ff[0]), seed, foldMapShift), ff[0])
for _, f := range ff[1:] {
fmt.Fprintf(w, ", 0x%04X", f)
}
fmt.Fprintf(w, "}, // %q\n", ff)
}
fmt.Fprint(w, "}\n\n")
type runeSet struct {
r uint32
a [2]rune
}
var noUpperLower []runeSet
for k, rs := range runes {
u := toUpper(k)
l := toLower(k)
a := make([]rune, 0, 2)
for _, r := range rs {
if r != u && r != l {
a = append(a, r)
}
}
if len(a) > 2 {
log.Fatalf("fold set excluding upper/lower %q "+
"must have 2 or less elements got: %d", a, len(a))
}
switch len(a) {
case 0:
a = append(a, k, k)
case 1:
a = append(a, a[0])
}
slices.Sort(a)
noUpperLower = append(noUpperLower, runeSet{uint32(k), [2]rune{a[0], a[1]}})
}
slices.SortFunc(noUpperLower, func(c1, c2 runeSet) int {
return cmp.Compare(c1.r, c2.r)
})
const foldMapExcludingUpperLowerComment = `
// _FoldMapExcludingUpperLower stores the Unicode case-folds for charactecrs that
// have two or more folds, but excludes the uppercase and lowercase forms of the
// character.`
fmt.Fprintln(w, "")
fmt.Fprintf(w, "const _FoldMapExcludingUpperLowerSeed = 0x%04X\n", seed)
fmt.Fprintf(w, "const _FoldMapExcludingUpperLowerShift = %d\n", foldMapShift)
fmt.Fprintln(w, "")
fmt.Fprintln(w, foldMapExcludingUpperLowerComment)
fmt.Fprintf(w, "var _FoldMapExcludingUpperLower = [%d]struct {\n", foldMapSize)
fmt.Fprintln(w, "\tr uint16")
fmt.Fprintln(w, "\ta [2]uint16")
fmt.Fprintln(w, "}{")
for _, c := range noUpperLower {
h := hash(c.r, seed, foldMapShift)
if c.a[0] > math.MaxUint16 {
log.Fatalf("rune 0x%04X is larger than MaxUint16 0x%04X", c.a[0], math.MaxUint16)
}
if c.a[1] > math.MaxUint16 {
log.Fatalf("rune 0x%04X is larger than MaxUint16 0x%04X", c.a[1], math.MaxUint16)
}
fmt.Fprintf(w, "\t%d: {0x%04X, [2]uint16{0x%04X, 0x%04X}}, // %q: [%q, %q]\n",
h, c.r, c.a[0], c.a[1], c.r, c.a[0], c.a[1])
}
fmt.Fprint(w, "}\n\n")
}
func genUpperLowerTable(w *bytes.Buffer, firstValidHash bool) {
// WARN: attempt to use caseOrbit so that we don't have to handle special
// cases with toUpperLowerSpecial.
const docComment = `
// _UpperLower stores upper/lower case pairs of Unicode code points.
// This takes up more space than the stdlib's "unicode" package, but
// is roughly ~4x faster.`
type Case struct {
Rune rune `json:"rune"`
Upper rune `json:"upper"`
Lower rune `json:"lower"`
}
var cases []Case
// special cases where Rune != Upper or Lower
var special []Case
for r := rune('A'); r <= unicode.MaxRune; r++ {
if r <= unicode.MaxASCII {
continue
}
l := toLower(r)
u := toUpper(r)
if r != l || r != u {
if r == l || r == u {
cases = append(cases, Case{Rune: r, Upper: u, Lower: l})
} else {
special = append(special, Case{Rune: r, Upper: u, Lower: l})
}
}
}
keys := make([]uint32, len(cases))
for i, c := range cases {
keys[i] = uint32(c.Rune)
}
// TODO: this is probably not necessary
slices.Sort(keys)
keys = slices.Compact(keys)
conf := HashConfig{
TableName: "_UpperLower",
TableSize: upperLowerTableSize,
HashShift: upperLowerTableShift,
ShiftHash: true,
FirstValidHash: firstValidHash,
}
seed := conf.GenerateHashValues(keys)
fmt.Fprint(w, "\n")
fmt.Fprintf(w, "const _UpperLowerSeed = 0x%04X\n", seed)
fmt.Fprintf(w, "const _UpperLowerShift = %d\n", upperLowerTableShift)
fmt.Fprint(w, "\n")
fmt.Fprintln(w, strings.TrimSpace(docComment))
fmt.Fprintf(w, "var _UpperLower = [%d][2]uint32{\n", upperLowerTableSize)
for _, c := range cases {
fmt.Fprintf(w, "\t%d: {0x%04X, 0x%04X}, // %q => %q\n",
shiftHash(seed, uint32(c.Rune), upperLowerTableShift), c.Upper, c.Lower, c.Upper, c.Lower)
}
fmt.Fprint(w, "}\n\n")
slices.SortFunc(special, func(c1, c2 Case) int {
return cmp.Compare(c1.Rune, c2.Rune)
})
fmt.Fprintln(w, `
// toUpperLowerSpecial returns the uppercase and lowercase form of r,
// which is a character that is not equal to either its uppercase or
// lowercase form and thus cannot be mapped into the _UpperLower table.
func toUpperLowerSpecial(r rune) (rune, rune, bool) {
switch r {`)
for _, c := range special {
fmt.Fprintf(w, "\tcase %q:\n", c.Rune)
fmt.Fprintf(w, "\t\treturn %q, %q, %t\n", c.Upper, c.Lower, true)
}
fmt.Fprintln(w, "\t}")
fmt.Fprintln(w, "\treturn r, r, false")
fmt.Fprintln(w, "}")
}
func writeInitGuard(w *bytes.Buffer) {
const s = `
func init() {
// This is essentially a compile time assertion that can only fail if a
// future Go release updates the version of Unicode it supports.
//
// TLDR: https://github.com/charlievieth/strcase/issues
if UnicodeVersion != unicode.Version {
panic("strcase.UnicodeVersion \"" + UnicodeVersion +
"\" != unicode.Version \"" + unicode.Version + "\"")
}
}
`
w.WriteString(s)
}
func runCommand(dir string, args ...string) {
cmd := exec.Command("go", args...)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error: %v", err)
log.Printf("Command: %s", strings.Join(cmd.Args, " "))
log.Printf("Output: %s", bytes.TrimSpace(out))
log.Panicf("Failed to build generated file: %v\n", err)
}
}
func testBuild(tablesFile string, data []byte, skipTests bool) {
dir, err := os.MkdirTemp("", "strcase.*")
if err != nil {
log.Panic(err)
}
tables := filepath.Join(dir, filepath.Base(tablesFile))
overlay := filepath.Join(dir, "overlay.json")