-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfts-lmdb.go
1793 lines (1667 loc) · 43.4 KB
/
fts-lmdb.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
package main
import (
"bufio"
"encoding/hex"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/AskAlexSharov/lmdb-go/lmdb"
)
/*
* GRAMS
KEY IS THE GRAM
VALUE IS AN ARRAY OF 4-byte OIDs
* OBJECTS
KEY IS THE OID
VALUE IS [len][name][len][data][gram...]
* NAMES
KEY IS THE NAME
VALUE IS THE 4-byte OID
* COMPRESSED NUMBERS THAT COMPARE LEXICOGRAPHICALLY
7 bits (1 byte): 0xxxxxxx
12 bits (2 bytes): 1000xxxx X
20 bits (3 bytes): 1001xxxx X X
28 bits (4 bytes): 1010xxxx X X X
36 bits (5 bytes): 1011xxxx X X X X
44 bits (6 bytes): 1100xxxx X X X X X
52 bits (7 bytes): 1101xxxx X X X X X X
60 bits (8 bytes): 1110xxxx X X X X X X X
64 bits (9 bytes): 1111---- X X X X X X X X
*/
const (
// map_size 5GB max
mapSize = 1024 * 1024 * 1024 * 10
dbs = 10 // objects, names, grams
gramSize = 2 // bytes
maxFileIDBytes = 65536 * 2 // number of bytes in a list of all file ids
maxInt = int(^uint(0) >> 1)
null64 = 0xFFFFFFFFFFFFFFFF
groupStart = ""
lineFormat = "%[6]s:%[2]d:%[5]s\n"
fuzzyLineFormat = "%[6]s:%[2]d:%4.1[4]f%%:%[5]s\n"
groupEnd = ""
sexpGroupStart = ""
infoSexpFormat = "(:filename \"%[6]s\" :line %[2]d :offset %[3]d :text \"%[5]s :char-offset %[1]d\")\n"
sexpFormat = "(:filename \"%[6]s\" :line %[2]d :offset %[3]d :text \"%[5]s\" :char-offset %[1]d :percent %[4]f)\n"
sexpGroupEnd = "\n"
)
const (
valid = iota
deleted
)
var groupValidity = []string{"valid", "changed", "deleted"}
var systemID = []byte{0}
type oidList [9][]byte
type chunk struct {
gid uint64
data []byte
gramCount uint16
}
type groupStruct struct {
groupName string
oidCount uint64
lastChanged time.Time
validity byte
org bool
}
type myBuf struct {
bytes []byte
}
type chunkInfo struct {
oid uint64
start int
line int
chunk string
match float64
original *chunk
}
type lmdbConfigStruct struct {
cmd string // arg 1
args []string // args 2 - N-1
db string // arg N
env *lmdb.Env
gramKeyBuf []byte
gramBuf []byte
txn *lmdb.Txn
chunkDb lmdb.DBI
groupDb lmdb.DBI
groupNameDb lmdb.DBI
gramDb lmdb.DBI
scratchBuf *myBuf
dirty bool
dirtyGroup *groupStruct
dirtyGroupGid uint64
dirtyName bool
dirtyGrams map[gram]*oidList
oidBuf []byte
input *bufio.Reader
data []byte
// persisted values
nextOID uint64
nextGID uint64
freeOids []byte // compressed oids
freeGids []byte // compressed oids
//options
autoupdate bool
partial bool
limit int
org bool
sexp bool
gramSize int
delimiter string
gramHex bool
gramDec bool
dataHex bool
dataString string
grams bool
groups bool
filter string
file bool
chunks bool
candidates bool
separate bool
numbers bool
compression string
force bool
test bool
fuzzy float64
format string
startFormat string
endFormat string
sort bool
}
type searchContext struct {
cfg *lmdbConfigStruct
groups []string
groupStructs map[string]*groupStruct
gids map[string]uint64
hits map[uint64]map[uint64]*chunk
badFiles map[string]string
deletedGroups map[uint64]struct{}
groupsByGid map[uint64]*groupStruct
fuzzyMatches map[uint64]float64
reg *regexp.Regexp
success bool
fileChunkArgs map[uint64]map[uint64][]int // group->chunk->args-to-test
}
var lmdbConfig lmdbConfigStruct
func runLmdb() bool {
if len(os.Args) == 1 {
usage()
}
if cmds[os.Args[1]] == nil {return false}
cfg := &lmdbConfig
cfg.scratchBuf = new(myBuf)
cfg.gramBuf = (&[3]byte{})[:]
cfg.gramKeyBuf = (&[2]byte{})[:]
cfg.db = flag.Args()[0]
cfg.cmd = os.Args[1]
cfg.args = flag.Args()[1:]
cfg.oidBuf = make([]byte, 1024)
if cfg.sexp {
if cfg.format == lineFormat {
cfg.format = sexpFormat
}
if cfg.startFormat == groupStart {
cfg.startFormat = sexpGroupStart
}
if cfg.format == groupEnd {
cfg.endFormat = sexpGroupEnd
}
} else if cfg.fuzzy > 0 && cfg.format == lineFormat {
cfg.format = fuzzyLineFormat
}
if cfg.cmd != "create" && cfg.cmd != "grams" {
_, err := os.Stat(cfg.db)
if err != nil {
exitError(fmt.Sprintf("%s: DATABASE %s DOES NOT EXIST", cfg.cmd, cfg.db), ERROR_DB_MISSING)
}
}
cfg.clean()
cmds[cfg.cmd](cfg)
return true
}
func (cfg *lmdbConfigStruct) numBytes(n uint64) []byte {
cfg.scratchBuf.reset()
cfg.scratchBuf.putNum(n)
return cfg.scratchBuf.bytes
}
func (cfg *lmdbConfigStruct) open(write bool) {
flags := uint(lmdb.NoSubdir)
env, err := lmdb.NewEnv()
check(err)
check(env.SetMapSize(mapSize))
check(env.SetMaxDBs(dbs))
cfg.env = env
if !write {
flags |= lmdb.Readonly
}
err = env.Open(cfg.db, flags, 0644)
check(err)
if cfg.cmd == "create" {
cfg.dirty = true
} else {
cfg.view(func() {
cfg.load()
})
}
}
func cmdInfo(cfg *lmdbConfigStruct) {
if len(cfg.args) > 1 {
fmt.Fprintf(os.Stderr, "Too many arguments: %s\n", strings.Join(os.Args[1:], " "))
usage()
}
cfg.open(false)
defer cfg.env.Close()
cfg.view(func() {
if len(cfg.args) == 0 {
cfg.totalInfo()
} else if len(cfg.args) == 1 {
cfg.groupInfo()
}
})
}
func (cfg *lmdbConfigStruct) totalInfo() {
if cfg.groups {
cfg.iterate(cfg.groupNameDb, func(cur *lmdb.Cursor, k []byte, v []byte) {
printGroupInfo(cfg.getGroupWithGidBytes(v))
})
return
}
groups := int(cfg.stat(cfg.groupDb).Entries)
groupNames := cfg.stat(cfg.groupNameDb).Entries
chunks := float64(cfg.stat(cfg.chunkDb).Entries)
gramTot := cfg.stat(cfg.gramDb).Entries
gramTot--
staleGroups := map[string]string{}
staleGroupNames := []string{}
deletedGroups := map[uint64]struct{}{}
deletedChunks := 0
cfg.iterate(cfg.groupDb, func(cur *lmdb.Cursor, k, v []byte) {
gid, _ := getNumOrPanic(k)
group := decodeGroup(v)
if group.validity == deleted {
deletedGroups[gid] = member
return
}
stat, err := os.Stat(group.groupName)
if os.IsNotExist(err) {
staleGroups[group.groupName] = "File %s does not exist"
} else if err != nil {
staleGroups[group.groupName] = "Cannot open file %s"
} else if stat.ModTime().After(group.lastChanged) {
staleGroups[group.groupName] = "File %s has changes"
}
})
cfg.iterate(cfg.chunkDb, func(cur *lmdb.Cursor, k, v []byte) {
chunk := decodeChunk(v)
if _, deleted := deletedGroups[chunk.gid]; deleted {
deletedChunks++
}
})
groups -= len(deletedGroups)
groups -= len(staleGroups)
chunks -= float64(deletedChunks)
fmt.Printf("%-15s %d\n", "Group names:", groupNames)
fmt.Printf("%-15s %d\n", "Groups:", groups)
fmt.Printf("%-15s %d\n", "Deleted groups:", len(deletedGroups))
fmt.Printf("%-15s %d\n", "Bad groups:", len(staleGroups))
fmt.Printf("%-15s %d\n", "Chunks:", int64(chunks))
fmt.Printf("%-15s %d\n", "Deleted chunks:", deletedChunks)
fmt.Printf("%-15s %d\n", "Grams:", gramTot)
if len(staleGroups) > 0 {
for group := range staleGroups {
staleGroupNames = append(staleGroupNames, group)
}
sort.Strings(staleGroupNames)
for _, group := range staleGroupNames {
fmt.Fprintf(os.Stderr, staleGroups[group]+"\n", group)
}
}
if cfg.grams {
cfg.displayGrams(chunks)
}
}
func (cfg *lmdbConfigStruct) displayGrams(chunks float64) {
maxOids := 0
minOids := int(maxInt)
amounts := []float64{
0.99,
0.95,
0.90,
0.80,
0.75,
0.70,
0.30,
0.20,
0.10,
0.05,
0.01,
0.001,
0.0001,
0.00001,
0.000001,
}
coverage := map[float64]int{}
for _, amt := range amounts {
coverage[amt] = 0
}
totalBytes, chunkBytes, gramBytes := 0, 0, 0
cfg.iterate(cfg.chunkDb, func(cur *lmdb.Cursor, k, v []byte) {
totalBytes += len(k) + len(v)
chunkBytes += len(k) + len(v)
})
first := true
cfg.iterate(cfg.gramDb, func(cur *lmdb.Cursor, k, v []byte) {
if first {
first = false
return
}
oids := oidListFor(v)
totalBytes += len(k) + len(v)
gramBytes += len(k) + len(v)
oidTot := oids.totalOids()
if oidTot < minOids {
minOids = oidTot
}
if oidTot > maxOids {
maxOids = oidTot
}
for amt := range coverage {
if float64(oidTot)/float64(chunks) <= amt {
coverage[amt]++
}
}
})
if minOids == maxInt {
minOids = 0
}
fmt.Printf("total bytes: %d\n", totalBytes)
fmt.Printf("chunk bytes: %d\n", chunkBytes)
fmt.Printf("gram bytes: %d\n", gramBytes)
fmt.Printf("max oids: %d\n", maxOids)
fmt.Printf("min oids: %d\n", minOids)
for _, amt := range amounts {
fmt.Printf("%5d grams appear in %7.4f%% or fewer chunks\n", coverage[amt], 100*amt)
}
}
func (cfg *lmdbConfigStruct) groupInfo() {
_, group := cfg.getGroup(cfg.groupName())
if group == nil {
exitError(fmt.Sprintf("NO GROUP %s\n", cfg.groupName()), ERROR_FILE_NOT_IN_DB)
}
if !printGroupInfo(group) {return}
if cfg.chunks {
if cfg.format == sexpFormat {
cfg.format = infoSexpFormat
}
contents, err := ioutil.ReadFile(group.groupName)
if os.IsNotExist(err) {
exitError(fmt.Sprintf("File does not exist: %s", group.groupName), ERROR_FILE_MISSING)
} else if err != nil {
exitError(fmt.Sprintf("Could not read file: %s", group.groupName), ERROR_FILE_UNREADABLE)
}
str := string(contents)
runeOffset := 0
printf(cfg.startFormat, group.groupName)
if group.org {
prev := 0
forParts(str, func(line, typ, start, end int) {
runeOffset += len([]rune(str[prev:start]))
fmt.Printf(cfg.format, runeOffset+1, line, 0, 0.0, escape(str[start:end]), group.groupName)
prev = start
})
} else {
input := bufio.NewReader(strings.NewReader(str))
pos := 0
for lineNo := 1; ; lineNo++ {
line, err := readLine(input)
if err == io.EOF {break}
check(err)
runes := []rune(line)
lineLen := len(line)
if lineLen > 0 && line[lineLen-1] == '\n' {
line = line[:lineLen-1]
}
fmt.Printf(cfg.format, runeOffset+1, line, 0, 0.0, escape(line), group.groupName)
pos += lineLen
runeOffset += len(runes)
}
}
printf(cfg.endFormat, group.groupName)
}
}
func printGroupInfo(group *groupStruct) bool {
if group == nil {return false}
valid := false
fmt.Printf("%s", group.groupName)
if group.org {
fmt.Print(" org-mode")
}
stat, err := os.Stat(group.groupName)
if os.IsNotExist(err) {
fmt.Print(" DELETED")
} else if err != nil {
fmt.Print(" NOT AVAILABLE")
} else if stat.ModTime().After(group.lastChanged) {
fmt.Print(" CHANGED")
} else {
valid = true
}
fmt.Println()
return valid
}
func (cfg *lmdbConfigStruct) stat(db lmdb.DBI) *lmdb.Stat {
stat, err := cfg.txn.Stat(db)
check(err)
return stat
}
func cmdCreate(cfg *lmdbConfigStruct) {
if len(cfg.args) != 0 {
fmt.Fprintf(os.Stderr, "Too many arguments: %s\n", strings.Join(os.Args[1:], " "))
usage()
}
cfg.open(true)
defer cfg.env.Close()
cfg.env.Update(func(txn *lmdb.Txn) error {
cfg.runTxn(txn, lmdb.Create, func() {
cfg.store()
})
return nil
})
}
func (cfg *lmdbConfigStruct) groupName() string {
return cfg.args[0]
}
func cmdChunk(cfg *lmdbConfigStruct) {
if len(cfg.args) != 2 {
fmt.Fprintf(os.Stderr, "Wrong number of arguments: %s\n", strings.Join(os.Args[1:], " "))
usage()
}
cfg.open(true)
defer cfg.env.Close()
if cfg.dataHex {
bytes, err := hex.DecodeString(cfg.dataString)
check(err)
cfg.data = bytes
} else {
cfg.data = []byte(cfg.dataString)
}
cfg.update(func() {
oid, d := cfg.initChunk()
if cfg.gramHex {
grams := make([]byte, len(cfg.args[1])/2)
_, err := hex.Decode(grams, []byte(cfg.args[1]))
check(err)
for i := 0; i < len(grams); i += 2 {
cfg.addGramEntry(gram((int(grams[i])<<8)|int(grams[i+1])), oid, d)
}
} else {
grams := strings.Split(cfg.args[1], cfg.delimiter)
for _, grm := range grams {
cfg.addGramEntry(gramForUnicode(grm), oid, d)
}
}
cfg.putChunk(oid, d)
})
}
func cmdInput(cfg *lmdbConfigStruct) {
if len(cfg.args) == 0 { // DATABASE and at least one GROUP
fmt.Fprintf(os.Stderr, "Too many arguments: %s\n", strings.Join(os.Args[1:], " "))
usage()
}
cfg.open(true)
defer cfg.env.Close()
cfg.update(func() {
for len(cfg.args) > 0 {
cfg.index(cfg.args[0])
cfg.storeDirtyGroup()
cfg.args = cfg.args[1:]
}
})
}
func (cfg *lmdbConfigStruct) index(group string) {
if cfg.org {
cfg.indexOrg(group)
} else {
cfg.indexLines(group)
}
}
func (cfg *lmdbConfigStruct) openInputFile(group string) (bool, time.Time) {
stat, err := os.Stat(group)
check(err)
date := stat.ModTime()
_, grp := cfg.getGroup(group)
if grp != nil && grp.lastChanged.Equal(date) {return false, time.Now()}
cfg.deleteGroupByName(group)
input, err := os.OpenFile(group, os.O_RDONLY, 0)
check(err)
cfg.input = bufio.NewReader(input)
return true, date
}
func (cfg *lmdbConfigStruct) indexOrg(group string) {
open, date := cfg.openInputFile(group)
if !open {return}
contents, err := ioutil.ReadAll(cfg.input)
check(err)
str := string(contents)
runeOffset := 0
prev := 0
forParts(str, func(line, typ, start, end int) {
g := grams(false, str[start:end])
if len(g) > 0 {
runeOffset += len([]rune(str[prev:start]))
runeLen := len([]rune(str[start:end]))
buf := new(myBuf)
buf.putNum(uint64(line))
buf.putNum(uint64(runeOffset))
buf.putNum(uint64(runeLen))
buf.putNum(uint64(start))
buf.putNum(uint64(end - start))
runeOffset += runeLen
prev = end
cfg.data = buf.bytes
oid, d := cfg.initChunk() // make chunk for chunk
for grm := range g {
cfg.addGramEntry(grm, oid, d)
}
cfg.putChunk(oid, d)
}
})
cfg.dirtyGroup.lastChanged = date
}
func (cfg *lmdbConfigStruct) indexLines(group string) {
open, date := cfg.openInputFile(group)
if !open {return}
pos := 0
runeOffset := 0
for lineNo := 1; ; lineNo++ {
line, err := readLine(cfg.input)
if err == io.EOF {break}
runes := []rune(line)
buf := new(myBuf)
buf.putNum(uint64(lineNo))
buf.putNum(uint64(runeOffset))
buf.putNum(uint64(len(runes)))
buf.putNum(uint64(pos))
buf.putNum(uint64(len(line)))
runeOffset += len(runes)
cfg.data = buf.bytes
oid, d := cfg.initChunk() // make chunk for line
for grm := range grams(false, line) {
cfg.addGramEntry(grm, oid, d)
}
cfg.putChunk(oid, d)
pos += len(line)
}
cfg.dirtyGroup.lastChanged = date
}
func readLine(reader *bufio.Reader) (string, error) {
line, err := reader.ReadBytes('\n')
if err == io.EOF {return "", err}
check(err)
return string(line), nil
}
func (cfg *lmdbConfigStruct) initChunk() ([]byte, *chunk) {
d := new(chunk)
d.data = cfg.data
gid, group := cfg.getGroup(cfg.groupName())
if group == nil {
gid, group = cfg.createGroup()
}
d.gid = gid
oid := cfg.getNewOid()
cfg.dirtyGroupGid = gid
cfg.dirtyGroup = group
group.oidCount++
return oid, d
}
//add the OID to the chunkBuf, mark it dirty, and add the gram to the chunk buf, returning the chunk buf
func (cfg *lmdbConfigStruct) addGramEntry(grm gram, oid []byte, d *chunk) {
oids := cfg.getGram(grm)
if oids == nil { // found an existing gram
oids = new(oidList)
}
l := len(oid)
oids[l-1] = cat(oids[l-1], oid)
cfg.dirtyGrams[grm] = oids
d.gramCount++
}
func cat(bytes1 []byte, bytes2 []byte) []byte {
buf := newBuf(bytes1)
buf.append(bytes2)
return buf.bytes
}
func newBuf(bytes []byte) *myBuf {
return &myBuf{bytes}
}
func (buf *myBuf) reset() {
buf.bytes = buf.bytes[:0]
}
func (buf *myBuf) append(bytes []byte) {
copy(buf.next(len(bytes)), bytes)
}
func (buf *myBuf) skip(n int) {
buf.grow(n)
buf.bytes = buf.bytes[:len(buf.bytes)+n]
}
func (buf *myBuf) next(n int) []byte {
l := len(buf.bytes)
buf.skip(n)
return buf.bytes[l : l+n]
}
func (buf *myBuf) rest(min int) []byte {
buf.grow(min)
return buf.bytes[len(buf.bytes):cap(buf.bytes)]
}
func (buf *myBuf) grow(n int) {
if cap(buf.bytes)-len(buf.bytes) < n {
l := cap(buf.bytes)
if l == 0 {
l = 1
}
target := len(buf.bytes) + n
for l < target {
l <<= 1
}
old := buf.bytes
buf.bytes = make([]byte, len(buf.bytes), l)
copy(buf.bytes, old)
}
}
func (buf *myBuf) len() int {
return len(buf.bytes)
}
func (buf *myBuf) putCountedBytes(bytes []byte) {
buf.putNum(uint64(len(bytes)))
buf.append(bytes)
}
func (buf *myBuf) putNum(n uint64) {
r1 := buf.rest(9)
r2, _ := putNum(n, r1)
buf.skip(len(r1) - len(r2))
}
func (buf *myBuf) appendOids(oids *oidList) {
for i := 0; i < 9; i++ {
buf.putNum(uint64(len(oids[i]) / (i + 1)))
}
for i := 0; i < 9; i++ {
buf.append(oids[i])
}
}
func (cfg *lmdbConfigStruct) getOidList(db lmdb.DBI, key []byte) *oidList {
return oidListFor(cfg.get(db, key))
}
func oidListFor(bytes []byte) *oidList {
if len(bytes) == 0 {return nil}
oids := new(oidList)
var rawOids uint64
start := 0
lengths := [9]int{}
for i := 0; i < 9; i++ {
rawOids, bytes = getNumOrPanic(bytes)
l := int(rawOids)
lengths[i] = l
}
for i := 0; i < 9; i++ {
l := lengths[i]
next := start + l*(i+1)
if next-start > 0 {
oids[i] = bytes[start:next:next]
} else {
oids[i] = bytes[0:0:0]
}
start = next
}
return oids
}
func (oids *oidList) total() int {
total := 9
for i := 0; i < 9; i++ {
total += len(oids[i])
}
return total
}
func (oids *oidList) totalOids() int {
total := 0
for i := 0; i < 9; i++ {
total += len(oids[i]) / (i + 1)
}
return total
}
func (oids *oidList) allOids() map[uint64]struct{} {
result := make(map[uint64]struct{})
for _, bytes := range oids {
for len(bytes) > 0 {
var n uint64
n, bytes = getNumOrPanic(bytes)
result[n] = member
}
}
return result
}
func (oids *oidList) append(bytes []byte) {
sz := len(bytes)
oids[sz-1] = cat(oids[sz-1], bytes)
}
func (cfg *lmdbConfigStruct) gramKeyForGram(gram gram) []byte {
cfg.gramKeyBuf[0] = byte(gram >> 8)
cfg.gramKeyBuf[1] = byte(gram & 0xFF)
return cfg.gramKeyBuf
}
func (cfg *lmdbConfigStruct) gramFor(str string) gram {
if cfg.gramHex {
digit1, err := strconv.ParseInt(str[:2], 16, 8)
check(err)
digit2, err := strconv.ParseInt(str[2:4], 16, 8)
check(err)
return gram((digit1 << 8) | digit2)
} else if cfg.gramDec {
num, err := strconv.Atoi(str)
check(err)
return gram(num)
}
return gramForUnicode(str)
}
func (cfg *lmdbConfigStruct) oidKey(oid uint64) []byte {
return cfg.numBytes(oid)
}
func (cfg *lmdbConfigStruct) load() {
buf := cfg.get(cfg.gramDb, systemID)
if buf != nil {
oid, rest := getNumOrPanic(buf)
cfg.nextOID = oid
oid, rest = getNumOrPanic(rest)
cfg.nextGID = oid
free, rest := getCountedBytes(rest)
cfg.freeOids = free
free, _ = getCountedBytes(rest)
cfg.freeGids = free
}
}
func (cfg *lmdbConfigStruct) store() {
buf := new(myBuf)
buf.putNum(cfg.nextOID)
buf.putNum(cfg.nextGID)
buf.putCountedBytes(cfg.freeOids)
buf.putCountedBytes(cfg.freeGids)
cfg.put(cfg.gramDb, systemID, buf.bytes)
}
func (cfg *lmdbConfigStruct) storeDirty() {
if cfg.dirty {
cfg.store()
}
cfg.storeDirtyGroup()
if len(cfg.dirtyGrams) > 0 {
for grm, oids := range cfg.dirtyGrams {
cfg.putGram(cfg.gramKeyForGram(grm), oids)
}
}
cfg.clean()
}
func (cfg *lmdbConfigStruct) storeDirtyGroup() {
if cfg.dirtyGroup != nil {
cfg.putGroup(cfg.dirtyGroupGid, cfg.dirtyGroup)
if cfg.dirtyName {
buf := new(myBuf)
buf.putNum(cfg.dirtyGroupGid)
cfg.put(cfg.groupNameDb, []byte(cfg.dirtyGroup.groupName), buf.bytes)
}
cfg.dirtyGroup = nil
cfg.dirtyName = false
}
}
func (cfg *lmdbConfigStruct) clean() {
cfg.dirty = false
cfg.dirtyGroup = nil
cfg.dirtyName = false
cfg.dirtyGrams = make(map[gram]*oidList)
}
func (cfg *lmdbConfigStruct) getNewOid() []byte {
var oid uint64
if len(cfg.freeOids) != 0 {
var rest []byte
oid, rest = getNumOrPanic(cfg.freeOids)
cfg.freeOids = rest
} else {
oid = cfg.nextOID
cfg.nextOID++
}
cfg.dirty = true
return cfg.oidKey(oid)
}
func cmdGrams(cfg *lmdbConfigStruct) {
if len(cfg.args) != 0 {
fmt.Fprintf(os.Stderr, "Too many arguments: %s\n", strings.Join(os.Args[1:], " "))
usage()
}
first := true
args := []string{cfg.db}
for grm := range grams(cfg.partial, append(args, cfg.args...)...) { // db is actually the phrase
if first {
first = false
} else {
fmt.Print(" ")
}
if cfg.gramHex {
fmt.Printf("%s%s",
strconv.FormatUint(uint64(grm>>8), 16),
strconv.FormatUint(uint64(grm&0xFF), 16))
} else {
fmt.Printf("%s", gramString(grm))
}
}
fmt.Println()
}
func cmdDelete(cfg *lmdbConfigStruct) {
if len(cfg.args) != 1 {
fmt.Fprintf(os.Stderr, "Wrong number of arguments: %s\n", strings.Join(os.Args[1:], " "))
usage()
}
cfg.open(true)
defer cfg.env.Close()
cfg.update(func() {
cfg.deleteGroup()
})
}
func (cfg *lmdbConfigStruct) iterate(dbi lmdb.DBI, code func(cur *lmdb.Cursor, key, value []byte)) {
cur, err := cfg.txn.OpenCursor(dbi)
check(err)
k, v, err := cur.Get(nil, nil, lmdb.First)
for err == nil {
code(cur, k, v)
k, v, err = cur.Get(nil, nil, lmdb.Next)
}
if err != nil && !lmdb.IsNotFound(err) {
check(err)
}
cur.Close()
}
func cmdCompact(cfg *lmdbConfigStruct) {
if len(cfg.args) != 0 {
fmt.Fprintf(os.Stderr, "Too many arguments: %s\n", strings.Join(os.Args[1:], " "))
usage()
}
cfg.open(true)
defer cfg.env.Close()
cfg.update(func() {
deletedGroups := map[uint64]struct{}{}
deletedChunks := map[uint64]struct{}{}
cfg.iterate(cfg.groupDb, func(cur *lmdb.Cursor, k, v []byte) {
gid, _ := getNumOrPanic(k)
group := decodeGroup(v)
if group.validity == deleted {
deletedGroups[gid] = member
cur.Del(0)
buf := &myBuf{cfg.freeGids}
buf.putNum(gid)
cfg.freeGids = buf.bytes
cfg.dirty = true
}
})
cfg.iterate(cfg.chunkDb, func(cur *lmdb.Cursor, k, v []byte) {
did, _ := getNumOrPanic(k)
chunk := decodeChunk(v)
if _, exists := deletedGroups[chunk.gid]; exists {
deletedChunks[did] = member
cur.Del(0)
buf := &myBuf{cfg.freeOids}
buf.putNum(did)
cfg.freeOids = buf.bytes
cfg.dirty = true
}
})
first := true
cfg.iterate(cfg.gramDb, func(cur *lmdb.Cursor, k, v []byte) {
if first { // skip system record
first = false
return
}
oids := oidListFor(v)
dirty := false
for i, bytes := range oids {
newBytes := new(myBuf)
for len(bytes) > 0 {
did, rest := getNumOrPanic(bytes)
if _, exists := deletedChunks[did]; exists {
dirty = true
} else {
newBytes.append(bytes[:len(bytes)-len(rest)])
}
bytes = rest
}
oids[i] = newBytes.bytes
}
if dirty {
if oids.totalOids() == 0 {
cur.Del(0)
} else {
buf := new(myBuf)
buf.appendOids(oids)
cur.Put(k, buf.bytes, lmdb.Current)
}
}
})
})
}
func cmdUpdate(cfg *lmdbConfigStruct) {
if len(cfg.args) != 0 {
fmt.Fprintf(os.Stderr, "Too many arguments: %s\n", strings.Join(os.Args[1:], " "))
usage()
}
cfg.open(true)
defer cfg.env.Close()
cfg.update(func() {
deleteGroups := map[string]struct{}{}
updateGroups := map[string]struct{}{}
groupOrg := map[string]bool{}
cfg.iterate(cfg.groupDb, func(cur *lmdb.Cursor, k, v []byte) {
group := decodeGroup(v)
stat, err := os.Stat(group.groupName)