-
Notifications
You must be signed in to change notification settings - Fork 0
/
gdf.go
81 lines (73 loc) · 1.36 KB
/
gdf.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
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type GDFScanner struct {
filename string
nodeFn func(string)
edgeFn func(string)
f *os.File
s *bufio.Scanner
scanning bool
foundNodeHeader bool
foundEdgeHeader bool
}
func NewGDFScanner(filename string, nodeFn, edgeFn func(string)) *GDFScanner {
return &GDFScanner{
filename: filename,
nodeFn: nodeFn,
edgeFn: edgeFn,
}
}
func (g *GDFScanner) IsOpen() bool {
return g.s != nil
}
func (g *GDFScanner) Close() error {
err := g.f.Close()
g.s = nil
g.f = nil
return err
}
func (g *GDFScanner) Open() error {
if g.IsOpen() {
if err := g.Close(); err != nil {
return err
}
}
f, err := os.Open(g.filename)
if err != nil {
return err
}
g.f = f
g.s = bufio.NewScanner(f)
g.scanning = true
return nil
}
func (g *GDFScanner) Scan() error {
g.scanning = g.s.Scan()
if !g.scanning {
return g.s.Err()
}
if !g.foundNodeHeader {
if strings.HasPrefix(g.s.Text(), "nodedef>") {
g.foundNodeHeader = true
} else {
return fmt.Errorf("expected gdf nodedef header")
}
} else if !g.foundEdgeHeader {
if strings.HasPrefix(g.s.Text(), "edgedef>") {
g.foundEdgeHeader = true
} else {
g.nodeFn(g.s.Text())
}
} else {
g.edgeFn(g.s.Text())
}
return g.s.Err()
}
func (g *GDFScanner) Done() bool {
return !g.scanning
}