-
Notifications
You must be signed in to change notification settings - Fork 1
/
database.go
102 lines (82 loc) · 2.2 KB
/
database.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
package libgenders
import (
"bufio"
"fmt"
"os"
"github.com/ryanmoran/libgenders/internal"
)
const DefaultGendersFilepath = "/etc/genders"
type Database struct {
nodes []Node
names map[string]int
attrs map[string]internal.Set
attrvals map[string]internal.Set
indices internal.Set
}
func NewDatabase(path string) (Database, error) {
file, err := os.Open(path)
if err != nil {
return Database{}, err
}
defer file.Close()
database := Database{
nodes: []Node{},
names: make(map[string]int),
attrs: make(map[string]internal.Set),
attrvals: make(map[string]internal.Set),
}
scanner := bufio.NewScanner(file)
var parser internal.Parser
for scanner.Scan() {
line := scanner.Text()
nodes, err := parser.Parse(line)
if err != nil {
return Database{}, fmt.Errorf("failed to parse database file: %w", err)
}
for _, node := range nodes {
if index, ok := database.names[node.Name]; ok {
database.nodes[index].mergeAttributes(node.Attributes)
continue
}
database.nodes = append(database.nodes, Node(node))
index := len(database.nodes) - 1
database.names[node.Name] = index
}
}
database.indices = make(internal.Set, len(database.nodes))
for index, node := range database.nodes {
database.indices[index] = index
for key, value := range node.Attributes {
database.attrs[key] = append(database.attrs[key], index)
if value != "" {
keyval := fmt.Sprintf("%s=%s", key, value)
database.attrvals[keyval] = append(database.attrvals[keyval], index)
}
}
}
if err := scanner.Err(); err != nil {
return Database{}, fmt.Errorf("failed to scan database file: %w", err)
}
return database, nil
}
func (d Database) GetNodes() []Node {
return d.nodes
}
func (d Database) GetNodeAttr(name, attr string) (string, bool) {
if index, ok := d.names[name]; ok {
val, ok := d.nodes[index].Attributes[attr]
return val, ok
}
return "", false
}
func (d Database) Query(query string) ([]Node, error) {
tokens, err := internal.Tokenize(query)
if err != nil {
return nil, err
}
var nodes []Node
for _, index := range internal.ParseQuery(tokens).Evaluate(d.attrs, d.attrvals, d.indices) {
nodes = append(nodes, d.nodes[index])
}
return nodes, nil
}